开发者

PHP sql with foreach loop variable problem

开发者 https://www.devze.com 2023-01-03 00:04 出处:网络
This is really getting frustrating. I have a text file that I\'m reading for a list of part numbers that goes into an array. I\'m using the following foreach function to search a database for matching

This is really getting frustrating. I have a text file that I'm reading for a list of part numbers that goes into an array. I'm using the following foreach function to search a database for matching numbers.

$file = file('parts_array.txt');

foreach ($file as $newPart)
{
    $sql = "SELECT products_sku FROM products WHERE products_sku='" . $newPart . "'";
    $rs = mysql_query($sql);
    $num_rows = mysql_num_rows($rs);

    echo $num_rows;
    echo "<br />";
}

The problem is I'm getting 0 rows returned from mysql_num_rows. I can type the sql statement without the variable and it works perfectly. I can even echo out the开发者_开发百科 sql statement from this script, copy and paste the statement from the browser and it works. But, for some reason I'm not getting any records when I'm using the variable. I've used variables in sql statements tons of times, but this really has me stumped.


  1. Try trimming and mysql_real_escape_string on your variable.
  2. Check the source code of what is being echoed out and try to copy and paste that into PHPMyAdmin or something similar.


file includes newlines in the array elements. This may explain why it works when you copy the browser output but not in the script. You can try either:

$file = file('parts_array.txt', FILE_IGNORE_NEW_LINES);

or:

$sql = "SELECT products_sku FROM products WHERE products_sku='" . trim($newPart) . "'";

Note: Even though you're importing from a file of your own making, you can never be 100% sure that inject-able data hasn't been inserted into it. You should make sure to properly escape any data with mysql_real_escape_string. Even better would be using PDO prepared statements instead.


Obviously your code does something different than you expect. Running a successful query, for one: you don't check the return value of the mysql_query call, so you cannot be sure the query executed ok.

My idea:

  1. dump your sql statement from the foreach
  2. check the return code of the mysql_query


What does your parts_array.txt file look like? Do SKU numbers contain the ' character?

Can you please try this:

$file = file('parts_array.txt');

foreach ($file as $line_num => $line)
{
    $sql = "SELECT products_sku FROM products WHERE products_sku='$line'";
    echo $sql;
    $rs = mysql_query($sql);
    $num_rows = mysql_num_rows($rs);

    echo $num_rows;
    echo "<br />";
}


You might want to check for a mysql_error. It sounds like you've already verified the variable and have copied the query into a database interface like PHPMyAdmin or Query Browser, but if you haven't, I would recommend that.
After, verify that a very basic query will work, like SELECT * FROM Products. That will tell you if there is a problem outside of the query.

Overall, I would say the strategy would be to break the problem down into possible problem areas, like database, connection, query, errors, etc. Try to eliminate them one at a time until the problem is apparent. In other words, list the possibilities and cross them off one at a time.

I've encountered problems like this before; the trick is usually to start echoing things until you see the problem, and don't work off of assumptions.


I know this is pretty old now- but I'd like to help out others who may also be facing a similar problem with SQL statements that need to contain a potentially infinite number generated search parameters.

The code in the askers question is perfectly valid (for the avoidance of doubt) [see below]:

$file = file('parts_array.txt');

foreach ($file as $newPart)
{
    $sql = "SELECT products_sku FROM products WHERE products_sku='" . $newPart . "'";
    $rs = mysql_query($sql);
    $num_rows = mysql_num_rows($rs);

echo $num_rows; 
echo "<br />";

}

Their problem lies in the formatting of their text file ('parts_array.txt'). The root cause of the issue can be tracked down by dumping the information sent back by the server. Alternatively- they can try writing an SQL query in PHPMyAdmin and pasting in some or all of the data in their text file. MySQL will happily torment them until they find the problem.

For those trying to implement a variable based SQL query- the above is the way to go. If you are trying to get data from an array, instead of a text file- you could do something like the following:

foreach ($array as $array_stuff)
{
    $search_query = "SELECT * FROM table WHERE id='" . $array_stuff . "'";
    $rs = mysqli_query($database_connection, $search_query);
    $table_rows = mysqli_fetch_assoc($rs);

    echo $table_rows['id']." - ".$table_rows['desc'];
    echo "<br />";
}

/* free result set */
mysqli_free_result($rs);

This would output your data like this:

1001 - data 1
1002 - data 2
1003 - data 3

Note: The use of "mysql" functions are actively discouraged by MySQL. Therefore the second example I have given above is more up-to-date with current technologies, and using "mysqli" instead.

Also important

If you are here from a Google search as a result of trying to get data from a database, using a complex SQL query- you might have already tried to do something like the example below (or be considering it).

Do not attempt to write a variable based SQL query as per the example below. It won't work and will be incredibly frustrating.

Based on recent technological advancements- the second example I have given (using "mysqli") is the correct way (if there is one) to achieve this.

Bad example:

if ($search_result = mysqli_query($dbh1, "SELECT FROM sic_codes WHERE id = (".foreach ($_POST['SIC_Codes'] as $sic_codes) {echo "'".$sic_codes."' OR id = '',";})) {
/* fetch associative array */
while ($search_row = mysqli_fetch_assoc($search_result)) {
    echo $row["id"]." - ".$row["desc"]."<br/>";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消