Solved

array and multiple query insert issue

Posted on 2009-05-14
7
426 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
  • 4
  • 3
7 Comments
 
LVL 8

Expert Comment

by:Bobaran98
Comment Utility
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
Comment Utility
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
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Author Comment

by:krv123
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now