EDIT
Why is only the first row being echoed and not all rows that meet the WHERE condition?
$sql="SELECT from_name, to_name FROM private_messages WHERE from_id='$var' OR to_id='$var'" ;
$sql2 = mysql_query($sql);
$row = mysql_fetch_array($sql2);
echo $row['from_name'];
echo $row['to_name'];
Use a "while fetch" loop.
Here's an example of the pattern, using the mysqli interface.
(NOTE: The PHP mysql interface is deprecated. New development should use PDO or mysqli.)
if ($sth = mysqli_query($con, $sql) {
//echo "#debug: query returned a result set";
while ($row = mysqli_fetch_assoc($sth)) {
//echo "#debug: fetched next row";
echo $row['from_name'];
}
//echo "#debug: exited while loop, last row already fetched";
} else {
//echo "#debug: query execution returned FALSE, handle error";
}
This is the same as the pattern used with the deprecated mysql interface. (Is there some reason you are using that interface? N.B. Do not mix mysqli_ and mysql_ functions.
Related
I'm using this code to insert a record with a unique id and then return the id-string just created:
$sql ="set #id=UUID();";
$sql .="INSERT INTO `items` (`id`,`parent`, `text`, `type`) VALUES(#id,'".$parent."', '".$text."', '".$type."');";
$sql .="select #id;";
if (mysqli_multi_query($conn, $sql)) {
while (mysqli_more_results($conn)) {
mysqli_use_result($conn);
mysqli_next_result($conn);
}//while
$result = array('id' => mysqli_store_result($conn)->fetch_row()[0]);
}//if
If everything works as it should, the three queries should return:
1/true (I guess)
1/true
object
I never used this function before and I was wondering: what happens if the insert query fails?
The third query will still be executed?
And in that case, how can I check the result of the second query?
Edit:
Or in general:
having a set of 10 queries, in case of failure how can I check which one has failed?
After some test...
Let's assume we have the following 3 queries:
$sql ="INSERT INTO `items` (`id`,`parent`) VALUES ('id',WRONG_NO_QUOTES);";
$sql .="INSERT INTO `items` (`id`,`parent`) VALUES ('id','right2');";
$sql .="INSERT INTO `items` (`id`,`parent`) VALUES ('id','right3');";
Using the code provided by the manual...
if (mysqli_multi_query($conn,$sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
}
} while (mysqli_next_result($conn));
}
//...plus this....
if(mysqli_errno($conn)){
echo 'mysqli_errno:';
var_dump(mysqli_errno($conn));
echo'<br>';
}
...the output is:
mysqli_errno:
[...]test.php:39:int 1146
...and there are no changes to the database.
Conclusion:
When an error occours, the next queries are NOT executed.
AND the error can be easly catched at the end of the do/while loop.
EDIT
The code above generates a strict standards notice.
I edited it to avoid the notice and get a (basic) backtrace of the error:
$n=1;
$i=1;
if (mysqli_multi_query($conn,$sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = $result->fetch_row()) {
echo $row[0];
}
$result->free();
}
/* print divider */
if (mysqli_more_results($conn)) {
echo "<hr>";
$n++;
mysqli_next_result($conn);
}else{$i=0;}
} while ($i>0);
}
if(mysqli_errno($conn)){
echo 'mysqli error on query number '.$n;
var_dump(mysqli_errno($conn));
}
Since my actual problem was to avoid competition between queries and get the right identifier (check: this question) I realized there is a simpler (and maybe better) way to reach the desired result (here using pdo extension):
$db = new PDO ("mysql:host=$hostname;dbname=$dbname", $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//No user defined variable here inside (safe)
$identifier=db->query("SELECT UUID();")->fetch()[0];
Having the identifier stored into a PHP variable, then I can treat every following query separately using pdo and prepared statements.
I have code
$email = "jb#tlb.com";
$row = mysql_query("SELECT EXISTS(SELECT email FROM accounts WHERE email='".$email."');");
echo $row[0];
However, nothing is echoed.
This is strange because something is being returned because, later in the code I have a function that is CALLED:
if ( $row[0] == 0 ) { echo "Email address is available<br>";};
However: this is strange because when i put the SAME CODE into mySQL database command prompt:
It clearly returns 1 or TRUE.
The mysql_query is returning 0 when the same exact command in mysql command prompt returns 1. Further: I am unable to echo the result for debugging purposes.
EDIT: Please not, the regular mySQL command is returning this and ONLY this:
EDIT: Here is there entire database:
MySQL query gives you a ressource. After that you have to fetch the data with mysql_fetch_assoc or mysql_fetch_row or something else for example. But its better to use prepared statements with mysqli or PDO to get more security.
$email = "jb#tlb.com";
$res = mysql_query("SELECT EXISTS(SELECT email FROM accounts WHERE email='".myql_real_escape_string($email)."')");
$row = mysql_fetch_assoc($res);
echo $row['email'];
Answer to your question:
$email = "jb#tlb.com";
$res = mysql_query("SELECT email FROM accounts WHERE email='".mysql_real_escape_string($email)."')");
$numRows = mysql_num_rows($res);
if($rowRows > 0) {
echo "Record Available";
}
You need to actually retrieve the result set from the query. mysql_query() just returns a resource handle for a successful select. You then need to fetch the results using mysql_fetch_* class of functions. Alternatively, you can use mysql_num_rows() to determine the number of rows returned in the result set.
In this case it is really senseless to wrap your actual query into a subquery. Just run your select and determine the number of rows:
$email = "jb#tlb.com";
$result = mysql_query("SELECT email FROM accounts WHERE email='".$email . "'");
if($result) {
$row_count = mysql_num_rows($result);
echo $row_count;
}
Also, you should not be writing new code using mysql_* functions, as these are deprecated. I would suggest mysqli or PDO extensions instead.
You need to do something like
while ($r = mysql_fetch_assoc($row))
{
echo $r[0];
}
after that code.
Let me know.
I stuck on something stupid..
I have the table that has only one column.
I want to check if there is some value, which I get from the url (method $_GET)
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$row=htmlspecialchars($_GET['row']);
$query = #mysql_query ("SELECT * FROM table WHERE row=$row");
if ($result = #mysql_fetch_array($query)) {
echo "There is that row";
}
else {
echo "There is not that row";
}
Can you tell me what's wrong?
The correct way would be to check if the resultset contains any rows. You can do this with mysql_num_rows():
if (mysql_num_rows($query)>0) {
echo "There is that row";
}
else {
echo "There is not that row";
}
Also if your $row is a string, you should enclose it in single quotes.
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Obligatory "you should be using PDO" comment.
You don't say what sort of field it is, maybe it is a text field so it needs to be in quotes.
$query = #mysql_query ("SELECT * FROM table WHERE row='" . $row . "');
Also if you remove the # you might get to see some sort of error
$query = mysql_query ("SELECT * FROM table WHERE row='" . $row . "') or die(mysql_error());
You seem to mix row and column. When querying SQL database you usually specify clumnName="value" after WHERE statement. You have valid syntax for a table with one column named "row".
There might be a problem in your query as you do not escape your arguments, so it will fail it $row actually has any quotes in it. This would be avoided with use of PDO instead of mysql_ functions which are no longer maintained. Query your table like this instead:
$query = #mysql_query("SELECT * FROM gvar WHERE gvarebi='{addslashes($row)}'");
To actually check if there are any results, it is better to use mysql_num_rows as it will return number of rows for specified query. So update your code with this:
if (mysql_num_rows($query) > 0) {
echo "row exists";
} else {
echo "row does not exists";
}
I'm trying to simply get all the data from a mysql table using the following code:
$dbc = mysqli_connect('host', 'user', 'password', 'table');
$q = 'SELECT * FROM users';
$r = mysqli_query($dbc, $q);
$user_array = array();
while ($row = mysql_fetch_array($r))
{
$user_array[]=$row;
}
echo "<br />";
echo "print r of user_array: <br />";
print_r($user_array);
i'm getting nothing. I looked at this tutorial (http://www.w3schools.com/php/php_mysql_select.asp), among others, but all they do is confuse me.
What am I doing wrong?
try changing this
mysql_fetch_array($r)
to
mysqli_fetch_array($r)
You have connected via the procedural MySQLi API (mysqli_connect()), but you are attempting to use the old mysql_fetch_array() from the old mysql_*() API. They aren't compatible.
You need to fetch via mysqli_fetch_array() or mysqli_fetch_assoc() instead. mysqli_fetch_assoc() is recommended unless you really need numeric keys in addition to column names in the output $row:
// Check for errors.
if ($r) {
while ($row = mysqli_fetch_assoc($r)) {
$user_array[] = $row;
}
}
else echo mysqli_error($dbc);
What you're working with now is a simple query with no parameters, just a SELECT * without a WHERE clause. For the future, when you start adding WHERE conditions, you'll want to start reading about prepared statements and mysqli::prepare().
I have built a class which leverages the abilities of PHP's built-in MySQLi class, and it is intended to simplify database interaction. However, using an OOP approach, I am having a difficult time with the num_rows instance variable returning the correct number of rows after a query is run. Take a look at a snapshot of my class...
class Database {
//Connect to the database, all goes well ...
//Run a basic query on the database
public function query($query) {
//Run a query on the database an make sure is executed successfully
try {
//$this->connection->query uses MySQLi's built-in query method, not this one
if ($result = $this->connection->query($query, MYSQLI_USE_RESULT)) {
return $result;
} else {
$error = debug_backtrace();
throw new Exception(/* A long error message is thrown here */);
}
} catch (Exception $e) {
$this->connection->close();
die($e->getMessage());
}
}
//More methods, nothing of interest ...
}
Here is a sample usage:
$db = new Database();
$result = $db->query("SELECT * FROM `pages`"); //Contains at least one entry
echo $result->num_rows; //Returns "0"
exit;
How come this is not accurate? Other values from result object are accurate, such as "field_count".
Possible Bug: http://www.php.net/manual/en/mysqli-result.num-rows.php#104630
Code is from source above (Johan Abildskov):
$sql = "valid select statement that yields results";
if($result = mysqli-connection->query($sql, MYSQLI_USE_RESULT))
{
echo $result->num_rows; //zero
while($row = $result->fetch_row())
{
echo $result->num_rows; //incrementing by one each time
}
echo $result->num_rows; // Finally the total count
}
Could also validate with the Procedural style:
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
I had the same problem and found the solution was to put:
$result->store_result();
..after the execution of the $query and before
echo $result->num_rows;
This could be normal behavior when you disable buffering of the result rows with MYSQLI_USE_RESULT
Disabling the buffer means that it`s up to you to fetch, store and COUNT the rows.
You should use the default flag
$this->connection->query($query, MYSQLI_STORE_RESULT);
Equivalent of
$this->connection->query($query)