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.
Try trimming and mysql_real_escape_string on your variable.
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:
dump your sql statement from the foreach
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/>";
}
Related
Please anybody help me. I want to execute php script from mysql database. My plan is so many if(),else if() statement will be execute. I had used eval($row['data']) statement in to while() loop and it's worked. But only first one.not at all.
My code as below.
$conn = mysqli_connect();
$sql = "SELECT * FROM transaction ORDER BY id ASC";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_array($result)){
eval($row['tran_php']);
// echo eval($row['tran_php']);
}
}
Here is only first one does work which one is if(). Do you have any solution to work all about the else if() statement end of the if() statement?
You have ever heared "eval is evil"? Its true. eval is a development nightmare and a good indicator for doing something wrong.
Only a idea. Do not store the PHP code in database. Store it as files, link to it in DB (filename and/or id) and include it by the regular way.
But always remember this can be a security issue if the code comes from users!
The best way is to encapsule everithing by a UI where the user inputs his stuff and PHP handles it for example by a Parser, build by you.
Why there is the need to do it with PHP-Code like you?
This is my MySQL statement, I want to search record by status or description.. this statement works fine in phpMyAdmin, but it is not working in php script.. Any Suggestions Please..
$result = mysqli_query($mysqli,
"SELECT * FROM `statuses`
where statuses.`status` LIKE '%$search%' OR
statuses.`description` LIKE '%$search%'");
I hope you write everything correct but there may be error in how you fetching data. Here are the things you need to check.
check your connection string
If you are retrieving data then use something like below
while($row = $result->fetch_array())
{
echo $row['example_col_name'];
}
You can do one more thing if everything alright store your query to a variable and echo out that one then you will see what query is passing .
Well I've did do my research and I just can't seem to figure this out. So long story short, I'm using something like this:
btw, "(WebsiteInfo)" is just to sensor out my website/database information.
$SQL = new PDO('mysql:dbname=(WebsiteInfo);host=(WebsiteInfo);charset=utf8', '(WebsiteInfo)', '(WebsiteInfo)');
$SQL -> setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$SQL -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Now, that's just currently just to start the database connect up. Which btw is mostly just a copy/paste code I found on this website too which is to prevent MySQL injection. Actually from this link How can I prevent SQL injection in PHP?. If there's anything wrong with it, I wouldn't mind advice or tips. As long as if it makes sense because I just started using databases probably not even a week ago so everything is new to me. Now there's this:
$Exicu = $SQL -> prepare("SELECT `tags` FROM `users` WHERE `user_id` = :a ") -> execute(array( ':a' => 16));
$Exicu is just there, because I have been trying to get the results from the query (if I said that right). Also the 16 is the users ID, but this will change often so that's why 16 isn't just tossed in the prepare statement. I've tried a lot of things but none of them worked. It either didn't work or made the PHP crash.
But anyway, things I already tried for $Exicu is $Exicu->rowCount(), $Exicu->bindParam, a while loop with $row = $Exicu->fetch(), $SQL->query($Exicu)->fetchAll();, a foreach loop with ($Exicu->fetch(PDO::FETCH_ASSOC) as $row), $Exicu->get_result(), echo PDO::query($Exicu);, echo mysql_result($Exicu), and just echo $Exicu. Yes I know, that looks pretty sloppy.
But none of these seemed to work to just show me the tags from the database of the specific user. So that's pretty much what I need help with. There's no problem when I use something like this echo mysql_result( mysql_query("SELECT (etc,etc)") ) but that doesn't have protection from MySQL injections.
I do my PDO queries like this:
$user_id = 16;
$query = $SQL->prepare('SELECT tags FROM users WHERE user_id = :uid');
$query->bindValue(':uid', $user_id, PDO::PARAM_INT);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
echo $row['tags'];
}
This will select data from the database, bind values in it safely and then we echo out the results.
The loop is needed to iterate through every result returned from the query. You can skip the looping part and create a variable like in the while statement, and use $row as an array with your results.
There is a thing called user defined function.
I am wondering why noone on this site ever using them.
For some reason everyone is ready to make a mile long single line of chained methods, instead of clean and concise function call:
$user_id = 16;
$tags = getone('SELECT tags FROM users WHERE user_id = ?',array($user_id));
there are many ways to create such a function. A quick and dirty one
function getone($sql, $data) {
global $SQL;
$stmt = $SQL->prepare($sql);
$stmt->execute($data);
return reset($stmt->fetch());
}
but of course it would be better to make set of functions and put them in a class
I'm trying to get it so that the information retrieved from this query is sorted before be shown onto the page by the messageid, which I have assigned as the primary key. I keep getting this error though:
Warning: krsort() expects parameter 1 to be array, resource given in ...
Here's my code:
<?php
$id = $_SESSION[id];
$messages = #mysql_query("SELECT * FROM messages WHERE receiver='$id'");
$messagecount = mysql_num_rows($messages);
krsort($messages);
if ($messagecount == 0)
{
echo "<br>You have no messages.";
}
else
{
while ($messages2 = mysql_fetch_array($messages))
{
echo "<table width=800 class=\"normaltable\" cellpadding=\"3\" border=\"0\"><tr>
<td class=\"tdmessagesubject\"><b>Subject:</b> " . $messages2['subject'] . "</td>
<td class=\"tdmessagefrom\"><b>From:</b> " . $messages2['sendercallname'] . "</td> </tr>
</table>";
}
}
?>
I thought that $messages was an array but it doesn't seem to be working.
Have a look at the manual page, mysql_query returns a resource, not and array.
And while you're there, read that big red fat warning, the one that says that the mysql_ family of functions is deprecated which among other things mean you should not use them in new code.
I'd also suggest to forget about the more modern mysqli_ successor and skip right away to PDO - it's a modern, well designed API, usable with several database engines and last but not least, it makes working with prepared statements a breeze, and prepared statements are probably the least expensive yet most effective defense against sql injection.
But back to the order of the day: when you want a database resultset to be ordered in some way by far the easiest way is to let the database server sort it, like this:
$messages = #mysql_query("SELECT * FROM messages WHERE receiver='$id' order by messageid");
There are a couple of good reasons why you should let the db sort the data and not try to do it yourself:
that way you're forced to load up the entire resultset in memory, which is inefficient and with big resultsets it can exhaust the memory available to php
if your db is well designed, chances are that the data are already indexed on the column you want to sort on, which means that the server doesn't actually have to sort the data when returning them, making the whole operation a lot faster.
your $messages variable is not an array. to build array of messages from database query you should use:
$result = #mysql_query("SELECT * FROM messages WHERE receiver='$id'");
$messages = array();
while ($message = mysql_fetch_assoc($result)) {
$messages[] = $message;
}
Here you can find an example use of mysql_fetch_assoc: http://php.net/manual/en/function.mysql-fetch-array.php
If you want to order your messages in database query you should use ORDER BY statement. For example:
$result = #mysql_query("SELECT * FROM messages WHERE receiver='$id' ORDER BY id");
Oh man don't use # to suppress errors unless you have a really good reason.
mysql_query returns a resource: the query result. If you want to sort it you need to either pull out every row into an array first or (better solution) use ORDER BY in the query to get your results in sorted order.
I'd like to say first that Mysql is deprecated in PHP, it is recommended to use the new Mysql extension, Mysqli
Then, you have to extract the results from the resource:
$data = array();
while($row = mysql_fetch_row($messages)) $data[] = $row;
I'm trying to loop data from a api and then post these values to a MySQL db.
something like this:
$values = json_decode(file_get_contents("my-json-file"));
$SQL = new mysqli(SQL_HOST, SQL_USER, SQL_PASS, DB_NAME);
$SQL->autocommit(FALSE);
foreach($values As $item)
{
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2.";)";
$SQL->query($query);
if(!$SQL->commit())
{
echo "ERROR ON INSERT: [" . $query . "]<hr/>";
}
}
$SQL->close();
Since the loop is too fast, the SQL can't catch up. (Yea!)
I would then need something like this:
foreach($values As $item)
{
/**** STOP/PAUSE LOOP ****/
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2.";");
$SQL->query($query);
if($SQL->commit())
{
/**** START THE LOOP AGAIN ****/
}
else
{
echo "ERROR ON INSERT: [" . $query . "]<hr/>";
}
}
Or how should I do this the right way?
EDIT: It inserts random posts every time.
EDIT 2: This is just example code. It does escape and all that, and yes the semi colon is wrong here but since so many commented on it i will not change it. This was not the problem in the real case.
I tried to run it on another server and there it worked. The problem was fixed by restarting MAMP.
Firstly, your idea that the loop runs too fast for MySQL to keep up is completely totally wrong. The $SQL->query() call will wait for the MySQL to return a response before proceeding, so the loop won't run any faster than MySQL is responding.
Now onto the actual problem.... your query:
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2.";)";
There's a semi-colon in there at the end, after value2 which is invalid. I guess you intended to type a quote mark there? The semi-colon will be causing all your queries to fail and throw errors.
This may be the cause of your problem but you haven't got any error checking in there, so you won't know. Add some error checking to your code after calling the query; even if the query is right, it's still possible to get errors, and your code should check for them. See the examples on this manual page: http://www.php.net/manual/en/mysqli-stmt.error.php
Finally, since you're using the mysqli API, it's worth mentioning that your code would be a lot better and probably more secure if you used prepared statements. See the examples in PHP manual here: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
[EDIT]
Another possible reason your query is failing is that you're not escaping the input values. If any of the input values contains a quote character (or any other character that is illegal in SQL) then the query will fail. In addition, this problem makes your code vulnerable to a SQL injection hacking attack.
You need to escape your input using $SQL->real_escape_string() OR by changing your query to use prepared statements (as recommended above).
Your query is inside the loop, which means that the loop will wait until your query finished executing before it continue, php code is processed in order...
Has #phpalix said, PHP goes in order, and waits for the previous action to finish.
I think you SQL is wrong. Try replacing your INSERT with this:
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2."');";
And don't forget to run at least mysql_real_escape_string for each variable, for security measures.
As many of the answers and comments say, it does not continue until the SQL is done. The problem was in my local apache/mysql server. It was fixed by restarting it. Yes, stupid post.