I'm looking to label a string based on database results. I have the following code:
$loc1 = "A";
$query = "SELECT loc FROM User where nick='".$users[$j]."'";
$loc = mysql_query($query);
if($loc == 1)
$loc1 = "A";
if($loc== 2)
$loc1 = "B";
The loc1 location is always "A". I've confirmed that the query works in MySQL and I'm having a difficult time understanding why this simple case is not working. I would appreciate your help!
The function mysql_query does not return the value of the column fetched, instead it returns a MySQL resource which you use to extract the column value returned by the query.
Change:
$loc = mysql_query($query);
to:
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if ($row = mysql_fetch_assoc($result)) {
$loc = $row["loc"];
}
You are storing mysql_query() return value in $loc which is a resource.
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
So, $loc is not 1 or neither equals to 2.
You need to use mysql_fetch_array / mysql_fetch_object, etc to manipulate the resource.
You must fetch the recordset with, in example mysql_fetch_row
Example #1 Fetching one row with mysql_fetch_row()
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
But, be careful with SQL injection attacks!
http://es.php.net/manual/en/security.database.sql-injection.php
Related
This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('censored','censored','censored','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db");
$sql="SELECT message FROM messages WHERE code = '".$q."'";
$result = mysqli_query($con,$sql);
$resultstring = (string)$result;
echo $resultstring;
mysqli_close($con);
?>
I am attempting to echo the result of the query to the user but when this PHP runs through ajax I get this error:
Recoverable fatal error: Object of class mysqli_result could not be
converted to string in D:\xampp\htdocs\getmessage.php on line 12
Now I don't understand this because I am already converting $result into a string.. Thanks!
mysqli_query() can not convert to string.
You must use mysqli_fetch for parse to array.
Example:
if ($result=mysqli_query($con,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf ("%s (%s)\n",$row[0],$row[1]);
}
}
First of all mysqli_query Performs a query on the database
it does not directly return a value
$query = mysqli_query($con,$sql);
so to do that use mysqli_fetch_assoc it will Fetch a result row as an associative array
$result = mysqli_fetch_assoc($query);
Then you can now get your value
$resultstring = $result['message'];
so your code should be like this
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('censored','censored','censored','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db");
$sql="SELECT message FROM messages WHERE code = '".$q."'";
$query = mysqli_query($con,$sql);
$result = mysqli_fetch_assoc($query);
$resultstring = $result['message'];
echo $resultstring;
mysqli_close($con);
?>
you need to convert the data(RS) into array !
$result = mysqli_fetch_assoc($result);
print_r($result);
As an result of your query on success You will get mysqli_result object. If You want to get received rows use fetch data function.
$result = mysqli_query($con,$sql);
$resultstring = $result->fetch_row()[0];
See docs: mysqli_query &
mysqli_result
I have resolved similar issue with following approach.
// Assign your sql statement
$sqlMasterSiteIds = "SELECT DISTINCT table_name FROM site WHERE gwid = 39 AND master_site_id NOT LIKE '0'";
// Run the query
$masterSiteIdsQuery = $this->db->query($sqlMasterSiteIds);
// Prepare container
$masterSiteIds = [];
// Fetch first row of query results
$first_row = $masterSiteIdsQuery->fetch_assoc();
// Assign first row to your prepared container
$masterSiteIds= $first_row['master_site_id'];
// Change the results into string comma separated so it can be used in next mysqli query or echoed
while($sub_row = $masterSiteIdsQuery->fetch_assoc()) {
$masterSiteIds = implode(',', array($masterSiteIds, $sub_row['master_site_id']));
}
// Now you can use $masterSiteIds which is a STRING of values comma separated
echo $masterSiteIds; // Output: '1024, 1142, 8492'
I hope it will help you or anybody else in need. I am not sure if it is the best approach but it worked well in my case as I had to change my results into STRING so I could use it in my next mysqli query with FIND_IN_SET command.
Happy coding!
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 am trying to set the two outputs from this MySQL stored procedure as PHP variables:
$result = mysql_query("CALL mst2('$q', #eset, #leng)");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row = #mysql_fetch_assoc($result))
{
debug($row);
}
$eset = $row->{'#eset'};
$length= $row->{'#leng'};
The last two line are throwing an error Trying to get property of non-object . Does anybody know the proper way to do this?
mysql_fetch_object instead of mysql_fetch_assoc should fix your query up.
Secondly though you should really look at either using mysqli_ or pdo statements.
Links here:
http://php.net/manual/en/pdo.query.php
http://php.net/manual/en/mysqli.query.php
Here's how I got it to work with mysql_query:
$result = mysql_query("CALL mst2('$q', #eset, #leng)");
$result = mysql_query("SELECT #eset, #leng");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row = #mysql_fetch_object($result))
{
$eset = $row->{'#eset'};
}
right after the procedure I called a SELECT statement, then in the while loop, the $eset variable gets set properly.
Back again, thanks for all the help last time. I'm running this query:
$query = "SELECT * FROM event where evLoc = ".$loc." AND evChar = ".$char;
var_dump($query);
$result = mysql_query($query, $con) or die('Error 1:'.mysql_error());
if ($result) {
$row = mysql_fetch_array($result) or die('Error 2:'.mysql_error());
var_dump(mysql_num_rows($result));
exit();
I get a message Error 2: but no mysql_error printed out. The var_dump($query) printed out a query that ran without errors in phpMyAdmin. The var_dump(mysql_num_rows($result)) did not print.
This is a case of being too cautious and applying error checking where it doesn't belong.
Don't call die() in partnership with a fetch call. The fetch intentionally returns FALSE when there are no rows available, so you don't have an error, just no rows.
// No rows were returned, wich is FALSE
$row = mysql_fetch_array($result) or die('Error 2:'.mysql_error());
Instead, don't call die() here:
$row = mysql_fetch_array($result);
if ($row) {
// you got something
}
Or this way:
if ($row = mysql_fetch_array($result)) {
// you got something.
}
If multiple rows are expected to be returned, fetch in a while loop.
while ($row = mysql_fetch_array($result)) {
// loops until you're out of rows
// or not at all if you have no rows
}
Obviously, your request returns 0 rows and mysql_fetch_array returns FALSE
Apply Single Quotes in the fields of your query
$query = "SELECT * FROM event where evLoc = '".$loc."' AND evChar = '".$char."'";
You can write these in short form too. Like
$query = "SELECT * FROM event where evLoc = '$loc' AND evChar = '$char'";
Next, you might want to change your fetch portion.
while($row = mysql_fetch_assoc($result)) {
....
}
When you use this, you will avoid the error you would receive when no rows are returned.
I am trying to access some information from mysql, but am getting the warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource for the second line of code below, any help would be much appreciated.
$musicfiles=getmusicfiles($records['m_id']);
$mus=mysql_fetch_assoc($musicfiles);
for($j=0;$j<2;$j++)
{
if(file_exists($mus['musicpath']))
{
echo ''.$mus['musicname'].'';
}
else
{
echo 'Hello world';
}
}
function getmusicfiles($m_id)
{
$music="select * from music WHERE itemid=".$s_id;
$result=getQuery($music,$l);
return $result;
}
Generally, the mysql_* functions are used as follows:
$id = 1234;
$query = 'SELECT name, genre FROM sometable WHERE id=' . $id;
// $query is a string with the MySQL query
$resource = mysql_query($query);
// $resource is a *MySQL result resource* - a mere link to the result set
while ($row = mysql_fetch_assoc($resource)) {
// $row is an associative array from the result set
print_r($row);
// do something with $row
}
If you pass something to mysql_fetch_assoc that is not a MySQL result resource (whether it's a string, an object, or a boolean), the function will complain that it doesn't know what to do with the parameter; which is exactly what you are seeing.
A common gotcha: you get this warning if you pass something (other than a valid query string) to mysql_query:
$id = null;
$query = 'SELECT name, genre FROM sometable WHERE id=' . $id;
$res = mysql_query($query);
// $res === FALSE because the query was invalid
// ( "SELECT name, genre FROM sometable WHERE id=" is not a valid query )
mysql_fetch_assoc($res);
// Warning: don't know what to do with FALSE, as it's not a MySQL result resource
Without seeing the code of getmusicfiles there's not a lot we can really help you with. You should be returning a valid mysql resource in that function.
As others have noted, you need to return a valid mysql resource into the mysql_fetch_assoc function to retrieve the next row. For example:
$sql = "select * from table";
$resultSet = mysql_query($sql) or die("Couldn't query the database.");
echo "Num Rows: " . mysql_num_rows($resultSet);
while ($resultRowArr = mysql_fetch_assoc($resultSet)) {
...
}
I think you need to specify what the function getQuery()
$result=getQuery($music,$l);
does
It depends on what exactly getmusicfiles() does. It must return a result of mysql_query() function call, then it will be a "valid MySQL result".
And you most probably wanted to put the line $mus=mysql_fetch_assoc($musicfiles) inside of the for cycle to fetch several rows one after another.
function getmusicfiles($m_id) {
$music="select * from music WHERE itemid=".$s_id;
$m_id != $s_id ?