Way to test more data without advancing pointer? - php

Is there a way to check end-of-file on a recordset returned from MySQL (in PHP)?
I'd like to do something like the following:
while (!mysql_eof($result) {
$row = mysql_fetch_array($result);
}
I don't want to use mysql_fetch_array() in the main loop, because I need to do further reads inside the loop and don't want the recordset current record counter updated ie. I do not want to advance the current pointer.

Write your query like
$result = mysql_query("SELECT * FROM MyTable ORDER BY id DESC LIMIT 0,1");
$row = mysql_fetch_assoc($result);
print_r($row);
And try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.

$result = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
$counter = 1;
while($counter<=$num_rows)
{
//There is still more data
//Do whatever to the current row
$counter++;
}
Hope this does it. If not, I don't know what will.

mysql_eof() is deprecated. mysql_errno() or mysql_error() may be used instead.
mysql_eof() determines whether the last row of a result set has been read.
If you acquire a result set from a successful call to mysql_store_result(), the client receives the entire set in one operation. In this case, a NULL return from mysql_fetch_row() always means the end of the result set has been reached and it is unnecessary to call mysql_eof(). When used with mysql_store_result(), mysql_eof() always returns true.
Check out : http://dev.mysql.com/doc/refman/4.1/en/mysql-eof.html for more details.

Related

Get values from query and return as array

How could I return the values from this query as an array so that I can perform an action with the array?
$sql = mysql_query("SELECT username FROM `users`");
$row = mysql_fetch_array($sql);
How would I get the code to be like the following? Here, the user1 and user2 would be the usernames of the users selected from the above query.
$userarray = array("user1","user2");
Before I point out best practices, you need working code first. So I'll give you a simple solution first.
To run a query with the mysql extension the function is mysql_query, you can't pass the query text directly to mysql_fetch_array. Nextly mysql_fetch_array doesn't do what you think it does. mysql_fetch_array combines the functionality of mysql_fetch_row and mysql_fetch_assoc together by storing the key names of the resulting columns along with their numeric indexes. The mysql_fetch_array function does not return an array with all rows from your query. To get all rows from the query, you need to run mysql_fetch_array in a loop like so:
$sql = "SELECT username FROM `users`";
$result = mysql_query($sql);
if(!$result){echo mysql_error();exit;}
$rows=array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
print_r($rows);
Nextly, do note that the mysql_* functions are deprecated because the mysql extension in PHP is no longer maintained. This doesn't mean MySQL databases are deprecated, it just means the database adapter called mysql in PHP is old and newer adapters are available that you should be using instead, such as mysqli and PDO.
Next point, it is bad practice to rely upon short tags as it can be disabled by php.ini settings, always use either <?php ... ?> or <?= ... ?> for easy echoing which isn't affected by short tags.
Please read up on some mysqli or PDO simple examples to get started with one or the other. The mysqli extension is specific for MySQL while PDO (PHP Data Objects) is designed as a generic adapter for working with several kinds of databases in a unified way. Make your pick and switch so you're no longer using the deprecated mysql_* functions.
You would need to use a foreach loop to do it:
$userarray = [];
foreach($row as $single)
{
array_push($userarray, $single['username']);
}
and if can, try to use this MySQLi Class, it's very simple to get what you want from the database.
$db = new MysqliDb ('host', 'username', 'password', 'databaseName');
$userarray = $db->getValue('users', 'username', null);

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.

Sorting information from query using while?

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;

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

How to know if MySQL returns 0

When I run this query `
SELECT id FROM bckoff WHERE left
= 3;
`
in phpmyAdmin, I get the correct response
MySQL returned an empty result set
(i.e. zero rows).
However, when I run the same query through my PHP code using mysql_query('the above query').. then I get "Resource ID#5" or "Resource ID#6" and so on..
How do I get the empty result set (or zero rows) in PHP ?
mysql_num_rows is the answer. This function returns the number of rows affected by a executed query.
$query = "SELECT id FROM bckoff WHERE left = 3";
$result = mysql_query($query);
echo mysql_num_rows($result);
When you execute mysql_query($query) it executes the query and puts it in a resource. This resource can be read by different mysql-functions (like mysql_num_rows). For a complete overview of all MySQL functions have a look at http://nl.php.net/manual/en/ref.mysql.php
Note: Extension used in above code is deprecated as of PHP 5.5.0, Use MySQLi or PDO_MySQL extension.
So instead of mysql_num_rows use mysqli_num_rows()
You can use mysql_num_rows function as:
$result = mysql_query("SELECT id FROM bckoff WHERE left = 3");
$num_rows = mysql_num_rows($result);
// $num_rows will be 0.
You need to use a mysql_fetch_* function to retrieve the results. Look here
Mysql Fetch Functions
There is a mysql_num_rows function that you can call on the $result returned by mysql_query("SELECT ...").
You might look into the MySQLi extension instead. It's a big improvement over the MySQL driver, and allows you to use prepared statements and bind parameters among other things, and I find it much more comfortable to use. You can look at the examples on the documentation page for num_rows.

Categories