why does mysql_fetch_array() storing an empty result? - php

I am successfully selecting the data from database table, when ever I am trying to fetch that data in to an array with the help of mysql_fetch_array() it's not storing anything into the array.
#session.start();
$name=$_SESSION['umailid'];
$chkname1 = "select * from ".USREG." where email='.$name.'";
echo $chkname1;
// it is printing like this:
// " select * from users_temp where email='.subbu66g#gmail.com.' "
// which means query was successful, above email is there in database table
$res1 = mysql_query($chkname1, $con) or die(mysql_error());
$chkresult1 = mysql_fetch_array($res1);
echo $chresult1['name']; //its not printing anything
if ($chkresult1) //it is storing null and entering into else block
{
echo "query successful";
}
else {
echo "query was not successful";
}
And the result is "query was not successful". I think everything is fine with my select query. Then why this mysql_fetch_array() is not fetching the data?

In $chkname change to email = $name
(remove dot) or email = '$name'
And you are using mysql ,rather use mysqli or pdo sql

Related

Selecting * from table returns nothing

I wrote this php script that allows me to fetch all the rows in a table in my MySQL database.
I have put the echo "1", etc. to see whether it gets to the code at the very end. The output proves it does. However, it does not output anything when echoing json_encode($resultsArray), which I can't seem to figure out why.
Code:
// Create connection
$connection = mysqli_connect("localhost", "xxx", "xxx");
// Check connection
if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } else { echo "0"; }
// select database
if (!mysqli_select_db($connection, "myDB")) { die('Unable to connect to database. '. mysqli_connect_error()); } else { echo "1"; }
$sql = "select * from myTable";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));;
echo "3";
$resultsArray = array();
while($row = mysqli_fetch_assoc($result)) {
// convert to array
$resultsArray[] = $row;
}
echo "4";
// return array w/ contents
echo json_encode($resultsArray);
echo "5";
Output:
01345
I figured, it is not about the json_encode, because I can also try to echo sth. like $result['id'] inside the while loop and it just won't do anything.
For testing, I went into the database using Terminal. I can do select * from myTable without any issues.
Any idea?
After around 20hrs of debugging, I figured out the issue.
As I stated in my question, the code used to work a few hours before posting this question and then suddenly stopped working. #MichaelBerkowski confirmed that the code is functional.
I remembered that at some point, I altered my columns to have a default value of an empty string - I declared them as follows: columnName VARCHAR(50) NOT NULL DEFAULT ''.
I now found that replicating the table and leaving out the NOT NULL DEFAULT '' part makes json_encode() work again, so apparently there's an issue with that.
Thanks to everybody for trying anyway!

No Database Selected Php

This is a somewhat simple task, I am trying to compare a username to that in the database. I am testing it out in a single php file before I do it properly. My code is below. Basically I have a user, which is in the database and I am checking if it is in there.
<?php
$db_connect = mysql_connect("127.0.0.1", "root", "anwesha01", "mis");
//Check if connection worked.
if(!$db_connect)
{
die("Unable to connect to database: " . mysql_error());
}
//For testing purposes only.
else
{
echo "Database connect success!";
}
$user = "alj001";
$query = "SELECT Username FROM `user` WHERE `Username` = '".$user."'";
//What is being passed through the database.
echo "<p><b>This is what is being queried:</b> " . $query;
//Result
if (mysql_query($query, $db_connect))
{
echo "<br> Query worked!";
}
else
{
echo "<p><b>MySQL error: </b><br>". mysql_error();
}
?>
The result I get is:
Database connect success!
This is what is being queried: SELECT Username FROM user WHERE Username = 'alj001'
MySQL error: No database selected
First I had my mysql_query without the $db_connect as it is above, but I put it in and I still get "no database selected".
Ive looked at the w3c schools for the mysql_query function, I believe I have done everything correctly. http://www.w3schools.com/php/func_mysql_query.asp
Because you haven't called mysql_select_db. Note that the 4th parameter to mysql_connect is not what you think it is.
That said, you really should be using PDO or mysqli, not the plain mysql_ functions, since they're deprecated.

How to print the value of a single cell using MySQL and PHP?

