Sorting information from query using while? - php

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;

Related

multi query select using wrong array?

I have a multi query select which half works. The first query is straight forward.
$sql = "SELECT riskAudDate, riskClientId, RiskNewId FROM tblriskregister ORDER BY riskId DESC LIMIT 1;";
The second one doesn't seem to work even when I do it on its own:
$sql ="SELECT LAST(riskFacility) FROM tbleClients";
If I get rid of the LAST it returns the first entry in that field of the table. I want to use the LAST to get the LAST entry in that field.
When I do the first query on its own I get the data returned and I can echo it to the screen. When I add the second (with out the LAST) I get nothing. Here is what I am using
$result = $conn->query($sql);
if ($result == TRUE){
$r = $result->fetch_array(MYSQLI_ASSOC);
echo $r['riskAudDate'];
echo $r['riskClientId'];
echo $r['RiskNewId'];
echo $r['riskFacility'];
echo "<pre>";
print_r($r);
echo "</pre>";
}
The last bit is just for me to see whats in the array and just for testing.
So I have worked out that its the results array that is not right.
If I change the actual query to multi query I get this:
Call to a member function fetch_array() on boolean
So the array bit seems to be wrong for a multi query. The data returned is one row from each table. It works for the top query but add in the second (which I'm not sure is correct anyway) and the whole things crashes. So I guess it's a two part question. Whats wrong with my inserts and whats wrong with my returned array?
There is no last() function in mysql, it is only supported in ms access, if I'm not much mistaken. In mysql you can do what you do in the 1st query: do an order by and limit the results to 1.
According to the error message, the $conn->query($sql) returns a boolean value (probably true), therefore you cannot call $result->fetch_array(MYSQLI_ASSOC) on it. Since we have no idea what exactly you have in $sql variable, al I can say is that you need to debug your code to detrmine why $conn->query($sql) returns a boolean value.
Although it is not that clear from mysqli_query()'s documentation, but it only supports the execution of 1 query at a time. To execute multiple queries in one go, use mysqli_multi_query() (you can call this one in OO mode as well, see documentation). However, for security reasons I would rather call mysqli_query() twice separately. It is more difficult to execute a successful sql injection attack, if you cannot execute multiple queries.
It seems to me you are trying to do two SQL-queries at once.
That is not possible. Do a separate
$result = $conn->query($sql);
if ($result == TRUE){
while( $r = $result->fetch_array(MYSQLI_ASSOC)) {
...
}
}
for each SQL-query.
concerning :
$sql ="SELECT LAST(riskFacility) FROM tbleClients";
since the last function does not exists in MySQL i would recommend doing a sort like this(because i don't know what you mean with last )
$sql ="SELECT riskFacility FROM tbleClients order by riskFacility desc limit 0,1";

Assign MySQL database value to PHP variable

I have a MySQL Database Table containing products and prices.
Though an html form I got the product name in a certain php file.
For the operation in this file I want to do I also need the corresponding price.
To me, the following looks clear enough to do it:
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
However, its echo returns:
Resource id #5
instead a value like like:
59.95
There seem to be other options like
mysqli_fetch_assoc
mysqli_fetch_array
But I can't get them to output anything meaningful and I don't know which one to use.
Thanks in advance.
You will need to fetch data from your database
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
$result = mysql_fetch_array($price);
Now you can print it with
echo $result['price'];
As side note I would advise you to switch to either PDO or mysqli since mysql_* api are deprecated and soon will be no longer mantained
If you read the manual at PHP.net (link), it will show you exactly what to do.
In short, you perform the query using mysql_query (as you did), which returns a Result-Resource. To actually get the results, you need to perform either mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_object on the result resource. Like so:
$res = mysql_query("SELECT something FROM somewhere"); // perform the query on the server
$result = mysql_fetch_array($res); // retrieve the result from the server and put it into the variable $result
echo $result['something']; // will print out the result you retrieved
Please be aware though that you should not use the mysql extension anymore; it has been officially deprecated. Instead you should use either PDO or MySQLi.
So a better way to perform the same process, but using for example the MySQLi extension would be:
$db = new mysqli($host, $username, $password, $database_name); // connect to the DB
$query = $db->prepare("SELECT price FROM items WHERE itemId=?"); // prepate a query
$query->bind_param('i', $productId); // binding parameters via a safer way than via direct insertion into the query. 'i' tells mysql that it should expect an integer.
$query->execute(); // actually perform the query
$result = $query->get_result(); // retrieve the result so it can be used inside PHP
$r = $result->fetch_array(MYSQLI_ASSOC); // bind the data from the first result row to $r
echo $r['price']; // will return the price
The reason this is better is because it uses Prepared Statements. This is a safer way because it makes SQL injection attacks impossible. Imagine someone being a malicious user and providing $itemId = "0; DROP TABLE items;". Using your original approach, this would cause your entire table to be deleted! Using the prepared queries in MySQLi, it will return an error stating that $itemId is not an integer and as such will not destroy your script.

PHP MYSQL query shortcut?

If I am doing a PHP MYSQL select of a table using the where clause that will return only 1 result, is there a simpler way to do this:
$result = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
$cartrec = mysql_fetch_array($result);
Is the $cartrec = mysql_fetch_array($result); needed or could I just do:
$cartrec = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
or is there a better syntax to use?
mysql_query gets a result set (actually, a resource that refers to a result set) based on your query. This is the set of records that match your query.
mysql_fetch_array gets the first record from a result set, and returns it as an array.
So, up until you've called mysql_fetch_array, you haven't gotten the data in a usable format.
Side note: Consider using PDO
The fetch array is required, the mysql_query gets a result set (ressource), then mysql_fetch_array get's the element in the result set.
As a side note, be careful of SQL injections: http://en.wikipedia.org/wiki/SQL_injection
EDIT: Might be a bit more advanced that what you need, but it might be worth while looking into PDO: http://php.net/manual/en/book.pdo.php
Is the $cartrec = mysql_fetch_array($result); needed
Yes, otherwise you get a resource pointer not an result set (array).
or is there a better syntax to use?
Yes, MySQLi
No, but its pretty common for people to write their own function for this use case. It's usually named something like fetch_one($sqlString) or fetch_first($sqlString)
You could use this, but if the database structure were to change, it would be problematic
$row = mysql_fetch_row($result);
echo $row[0]; //column 1
echo $row[1]; //column 2
You may want to look at this http://www.php.net/manual/en/function.mysql-fetch-row.php

PHP SQL query results

Alright, I'm pretty confident I did this only a few days ago, although I may be going crazy. I am attempting to loop through an SQL result array for example..
$query = mysql_query("SELECT * FROM `my_table`");
$result = mysql_fetch_assoc($query);
Now $result should return multiple rows.. and it does if I loop through it using a while loop. Unfortunately, Im trying to access this data with a foreach loop, and for some reason it will not work. Its only giving me the first row and print_r($result) only gives me the first row as well.
foreach($result as $name => $value)
echo "$name = $value\n";
Any suggestions would be appreciated!
** EDIT:
I love all of the smart answers.. I know the website for the php manual and I know what mysql_fetch_assoc() returns. Here is my solution:
function returnSQLArray() {
$returnArray = array();
$row = 0;
$query = mysql_query("some sql");
while($result = mysql_fetch_assoc($query)) {
$returnArray[$row] = $result;
$row++;
}
return $returnArray;
}
$result = mysql_fetch_assoc($query); returns a single row... you need to loop fetching each row. You're looping through that one row to extract each column.
What Vladson is sarcastically pointing out is nonetheless very true. My forays into PHP programming (many years' worth) have been ever-sprinkled with a great many readups on the php.net site. I'd call it the best online programming documentation in existence, far beating any other language I've used in 20 years.. mostly because of the amazing calibre of the community contributions.
Also, I'd highly recommend abstracting what you're talking about into a db helper class. Reference perhaps the PHPBB code for an example. PHPBB code may be less OO than is ideal, but it's still a good reference point for architecture. And, don't just do this because you may switch out your data layer or change the version, but because it makes it trivial to introduce common error reporting, query logging, data caching, and many other such useful features. This also makes it easier to juggle more than one connection.
Example might be so that you can expose an interface more like: (excuse the very ADODB nature here, but it's still a nice way to think of MySQL, too)
include "db.inc.php";
$SQL = "SELECT * FROM user WHERE id=123";
$oDB = new Database("localhost", "database", "user", "password");
$oRS = $oDB->NewRecordSet($SQL);
while( $data = $oRS->Read() ) {
// do stuff
}
In this manner, the pages have to worry less about the tedium of accessing the data, and can just think more about how to filter the data and what to do with it.
while ($result = mysql_fetch_assoc($query))
{
// do stuff
}
There is a thing called Manual http://www.php.net/manual/en/function.mysql-fetch-assoc.php examples are also there (a lot of them)

PHP sql with foreach loop variable problem

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/>";
}

Categories