PHP MYSQL query shortcut? - php

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

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.

Way to test more data without advancing pointer?

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.

How do I use a MySQL user-defined function from within PHP?

Spent several hours searching for an answer without success. I've written a user-defined function in MySQL which is passed an identifier which it uses to retrieve various pieces of data, concatenate it into one string and return it. I want to call this function from my PHP page and output the result.
Unsuccessful attempts include:
1. $result = mysql_query("select functionName($id)");
2. $sql = "select functionName($id)";
$result = mysql_query($sql, $link);
3. functionName($id)
Any ideas?
1 and 2 are close, but $result is not going to contain the result of the function call. Rather, it is going to contain the result cookie from the query. You can use that cookie to get the actual data, with mysql_fetch_row(). The function call just returns a value for the select statement, just the same as "SELECT 42" or "SELECT a FROM MyTable". So to get the result you would use the same mechanism as with any other SQL query that returns results; that is, use the cookie and call mysql_fetch_row(). So your final code will look like this:
$result = mysql_query("select functionName($id)");
$row = mysql_fetch_row($result, $link);
$returnValue = $row[0];
Note that you don't want to be interpolating variables directly into an SQL string (that can be a vector for attacks). I assume, however, that this code is just for example purposes.
I had the same question and found this very useful write up from devx, particulary the part at the bottom about calling MySQL functions:
http://www.devx.com/webdev/Article/42887/0/page/2
With regards to mysqli, my code is now as follows:
$result = mysqli_query($sqlconnection,"SELECT functionName($id)");
$row = mysqli_fetch_row($result);
return $row[0];
works perfectly.

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