This returns a blank page:
<?php
$con=mysqli_connect("xxx.x.xx.x","user","password","db");
// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT column FROM table WHERE id=1");
print $result;
mysqli_close($con);
?>
And this returns data:
<?php
$con=mysqli_connect("xxx.x.xx.x","user","password","db");
// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM table");
while($row = mysqli_fetch_array($result))
{
echo $row['column_1'] . " " . $row['column_2'];
echo "<br>";
}
mysqli_close($con);
?>
What is wrong with the first block of code that prevents it returning any data?
http://php.net/manual/en/mysqli.query.php
tells me that mysqli_query returns a mysqli_query object. Not a primitive value like string or int.
The exact line that says this is:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
Hence the first block does not work because the first block assumes the value in the column is automatically returned.
In fact, if you used the same SELECT column from table where id=1, you still have to use the while loop to extract the values because it is STILL a mysqli_result object you are getting back.
By while loop I mean this:
while($row = mysqli_fetch_array($result))
{
echo $row['column_1'];
echo "<br>";
}
I hope this answers your question.

php/sql error - mysql_fetch_assoc()

I'm receiving the following error:
mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource..
and I can't figure out what is going on. Here is my code. I did create a database with a table named notes. Also, the database connection is working correctly. Any idea on what is going on?
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
mysql_fetch_assoc($query)
Thanks
var_dump($query);
echo mysql_error();
Did mysql_query fail and return FALSE? As the documentation explains:
For SELECT, SHOW, DESCRIBE, EXPLAIN
and other statements returning
resultset, mysql_query() returns a
resource on success, or FALSE on
error.
FALSE would not be a valid resource.
On the PHP page, it gives you a perfect example of how to use it and do error checking...
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
How about you go and implement the entire way making sure rows are returned, and its a valid resource, and if result is truthy?
You should always debug and never assume something executed rightfully.
In the future please read through the entire page of the function on php.net, in this case it's http://php.net/manual/en/function.mysql-fetch-assoc.php

Posting variable returns invalid

I am using a simple PHP script for the activation part of one of my applications. The applications posts one variable to the page (http://validate.zbrowntechnology.info/WebLock.php?method=validate). The variable is the serial number, posted as 'Serial'. Each time I post to this page, it returns Invalid. Here is the code:
<?php
$serial = $_POST['Serial'];
$method = $_GET['method'];
$con = mysql_connect("HOSTHERE", "USERHERE", "PASSHERE");
if(!$con) {
die('Unable to connect to MySQL: ' . mysql_error());
}
if($method == "validate") {
mysql_select_db("zach_WebLock", $con);
$query = "SELECT Key, Status FROM Validation WHERE Key='".mysql_real_escape_string($serial)."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
echo "Valid";
} else {
echo "Invalid";
}
} else {
echo "Unkown Method";
}
?>
Here Is The Error From PHP,
PHP Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
Right after the query use mysql_error() to see what happened. And Key is a bad choice for a column name because it's a reserved word in SQL. You can enclose it in `` to tell MySQL it's an identifier. Do some more debugging like this:
...
if (!mysql_select_db("zach_WebLock", $con)) die('mysql_select_db failed');
$query = "SELECT `Key`, Status FROM Validation WHERE `Key`='".mysql_real_escape_string($serial)."'";
print "query=$query<br>\n";
$result = mysql_query($query, $con);
print "error=" . mysql_error($con);
...
You're missing a closing parenthesis on this line:
if(mysql_num_rows($result) > 0 {
Is that missing in your code or just your question?
You may also want to add
if (!$result) {
print mysql_error();
}
after your query
Try Like This
$query = "SELECT Key, Status FROM Validation WHERE Key='".$serial."'";
What happens if at the last line you add this?
else echo 'Unknown method';
What may be happening is that $_POST and $_GET are not getting populated, this is a setting in php.ini, if I remember correctly (search for "superglobals" in the php docs).
edit: also, you have a very bad security risk there, google "sql injection". Basically the problem is that you could get any SQL directly into your database, and if the php user has enough permissions it could mean that anyone can, for example, delete all the data from your Validation table. You should at least do something like this:
$query = "SELECT Key, Status FROM Validation WHERE Key='".addslashes($serial)."'";
It could be a typo but you are missing a closing parenthesis here:
if(mysql_num_rows($result) > 0 {
^
And you might have turned off you error reporting, in which case you get a blank page.
Try echoing $serial:
echo $serial;
And is it what you typed in form?

Categories