Solved

array and multiple query insert issue

Posted on 2009-05-14
7
431 Views
Last Modified: 2013-12-12
Hello,

For some reason my script is not looping through all my data and inserting product id's and qty's.
Ive used this script 5x before and now im having these issues.
- The cid,cartid,cartdate and active get inserted but no pid's or qty's and the it doesnt loop through and do multiple queries.


DB STRUCTURE:
id,cid,cartid,cartdate,pid,qty,active
Mysql 5, php 5, apache2


Thanks
if (isset($_POST['add'])) {
        $pid = $_POST['pid'];
        $qty = $_POST['qty'];
        $queries = array();
        for ($i = 0; $i < count($pid); $i++) {
            $qty = $_POST['qty'];
            if ($qty[$i] == '0') {
                echo "<meta http-equiv=\"refresh\" content=\"10;url=?c=$_GET[c]\">";
            } else {
                if (!get_magic_quotes_gpc()) {
                    $pid[$i] = addslashes($pid[$i]);
                    $qty[$i] = addslashes($qty[$i]);
                }
                $queries[] = "('$custid','$cartid','$dateTime','$pid[$i]','$qty[$i]','1')";
            }
            if (count($queries) == '0') {
                # Nothing passed
                echo "<meta http-equiv=\"refresh\" content=\"10;url=?c=$_GET[c]\">";
            }
        }
        $piece1 = implode(", ", $queries);
        $query = "INSERT INTO hb_temp_cart (cid,cartid,cartdate,pid,qty,active) VALUES $piece1";
        $result = mysql_query($query) or die(mysql_error());
        echo "<meta http-equiv=\"refresh\" content=\"3;url=?c=$_GET[c]\">";
    }
 
// php generated form elements
				<input type=\"hidden\" name=\"pid[]\" value=\"$sku\">
				<input type=\"text\" size=\"3\" maxlength=\"3\" onkeypress=\"return isNumberKey(event)\" name=\"qty[]\" value=\"0\" onfocus=\"if(this.value=='0')this.value=''\" onblur=\"if(this.value=='')this.value='0'\">

Open in new window

0
Comment
Question by:krv123
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 8

Expert Comment

by:Bobaran98
ID: 24390768
Summary:  try my code at the bottom of this post.

Details:

You need to fix the following things:
  • your INSERT query isn't actually executed inside the while loop, so that's why you're only getting one insertion
  • you've got your array variables embedded in a string, but I don't think that works... I think you need to concatenate them instead
Those fixes by themselves may get it working for you again.  However, I also have a few other concerns about your code:
  • Your use of the $queries[] array is entirely unnecessary. Just create your $piece1 string in the first place; I don't see any other reason for having unrelated values in an array with one another, especially not when you overwrite that array every time through the loop
  • Inside your loop, your count($queries) conditional will never be true, because count returns an integer, not a string-- and '0' is a string.
  • Even if it did work, it would simply output the same meta tag as the first if statement in the loop, and those two ifs would always be true together or false together
  • By the way, what's the logic behind outputting all those meta tags?
Anyway, try the code below and see if it works for you.

if (isset($_POST['add'])) {
	$pid = $_POST['pid'];
	$qty = $_POST['qty'];
	for ($i = 0; $i < count($pid); $i++) {
		if ($qty[$i] == '0') {
			echo "<meta http-equiv=\"refresh\" content=\"10;url=?c=$_GET[c]\">";
		} else {
			if (!get_magic_quotes_gpc()) {
				$pid[$i] = addslashes($pid[$i]);
				$qty[$i] = addslashes($qty[$i]);
			}
			$query = "INSERT INTO hb_temp_cart (cid,cartid,cartdate,pid,qty,active) VALUES ";
			$query .= "('$custid','$cartid','$dateTime','".$pid[$i]."','".$qty[$i]."','1')";
			mysql_query($query) or die(mysql_error());
		}
	}
}

Open in new window

0
 
LVL 1

Author Comment

by:krv123
ID: 24391214
OK my original script works. However if magic_quotes is turned on it works fine.... if its off it doesnt loop or insert the pid and qty.
This make no sense because i have the code being used in table temp_cart for another site on my local box with the same table information and setup besides the datetime column.
0
 
LVL 8

Expert Comment

by:Bobaran98
ID: 24391260
I don't know what to tell you.  I just know that the code as you posted it above can't possibly insert multiple records because the query execution takes place outside the loop.

Have you tried the code I posted?
0
Don't Cry: How Liquid Web is Ensuring Security

WannaCry is just the start. Read how Liquid Web is protecting itself and its customers against new threats.

 
LVL 1

Author Comment

by:krv123
ID: 24392107
yeah your code did not work.you would get a sql error with your code.

My code works because if you were to do a straight sql multiple insert you do

INSERT INTO table (id,something,somethingelse)VALUES (1,abc,cba),(2,efg,gfe) ## < Insert values


values need to put into an array from the form data then imploded with "," the comma separating the insert values.

0
 
LVL 8

Expert Comment

by:Bobaran98
ID: 24394154
Hmmm, potential quick fix on why your pid and qty values aren't getting written.  Wouldn't those values be integers?  You've got them inside single-quotes, which means you're trying to insert them as strings.  When I try that, it often just fails to import the value.  Try removing your single-quotes.
0
 
LVL 8

Accepted Solution

by:
Bobaran98 earned 500 total points
ID: 24394184
In answer to your last post... about my code... it did not work or would not work?  Did you try it?  What SQL error did you receive?  Because values certainly don't need to be put into an array and imploded.  If you use traditional single-record INSERT statements within the for loop, that would work fine.

If you tell me that your syntax is also effective, I'll take your word for it.  One thing I've learned here on EE is that there are many different ways to do the same thing, and I've not seen the half of them.  Just answering questions is as much a learning experience for me as asking them.  In any case, what I see you doing in your code that is so outside my experience is:
  • setting up a multiple insert query with the syntax you showed in your last post; didn't know you could do that. :-)
  • appending values to $queries[] by doing a simple assignment without an index; as far as I knew, the only two ways to add an array element were to use array_push() or to specify your element (which is easy here, since you're in a loop):
    • array_push($queries,"('$custid','$cartid'...etc...etc...)");
    • $queries[$i] = "('$custid','$cartid'...etc...etc...)";
Tell me, when you say you've used this script 5x before, was it in the same version of PHP?  Sometimes functionality becomes obsolete in a new version.  What about changes... have you made any changes to this code since the last time you used it successfully?  Even the slightest change can have unexpected effects.  I suggest walking through those changes one by one, if there are any.
 
 The fact remains that even though you say your code has worked before, it's not working now... and part of why it's not working is this looping issue.  I'll buy that the MySQL syntax for multiple INSERT is okay.  Maybe you should try using your code with one of the alternative array append methods I showed above.

Final question... do you have error reporting turned on?  If not, you may be receiving helpful error messages that just aren't being displayed.
0
 
LVL 1

Author Comment

by:krv123
ID: 24397483
I put my code in a seperate file and it works fine, must of been something in my coding structure.
Thanks for your help and advice.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

729 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question