Here is how I am currently counting mysql rows in PHP:
//GET total # of results and build $start and $end for main SQL statement
$sql= 'SELECT COUNT(*) FROM savedsearches WHERE user_id=\''.mysql_real_escape_string($user_id).'\'';
$initial_query = mysql_query($sql) or die("SQL error");
$num_sql = mysql_fetch_array($initial_query);
$numrows = $num_sql[0];
mysql_free_result($initial_query);
Is there a more efficient way to do this?
No. If you want a count , you run the query you're already running.
If you need more efficiency, make sure there is an index on the user_id column
//GET total # of results and build $start and $end for main SQL statement
$sql= 'SELECT * FROM savedsearches WHERE user_id=\''.mysql_real_escape_string($user_id).'\'';
$initial_query = mysql_query($sql) or die("SQL error");
$numrows = mysql_num_rows($initial_query)
As you can see, you can run mysql_num_rows() BEFORE mysql_fetch_array. This is very useful to me, since it allows me to know before hand, weather or not I have the amount of rows I need. If you want to learn more about this function: PHP Manual: mysql_num_rows()
You mean, do it in fewer lines of code? You could put that functionality into a user-defined function and then call the function instead of using that code, but other than that, it's not going to get an awful lot terser.
Related
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";
I've recently gotten over my bad habit of using the deprecated mysql functions in favor of mysqli, and I'm having some issues.
Right now, I'm using something similar to the following:
$query = $conn->prepare("SELECT * FROM table WHERE cid = ?");
$query->bind_param('i', $id);
$query->execute();
And this is where I get stuck. In order to loop through the result, I use:
while ($row = $query->get_result()->fetch_assoc()) {
//My code here
}
However, I need to determine the number of rows returned from the query before going through the results. To do this, I need to do the following:
$query->store_result();
$rows = $query->num_rows;
But I get errors when calling both get_result and store_result on the same query.. is there an easier way to do this? Am I overthinking things? I basically just want to determine if the result set has greater than x # of rows, and if so, loop through the results.
Thanks for any help.
I am editing a tutorial I found on inline editing. It uses mysql but obviously I want to use mysqli as mysql is depreciated. I have changed most of it but one part is causing me difficulty. There is a seperate file that is called to connect to the database and run queries so the main page I will declare at the top at the top of my page I declare
require_once("dbcontroller.php");
$db_handle = new DBController();
$sql = "SELECT * from php_interview_questions";
$faq = $db_handle->runQuery($sql);
The relevant part of the dbcontroller.php is:
function runQuery($query) {
$result = mysqli_query($conn, $query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysqli_query($conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
Am I right in thinking that I need to use prepared statements? If so how would this cope with working with a select query that could involve any number of columns or any number of conditions in the WHERE clause?
numRows() is a strange function since it runs a query only to find out how many rows it returns. I would consider it a questionable practice. If it is necessary to find out how many rows a SELECT would return, then one could change SELECT * to SELECT COUNT(*). MySQL would be able to optimize that for MyISAM tables, plus there is a saving on not having to transfer the result set to the client.
Otherwise there is no need to use prepared statements, since a prepared statement only increases the amount of work a DBMS has to do when a statement is executed only once (it has to handle two requests - prepare, execute, -- instead of one -- execute, plus extra work to clean up the cached statement when connection is destroyed).
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.
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.