PHP SQL SELECT from WHERE isn't working - php

I know that this is very thoroughly covered on stack overflow, but I cannot figure it out. I am completely new to PHP and SQL commands so please bear with me.
Here is my code:
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$result = mysql_query($connection,"SELECT `first_name` FROM `students` WHERE student_id = '$studentid'");
while($row = mysqli_fetch_array($result))
echo $row['first_name']
I am sure that it is probably something really stupid. I know that i should be using mysqli or something but this is just a test project to teach me some basics.
student_id is from the previous php page, and I want it to lookup student_id and display the first name of the student where I put echo from the table named students, but I get nothing on the page and there is no entry in the error log.
student_id is both the name of the column and the name of the input field on the previous php page.
Also, I don't know if it makes a difference, but the code from $connection to the while statement are in one
Any suggestions?
Thanks.

You're mixing your MySQL APIs, they do "not" mix.
Change mysqli_fetch_array to mysql_fetch_array if you really want to use mysql_*
Plus, put some bracing in:
while($row = mysql_fetch_array($result)) // missing brace
echo $row['first_name'] // <= missing semi-colon
and a semi-colon at the end of echo $row['first_name']
while($row = mysql_fetch_array($result)){
echo $row['first_name'];
}
Also, your DB connection here, goes at the end, not at the beginning: Unlike the mysqli_* method, it goes first. Using mysql_, the connection goes at the end. If you really want to use mysqli_* functions, then you'll need to change all mysql_ to mysqli_ (which follows).
$result = mysql_query($connection,"SELECT `first_name` FROM `students` WHERE student_id = '$studentid'");
which isn't really needed, since a DB connection has been established. (I've placed it at the end though).
$result = mysql_query("SELECT `first_name` FROM `students` WHERE student_id = '$studentid'",$connection);
Plus, use $studentid = mysql_real_escape_string(strip_tags($_POST['student_id']), $connection); for added protection, if you're still keen on using mysql_* based functions.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
MySQL (error reporting links)
http://www.php.net/manual/en/function.mysql-error.php
http://www.php.net/manual/en/mysqli.error.php
http://www.php.net/mysqli_error
However...
Here's a full mysqli_ based method: adding mysqli_real_escape_string() to the POST variable.
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = mysqli_connect($serverName, $userName, $password, $dbname)
or die('Unable to connect to Database host' . mysqli_error());
$studentid = mysqli_real_escape_string($connection,$_POST['student_id']);
$result = mysqli_query($connection,"SELECT `first_name` FROM `students` WHERE student_id = '$studentid'");
while($row = mysqli_fetch_array($result)){
echo $row['first_name'];
}
And technically speaking...
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Regarding SQL injection:
Your present code is open to SQL injection. Use mysqli_* functions. (which I recommend you use and with prepared statements, or PDO)

Change all the mysql to mysqli;
Also add a semicolon after your echo and curly braces { and } for your while

Add curly braces around the statement that is supposed to be executed in the while loop.
I'd also suggest you check out mysql_real_escape_string, to avoid SQL Injection ;-)
Also you have to remove the i in mysqli, since youre using the old MySQL functions.
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$result = mysql_query($connection,"SELECT `first_name` FROM `students` WHERE student_id = '$studentid'");
while($row = mysql_fetch_array($result)){
echo $row['first_name']
}

Ok, there are a lot of little problems here.
First mysql_query() 's syntax is:
mysql_query(query,connection)
so the connection should be the second argument.
In the query string you have to put `` around the column you are comparing to, like this:
WHERE `student_id` = '$studentid'
^here ^and here
mysql_query() and mysqli_fetch_array() can't work together.
It's either mysql_query() with mysql_fetch_array() or mysqli_query() with mysqli_fetch_array().
You have a missing semi-colon on this row:
echo $row['first_name'] // <- here
Also check if the value from $_POST['student_id'] is the one you expect.
That's what I see for now.

I find using mysqli is much faster to connect and call out your results
$connection = new mysqli($serverName, $userName, $password, $databaseName)
if ($connection->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$studentid = $_POST['student_id'];
$sql = "SELECT `first_name` FROM `students` WHERE student_id = '$studentid'";
$results = $connection->query($sql);
If you're just checking for one student, I would just grab one row
if($results->num_rows == 1){
$row = $results->fetch_assoc();
echo $row['first_name'];
}
If you're trying to grab multi student ids
while($row = $results->fetch_assoc()){
echo $row['first_name'];
}

Related

Getting mysqli_query() expects parameter 1 to be mysqli, null given in go daddy server but when i am running on localhost its running correctly [duplicate]

I am trying to select data from a MySQL table, but I get one of the following error messages:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
This is my code:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
while($row = mysql_fetch_array($result)) {
echo $row['FirstName'];
}
A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return false from their respective query functions/methods. You need to test for that error condition and handle it accordingly.
mysql_ extension:
NOTE The mysql_ functions are deprecated and have been removed in php version 7.
Check $result before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the [mysql_query][1] documentation for possible return values and suggestions for how to deal with them.
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
trigger_error(mysql_error(), E_USER_ERROR);
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
This error message is displayed when you have an error in your query which caused it to fail. It will manifest itself when using:
mysql_fetch_array/mysqli_fetch_array()
mysql_fetch_assoc()/mysqli_fetch_assoc()
mysql_num_rows()/mysqli_num_rows()
Note: This error does not appear if no rows are affected by your query. Only a query with an invalid syntax will generate this error.
Troubleshooting Steps
Make sure you have your development server configured to display all errors. You can do this by placing this at the top of your files or in your config file: error_reporting(-1);. If you have any syntax errors this will point them out to you.
Use mysql_error(). mysql_error() will report any errors MySQL encountered while performing your query.
Sample usage:
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name) or die("cannot select DB");
$sql = "SELECT * FROM table_name";
$result = mysql_query($sql);
if (false === $result) {
echo mysql_error();
}
Run your query from the MySQL command line or a tool like phpMyAdmin. If you have a syntax error in your query this will tell you what it is.
Make sure your quotes are correct. A missing quote around the query or a value can cause a query to fail.
Make sure you are escaping your values. Quotes in your query can cause a query to fail (and also leave you open to SQL injections). Use mysql_real_escape_string() to escape your input.
Make sure you are not mixing mysqli_* and mysql_* functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick with mysqli_*. See below for why.)
Other tips
mysql_* functions should not be used for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.
Error occurred here was due to the use of single quotes ('). You can put your query like this:
mysql_query("
SELECT * FROM Users
WHERE UserName
LIKE '".mysql_real_escape_string ($username)."'
");
It's using mysql_real_escape_string for prevention of SQL injection.
Though we should use MySQLi or PDO_MYSQL extension for upgraded version of PHP (PHP 5.5.0 and later), but for older versions mysql_real_escape_string will do the trick.
As scompt.com explained, the query might fail. Use this code the get the error of the query or the correct result:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("
SELECT * FROM Users
WHERE UserName LIKE '".mysql_real_escape_string($username)."'
");
if($result)
{
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
} else {
echo 'Invalid query: ' . mysql_error() . "\n";
echo 'Whole query: ' . $query;
}
See the documentation for mysql_query() for further information.
The actual error was the single quotes so that the variable $username was not parsed. But you should really use mysql_real_escape_string($username) to avoid SQL injections.
Put quotes around $username. String values, as opposed to numeric values, must be enclosed in quotes.
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
Also, there is no point in using the LIKE condition if you're not using wildcards: if you need an exact match use = instead of LIKE.
Please check once the database selected are not because some times database is not selected
Check
mysql_select_db('database name ')or DIE('Database name is not available!');
before MySQL query
and then go to next step
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
f($result === FALSE) {
die(mysql_error());
Your code should be something like this
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM Users WHERE UserName LIKE '$username'";
echo $query;
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error("error message for the user"));
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Once done with that, you would get the query printed on the screen. Try this query on your server and see if it produces the desired results. Most of the times the error is in the query. Rest of the code is correct.
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
You define the string using single quotes and PHP does not parse single quote delimited strings. In order to obtain variable interpolation you will need to use double quotes OR string concatenation (or a combination there of). See http://php.net/manual/en/language.types.string.php for more information.
Also you should check that mysql_query returned a valid result resource, otherwise fetch_*, num_rows, etc will not work on the result as is not a result! IE:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
if( $result === FALSE ) {
trigger_error('Query failed returning error: '. mysql_error(),E_USER_ERROR);
} else {
while( $row = mysql_fetch_array($result) ) {
echo $row['username'];
}
}
http://us.php.net/manual/en/function.mysql-query.php for more information.
This query should work:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
The problem is single quotes, thus your query fails and returns FALSE and your WHILE loop can't execute. Using % allows you to match any results containing your string (such as SomeText-$username-SomeText).
This is simply an answer to your question, you should implement stuff mentioned in the other posts: error handling, use escape strings (users can type anything into the field, and you MUST make sure it is not arbitrary code), use PDO instead mysql_connect which is now depricated.
If you tried everything here, and it does not work, you might want to check your MySQL database collation. Mine was set to to a Swedish collation. Then I changed it to utf8_general_ci and everything just clicked into gear.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Sometimes suppressing the query as #mysql_query(your query);
$query = "SELECT Name,Mobile,Website,Rating FROM grand_table order by 4";
while( $data = mysql_fetch_array($query))
{
echo("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td></tr>");
}
Instead of using a WHERE query, you can use this ORDER BY query. It's far better than this for use of a query.
I have done this query and am getting no errors like parameter or boolean.
Try this, it must be work, otherwise you need to print the error to specify your problem
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from Users WHERE UserName LIKE '$username'";
$result = mysql_query($sql,$con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
There might be two reasons:
Have you opened the connection to the database prior to calling mysql_query function? I don't see that in your code. Use mysql_connect before making the query. See php.net/manual/en/function.mysql-connect.php
The variable $username is used inside a single quote string, so its value will not be evaluated inside the query. The query will definitely fail.
Thirdly, the structure of query is prone to SQL injection. You may use prepared statements to avoid this security threat.
Try the following code. It may work fine.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName ='$username'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Go to your config.php. I had the same problem. Verify the username and the password, and also sql select is the same name as the config.
Don't use the depricated mysql_* function (depricated in php 5.5 will be removed in php 7). and you can make this with mysqli or pdo
here is the complete select query
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// code here
}
} else {
echo "0 results";
}
$conn->close();
?>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '".$username."'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
?>
And if there is a user with a unique user name, you can use "=" for that. There is no need to like.
Your query will be:
mysql_query("SELECT * FROM Users WHERE UserName ='".$username."'");
Include a connection string variable before the MySQL query. For example, $connt in this code:
$results = mysql_query($connt, "SELECT * FROM users");
Any time you get the...
"Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given"
...it is likely because there is an issue with your query. The prepare() or query() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!
First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.
Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
// any additional code you need would go here.
} else {
$error = $mysqli->errno . ' ' . $mysqli->error; // 1054 Unknown column 'foo' in 'field list'
// handle error
}
If something is wrong you can spit out an error message which takes you directly to the issue. In this case, there is no foo column in the table, solving the problem is trivial.
If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '".mysql_real_escape_string($username)."'")or die(mysql_error());
while($row=mysql_fetch_array($result))
{
echo $row['FirstName'];
}
?>
Try This
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query('SELECT * FROM Users WHERE UserName LIKE $username');
if($result){
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
}
}
First, check your connection to the database. Is it connected successfully or not?
If it's done, then after that I have written this code, and it works well:
if (isset($_GET['q1mrks']) && isset($_GET['marks']) && isset($_GET['qt1'])) {
$Q1mrks = $_GET['q1mrks'];
$marks = $_GET['marks'];
$qt1 = $_GET['qt1'];
$qtype_qry = mysql_query("
SELECT *
FROM s_questiontypes
WHERE quetype_id = '$qt1'
");
$row = mysql_fetch_assoc($qtype_qry);
$qcode = $row['quetype_code'];
$sq_qry = "
SELECT *
FROM s_question
WHERE quetype_code = '$qcode'
ORDER BY RAND() LIMIT $Q1mrks
";
$sq_qry = mysql_query("
SELECT *
FROM s_question
WHERE quetype_code = '$qcode'
LIMIT $Q1mrks
");
while ($qrow = mysql_fetch_array($sq_qry)) {
$qm = $qrow['marks'] . "<br />";
$total += $qm . "<br />";
}
echo $total . "/" . $marks;
}
Make Sure You're Not Closing Database By using db_close() Before To
Running Your Query:
If you're using multiple queries in a script even you're including other pages which contains queries or database connection, then it might be possible that at any place you use db_close() that would close your database connection so make sure you're not doing this mistake in your scripts.
If you don't have any MySQL Error appearing while checking, make sure that you properly created your database table. This happened to me. Look for any unwanted commas or quotes.
Check your connection first.
Then if you want to fetch the exact value from the database then you should write:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName =`$usernam`");
Or you want to fetch the LIKE type of value then you should write:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
You can also check wether $result is failing like so, before executing the fetch array
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
if(!$result)
{
echo "error executing query: "+mysql_error();
}else{
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
}
Usually an error occurs when your database conectivity fails, so be sure to connect your database or to include the database file.
include_once(db_connetc.php');
OR
// Create a connection
$connection = mysql_connect("localhost", "root", "") or die(mysql_error());
//Select database
mysql_select_db("db_name", $connection) or die(mysql_error());
$employee_query = "SELECT * FROM employee WHERE `id` ='".$_POST['id']."'";
$employee_data = mysql_query($employee_query);
if (mysql_num_rows($employee_data) > 0) {
while ($row = mysql_fetch_array($employee_data)){
echo $row['emp_name'];
} // end of while loop
} // end of if
Best practice is to run the query in sqlyog and then copy it into your page code.
Always store your query in a variable and then echo that variable. Then pass to mysql_query($query_variable);.
Traditionally PHP has been tolerant to bad practice and failures in code,
which makes debugging quite hard.
The problem in this specific case is that both mysqli and PDO
by default don't tell you, when a query failed and just return FALSE.
(I will not talk about the depricated mysql extention.
The support for prepared statements is reason anough to switch either to PDO or mysqli.)
But you can change the default behavior of PHP to always throw exceptions when a query fails.
For PDO: Use $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
error_reporting(E_ALL);
$pdo = new PDO("mysql:host=localhost;dbname=test", "test","");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->query('select emal from users');
$data = $result->fetchAll();
This will show you the following:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\pdo.php on line 8
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\pdo.php on line 8
As you see, it tells you exactly, what is wrong with the query, and where to fix it in your code.
Without $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
you will get
Fatal error: Call to a member function fetchAll() on boolean in E:\htdocs\test\mysql_errors\pdo.php on line 9
For mysqli: Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'test', '', 'test');
$result = $mysqli->query('select emal from users');
$data = $result->fetch_all();
You will get
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
mysqli_sql_exception: Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
Without mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); you only get
Fatal error: Call to a member function fetch_all() on boolean in E:\htdocs\test\mysql_errors\mysqli.php on line 10
Of course, you could manually check the MySQL errors.
But I would go crazy if I had to do that every time I made a typo -
or worse - every time I want to query the database.
Try this code it work fine
assign the post variable to the variable
$username = $_POST['uname'];
$password = $_POST['pass'];
$result = mysql_query('SELECT * FROM userData WHERE UserName LIKE $username');
if(!empty($result)){
while($row = mysql_fetch_array($result)){
echo $row['FirstName'];
}
}

Having trouble with wamp server setup [duplicate]

I am trying to select data from a MySQL table, but I get one of the following error messages:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
This is my code:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
while($row = mysql_fetch_array($result)) {
echo $row['FirstName'];
}
A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return false from their respective query functions/methods. You need to test for that error condition and handle it accordingly.
mysql_ extension:
NOTE The mysql_ functions are deprecated and have been removed in php version 7.
Check $result before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the [mysql_query][1] documentation for possible return values and suggestions for how to deal with them.
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
trigger_error(mysql_error(), E_USER_ERROR);
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
This error message is displayed when you have an error in your query which caused it to fail. It will manifest itself when using:
mysql_fetch_array/mysqli_fetch_array()
mysql_fetch_assoc()/mysqli_fetch_assoc()
mysql_num_rows()/mysqli_num_rows()
Note: This error does not appear if no rows are affected by your query. Only a query with an invalid syntax will generate this error.
Troubleshooting Steps
Make sure you have your development server configured to display all errors. You can do this by placing this at the top of your files or in your config file: error_reporting(-1);. If you have any syntax errors this will point them out to you.
Use mysql_error(). mysql_error() will report any errors MySQL encountered while performing your query.
Sample usage:
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name) or die("cannot select DB");
$sql = "SELECT * FROM table_name";
$result = mysql_query($sql);
if (false === $result) {
echo mysql_error();
}
Run your query from the MySQL command line or a tool like phpMyAdmin. If you have a syntax error in your query this will tell you what it is.
Make sure your quotes are correct. A missing quote around the query or a value can cause a query to fail.
Make sure you are escaping your values. Quotes in your query can cause a query to fail (and also leave you open to SQL injections). Use mysql_real_escape_string() to escape your input.
Make sure you are not mixing mysqli_* and mysql_* functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick with mysqli_*. See below for why.)
Other tips
mysql_* functions should not be used for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.
Error occurred here was due to the use of single quotes ('). You can put your query like this:
mysql_query("
SELECT * FROM Users
WHERE UserName
LIKE '".mysql_real_escape_string ($username)."'
");
It's using mysql_real_escape_string for prevention of SQL injection.
Though we should use MySQLi or PDO_MYSQL extension for upgraded version of PHP (PHP 5.5.0 and later), but for older versions mysql_real_escape_string will do the trick.
As scompt.com explained, the query might fail. Use this code the get the error of the query or the correct result:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("
SELECT * FROM Users
WHERE UserName LIKE '".mysql_real_escape_string($username)."'
");
if($result)
{
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
} else {
echo 'Invalid query: ' . mysql_error() . "\n";
echo 'Whole query: ' . $query;
}
See the documentation for mysql_query() for further information.
The actual error was the single quotes so that the variable $username was not parsed. But you should really use mysql_real_escape_string($username) to avoid SQL injections.
Put quotes around $username. String values, as opposed to numeric values, must be enclosed in quotes.
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
Also, there is no point in using the LIKE condition if you're not using wildcards: if you need an exact match use = instead of LIKE.
Please check once the database selected are not because some times database is not selected
Check
mysql_select_db('database name ')or DIE('Database name is not available!');
before MySQL query
and then go to next step
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
f($result === FALSE) {
die(mysql_error());
Your code should be something like this
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM Users WHERE UserName LIKE '$username'";
echo $query;
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error("error message for the user"));
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Once done with that, you would get the query printed on the screen. Try this query on your server and see if it produces the desired results. Most of the times the error is in the query. Rest of the code is correct.
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
You define the string using single quotes and PHP does not parse single quote delimited strings. In order to obtain variable interpolation you will need to use double quotes OR string concatenation (or a combination there of). See http://php.net/manual/en/language.types.string.php for more information.
Also you should check that mysql_query returned a valid result resource, otherwise fetch_*, num_rows, etc will not work on the result as is not a result! IE:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
if( $result === FALSE ) {
trigger_error('Query failed returning error: '. mysql_error(),E_USER_ERROR);
} else {
while( $row = mysql_fetch_array($result) ) {
echo $row['username'];
}
}
http://us.php.net/manual/en/function.mysql-query.php for more information.
This query should work:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
The problem is single quotes, thus your query fails and returns FALSE and your WHILE loop can't execute. Using % allows you to match any results containing your string (such as SomeText-$username-SomeText).
This is simply an answer to your question, you should implement stuff mentioned in the other posts: error handling, use escape strings (users can type anything into the field, and you MUST make sure it is not arbitrary code), use PDO instead mysql_connect which is now depricated.
If you tried everything here, and it does not work, you might want to check your MySQL database collation. Mine was set to to a Swedish collation. Then I changed it to utf8_general_ci and everything just clicked into gear.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Sometimes suppressing the query as #mysql_query(your query);
$query = "SELECT Name,Mobile,Website,Rating FROM grand_table order by 4";
while( $data = mysql_fetch_array($query))
{
echo("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td></tr>");
}
Instead of using a WHERE query, you can use this ORDER BY query. It's far better than this for use of a query.
I have done this query and am getting no errors like parameter or boolean.
Try this, it must be work, otherwise you need to print the error to specify your problem
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from Users WHERE UserName LIKE '$username'";
$result = mysql_query($sql,$con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
There might be two reasons:
Have you opened the connection to the database prior to calling mysql_query function? I don't see that in your code. Use mysql_connect before making the query. See php.net/manual/en/function.mysql-connect.php
The variable $username is used inside a single quote string, so its value will not be evaluated inside the query. The query will definitely fail.
Thirdly, the structure of query is prone to SQL injection. You may use prepared statements to avoid this security threat.
Try the following code. It may work fine.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName ='$username'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Go to your config.php. I had the same problem. Verify the username and the password, and also sql select is the same name as the config.
Don't use the depricated mysql_* function (depricated in php 5.5 will be removed in php 7). and you can make this with mysqli or pdo
here is the complete select query
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// code here
}
} else {
echo "0 results";
}
$conn->close();
?>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '".$username."'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
?>
And if there is a user with a unique user name, you can use "=" for that. There is no need to like.
Your query will be:
mysql_query("SELECT * FROM Users WHERE UserName ='".$username."'");
Include a connection string variable before the MySQL query. For example, $connt in this code:
$results = mysql_query($connt, "SELECT * FROM users");
Any time you get the...
"Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given"
...it is likely because there is an issue with your query. The prepare() or query() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!
First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.
Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
// any additional code you need would go here.
} else {
$error = $mysqli->errno . ' ' . $mysqli->error; // 1054 Unknown column 'foo' in 'field list'
// handle error
}
If something is wrong you can spit out an error message which takes you directly to the issue. In this case, there is no foo column in the table, solving the problem is trivial.
If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '".mysql_real_escape_string($username)."'")or die(mysql_error());
while($row=mysql_fetch_array($result))
{
echo $row['FirstName'];
}
?>
Try This
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query('SELECT * FROM Users WHERE UserName LIKE $username');
if($result){
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
}
}
First, check your connection to the database. Is it connected successfully or not?
If it's done, then after that I have written this code, and it works well:
if (isset($_GET['q1mrks']) && isset($_GET['marks']) && isset($_GET['qt1'])) {
$Q1mrks = $_GET['q1mrks'];
$marks = $_GET['marks'];
$qt1 = $_GET['qt1'];
$qtype_qry = mysql_query("
SELECT *
FROM s_questiontypes
WHERE quetype_id = '$qt1'
");
$row = mysql_fetch_assoc($qtype_qry);
$qcode = $row['quetype_code'];
$sq_qry = "
SELECT *
FROM s_question
WHERE quetype_code = '$qcode'
ORDER BY RAND() LIMIT $Q1mrks
";
$sq_qry = mysql_query("
SELECT *
FROM s_question
WHERE quetype_code = '$qcode'
LIMIT $Q1mrks
");
while ($qrow = mysql_fetch_array($sq_qry)) {
$qm = $qrow['marks'] . "<br />";
$total += $qm . "<br />";
}
echo $total . "/" . $marks;
}
Make Sure You're Not Closing Database By using db_close() Before To
Running Your Query:
If you're using multiple queries in a script even you're including other pages which contains queries or database connection, then it might be possible that at any place you use db_close() that would close your database connection so make sure you're not doing this mistake in your scripts.
If you don't have any MySQL Error appearing while checking, make sure that you properly created your database table. This happened to me. Look for any unwanted commas or quotes.
Check your connection first.
Then if you want to fetch the exact value from the database then you should write:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName =`$usernam`");
Or you want to fetch the LIKE type of value then you should write:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
You can also check wether $result is failing like so, before executing the fetch array
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
if(!$result)
{
echo "error executing query: "+mysql_error();
}else{
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
}
Usually an error occurs when your database conectivity fails, so be sure to connect your database or to include the database file.
include_once(db_connetc.php');
OR
// Create a connection
$connection = mysql_connect("localhost", "root", "") or die(mysql_error());
//Select database
mysql_select_db("db_name", $connection) or die(mysql_error());
$employee_query = "SELECT * FROM employee WHERE `id` ='".$_POST['id']."'";
$employee_data = mysql_query($employee_query);
if (mysql_num_rows($employee_data) > 0) {
while ($row = mysql_fetch_array($employee_data)){
echo $row['emp_name'];
} // end of while loop
} // end of if
Best practice is to run the query in sqlyog and then copy it into your page code.
Always store your query in a variable and then echo that variable. Then pass to mysql_query($query_variable);.
Traditionally PHP has been tolerant to bad practice and failures in code,
which makes debugging quite hard.
The problem in this specific case is that both mysqli and PDO
by default don't tell you, when a query failed and just return FALSE.
(I will not talk about the depricated mysql extention.
The support for prepared statements is reason anough to switch either to PDO or mysqli.)
But you can change the default behavior of PHP to always throw exceptions when a query fails.
For PDO: Use $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
error_reporting(E_ALL);
$pdo = new PDO("mysql:host=localhost;dbname=test", "test","");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->query('select emal from users');
$data = $result->fetchAll();
This will show you the following:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\pdo.php on line 8
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\pdo.php on line 8
As you see, it tells you exactly, what is wrong with the query, and where to fix it in your code.
Without $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
you will get
Fatal error: Call to a member function fetchAll() on boolean in E:\htdocs\test\mysql_errors\pdo.php on line 9
For mysqli: Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'test', '', 'test');
$result = $mysqli->query('select emal from users');
$data = $result->fetch_all();
You will get
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
mysqli_sql_exception: Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
Without mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); you only get
Fatal error: Call to a member function fetch_all() on boolean in E:\htdocs\test\mysql_errors\mysqli.php on line 10
Of course, you could manually check the MySQL errors.
But I would go crazy if I had to do that every time I made a typo -
or worse - every time I want to query the database.
Try this code it work fine
assign the post variable to the variable
$username = $_POST['uname'];
$password = $_POST['pass'];
$result = mysql_query('SELECT * FROM userData WHERE UserName LIKE $username');
if(!empty($result)){
while($row = mysql_fetch_array($result)){
echo $row['FirstName'];
}
}

mysql_fetch_assoc does not work for stored procedure output, but works with a normal sql_query [duplicate]

I am trying to select data from a MySQL table, but I get one of the following error messages:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
This is my code:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
while($row = mysql_fetch_array($result)) {
echo $row['FirstName'];
}
A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return false from their respective query functions/methods. You need to test for that error condition and handle it accordingly.
mysql_ extension:
NOTE The mysql_ functions are deprecated and have been removed in php version 7.
Check $result before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the [mysql_query][1] documentation for possible return values and suggestions for how to deal with them.
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
trigger_error(mysql_error(), E_USER_ERROR);
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
This error message is displayed when you have an error in your query which caused it to fail. It will manifest itself when using:
mysql_fetch_array/mysqli_fetch_array()
mysql_fetch_assoc()/mysqli_fetch_assoc()
mysql_num_rows()/mysqli_num_rows()
Note: This error does not appear if no rows are affected by your query. Only a query with an invalid syntax will generate this error.
Troubleshooting Steps
Make sure you have your development server configured to display all errors. You can do this by placing this at the top of your files or in your config file: error_reporting(-1);. If you have any syntax errors this will point them out to you.
Use mysql_error(). mysql_error() will report any errors MySQL encountered while performing your query.
Sample usage:
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name) or die("cannot select DB");
$sql = "SELECT * FROM table_name";
$result = mysql_query($sql);
if (false === $result) {
echo mysql_error();
}
Run your query from the MySQL command line or a tool like phpMyAdmin. If you have a syntax error in your query this will tell you what it is.
Make sure your quotes are correct. A missing quote around the query or a value can cause a query to fail.
Make sure you are escaping your values. Quotes in your query can cause a query to fail (and also leave you open to SQL injections). Use mysql_real_escape_string() to escape your input.
Make sure you are not mixing mysqli_* and mysql_* functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick with mysqli_*. See below for why.)
Other tips
mysql_* functions should not be used for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.
Error occurred here was due to the use of single quotes ('). You can put your query like this:
mysql_query("
SELECT * FROM Users
WHERE UserName
LIKE '".mysql_real_escape_string ($username)."'
");
It's using mysql_real_escape_string for prevention of SQL injection.
Though we should use MySQLi or PDO_MYSQL extension for upgraded version of PHP (PHP 5.5.0 and later), but for older versions mysql_real_escape_string will do the trick.
As scompt.com explained, the query might fail. Use this code the get the error of the query or the correct result:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("
SELECT * FROM Users
WHERE UserName LIKE '".mysql_real_escape_string($username)."'
");
if($result)
{
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
} else {
echo 'Invalid query: ' . mysql_error() . "\n";
echo 'Whole query: ' . $query;
}
See the documentation for mysql_query() for further information.
The actual error was the single quotes so that the variable $username was not parsed. But you should really use mysql_real_escape_string($username) to avoid SQL injections.
Put quotes around $username. String values, as opposed to numeric values, must be enclosed in quotes.
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
Also, there is no point in using the LIKE condition if you're not using wildcards: if you need an exact match use = instead of LIKE.
Please check once the database selected are not because some times database is not selected
Check
mysql_select_db('database name ')or DIE('Database name is not available!');
before MySQL query
and then go to next step
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
f($result === FALSE) {
die(mysql_error());
Your code should be something like this
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM Users WHERE UserName LIKE '$username'";
echo $query;
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error("error message for the user"));
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Once done with that, you would get the query printed on the screen. Try this query on your server and see if it produces the desired results. Most of the times the error is in the query. Rest of the code is correct.
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
You define the string using single quotes and PHP does not parse single quote delimited strings. In order to obtain variable interpolation you will need to use double quotes OR string concatenation (or a combination there of). See http://php.net/manual/en/language.types.string.php for more information.
Also you should check that mysql_query returned a valid result resource, otherwise fetch_*, num_rows, etc will not work on the result as is not a result! IE:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
if( $result === FALSE ) {
trigger_error('Query failed returning error: '. mysql_error(),E_USER_ERROR);
} else {
while( $row = mysql_fetch_array($result) ) {
echo $row['username'];
}
}
http://us.php.net/manual/en/function.mysql-query.php for more information.
This query should work:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
The problem is single quotes, thus your query fails and returns FALSE and your WHILE loop can't execute. Using % allows you to match any results containing your string (such as SomeText-$username-SomeText).
This is simply an answer to your question, you should implement stuff mentioned in the other posts: error handling, use escape strings (users can type anything into the field, and you MUST make sure it is not arbitrary code), use PDO instead mysql_connect which is now depricated.
If you tried everything here, and it does not work, you might want to check your MySQL database collation. Mine was set to to a Swedish collation. Then I changed it to utf8_general_ci and everything just clicked into gear.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Sometimes suppressing the query as #mysql_query(your query);
$query = "SELECT Name,Mobile,Website,Rating FROM grand_table order by 4";
while( $data = mysql_fetch_array($query))
{
echo("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td></tr>");
}
Instead of using a WHERE query, you can use this ORDER BY query. It's far better than this for use of a query.
I have done this query and am getting no errors like parameter or boolean.
Try this, it must be work, otherwise you need to print the error to specify your problem
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from Users WHERE UserName LIKE '$username'";
$result = mysql_query($sql,$con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
There might be two reasons:
Have you opened the connection to the database prior to calling mysql_query function? I don't see that in your code. Use mysql_connect before making the query. See php.net/manual/en/function.mysql-connect.php
The variable $username is used inside a single quote string, so its value will not be evaluated inside the query. The query will definitely fail.
Thirdly, the structure of query is prone to SQL injection. You may use prepared statements to avoid this security threat.
Try the following code. It may work fine.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName ='$username'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Go to your config.php. I had the same problem. Verify the username and the password, and also sql select is the same name as the config.
Don't use the depricated mysql_* function (depricated in php 5.5 will be removed in php 7). and you can make this with mysqli or pdo
here is the complete select query
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// code here
}
} else {
echo "0 results";
}
$conn->close();
?>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '".$username."'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
?>
And if there is a user with a unique user name, you can use "=" for that. There is no need to like.
Your query will be:
mysql_query("SELECT * FROM Users WHERE UserName ='".$username."'");
Include a connection string variable before the MySQL query. For example, $connt in this code:
$results = mysql_query($connt, "SELECT * FROM users");
Any time you get the...
"Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given"
...it is likely because there is an issue with your query. The prepare() or query() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!
First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.
Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
// any additional code you need would go here.
} else {
$error = $mysqli->errno . ' ' . $mysqli->error; // 1054 Unknown column 'foo' in 'field list'
// handle error
}
If something is wrong you can spit out an error message which takes you directly to the issue. In this case, there is no foo column in the table, solving the problem is trivial.
If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '".mysql_real_escape_string($username)."'")or die(mysql_error());
while($row=mysql_fetch_array($result))
{
echo $row['FirstName'];
}
?>
Try This
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query('SELECT * FROM Users WHERE UserName LIKE $username');
if($result){
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
}
}
First, check your connection to the database. Is it connected successfully or not?
If it's done, then after that I have written this code, and it works well:
if (isset($_GET['q1mrks']) && isset($_GET['marks']) && isset($_GET['qt1'])) {
$Q1mrks = $_GET['q1mrks'];
$marks = $_GET['marks'];
$qt1 = $_GET['qt1'];
$qtype_qry = mysql_query("
SELECT *
FROM s_questiontypes
WHERE quetype_id = '$qt1'
");
$row = mysql_fetch_assoc($qtype_qry);
$qcode = $row['quetype_code'];
$sq_qry = "
SELECT *
FROM s_question
WHERE quetype_code = '$qcode'
ORDER BY RAND() LIMIT $Q1mrks
";
$sq_qry = mysql_query("
SELECT *
FROM s_question
WHERE quetype_code = '$qcode'
LIMIT $Q1mrks
");
while ($qrow = mysql_fetch_array($sq_qry)) {
$qm = $qrow['marks'] . "<br />";
$total += $qm . "<br />";
}
echo $total . "/" . $marks;
}
Make Sure You're Not Closing Database By using db_close() Before To
Running Your Query:
If you're using multiple queries in a script even you're including other pages which contains queries or database connection, then it might be possible that at any place you use db_close() that would close your database connection so make sure you're not doing this mistake in your scripts.
If you don't have any MySQL Error appearing while checking, make sure that you properly created your database table. This happened to me. Look for any unwanted commas or quotes.
Check your connection first.
Then if you want to fetch the exact value from the database then you should write:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName =`$usernam`");
Or you want to fetch the LIKE type of value then you should write:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
You can also check wether $result is failing like so, before executing the fetch array
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
if(!$result)
{
echo "error executing query: "+mysql_error();
}else{
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
}
Usually an error occurs when your database conectivity fails, so be sure to connect your database or to include the database file.
include_once(db_connetc.php');
OR
// Create a connection
$connection = mysql_connect("localhost", "root", "") or die(mysql_error());
//Select database
mysql_select_db("db_name", $connection) or die(mysql_error());
$employee_query = "SELECT * FROM employee WHERE `id` ='".$_POST['id']."'";
$employee_data = mysql_query($employee_query);
if (mysql_num_rows($employee_data) > 0) {
while ($row = mysql_fetch_array($employee_data)){
echo $row['emp_name'];
} // end of while loop
} // end of if
Best practice is to run the query in sqlyog and then copy it into your page code.
Always store your query in a variable and then echo that variable. Then pass to mysql_query($query_variable);.
Traditionally PHP has been tolerant to bad practice and failures in code,
which makes debugging quite hard.
The problem in this specific case is that both mysqli and PDO
by default don't tell you, when a query failed and just return FALSE.
(I will not talk about the depricated mysql extention.
The support for prepared statements is reason anough to switch either to PDO or mysqli.)
But you can change the default behavior of PHP to always throw exceptions when a query fails.
For PDO: Use $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
error_reporting(E_ALL);
$pdo = new PDO("mysql:host=localhost;dbname=test", "test","");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->query('select emal from users');
$data = $result->fetchAll();
This will show you the following:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\pdo.php on line 8
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\pdo.php on line 8
As you see, it tells you exactly, what is wrong with the query, and where to fix it in your code.
Without $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
you will get
Fatal error: Call to a member function fetchAll() on boolean in E:\htdocs\test\mysql_errors\pdo.php on line 9
For mysqli: Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'test', '', 'test');
$result = $mysqli->query('select emal from users');
$data = $result->fetch_all();
You will get
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
mysqli_sql_exception: Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
Without mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); you only get
Fatal error: Call to a member function fetch_all() on boolean in E:\htdocs\test\mysql_errors\mysqli.php on line 10
Of course, you could manually check the MySQL errors.
But I would go crazy if I had to do that every time I made a typo -
or worse - every time I want to query the database.
Try this code it work fine
assign the post variable to the variable
$username = $_POST['uname'];
$password = $_POST['pass'];
$result = mysql_query('SELECT * FROM userData WHERE UserName LIKE $username');
if(!empty($result)){
while($row = mysql_fetch_array($result)){
echo $row['FirstName'];
}
}

mysql_query returning a bool? [duplicate]

I am trying to select data from a MySQL table, but I get one of the following error messages:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
This is my code:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
while($row = mysql_fetch_array($result)) {
echo $row['FirstName'];
}
A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return false from their respective query functions/methods. You need to test for that error condition and handle it accordingly.
mysql_ extension:
NOTE The mysql_ functions are deprecated and have been removed in php version 7.
Check $result before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the [mysql_query][1] documentation for possible return values and suggestions for how to deal with them.
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
trigger_error(mysql_error(), E_USER_ERROR);
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
This error message is displayed when you have an error in your query which caused it to fail. It will manifest itself when using:
mysql_fetch_array/mysqli_fetch_array()
mysql_fetch_assoc()/mysqli_fetch_assoc()
mysql_num_rows()/mysqli_num_rows()
Note: This error does not appear if no rows are affected by your query. Only a query with an invalid syntax will generate this error.
Troubleshooting Steps
Make sure you have your development server configured to display all errors. You can do this by placing this at the top of your files or in your config file: error_reporting(-1);. If you have any syntax errors this will point them out to you.
Use mysql_error(). mysql_error() will report any errors MySQL encountered while performing your query.
Sample usage:
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name) or die("cannot select DB");
$sql = "SELECT * FROM table_name";
$result = mysql_query($sql);
if (false === $result) {
echo mysql_error();
}
Run your query from the MySQL command line or a tool like phpMyAdmin. If you have a syntax error in your query this will tell you what it is.
Make sure your quotes are correct. A missing quote around the query or a value can cause a query to fail.
Make sure you are escaping your values. Quotes in your query can cause a query to fail (and also leave you open to SQL injections). Use mysql_real_escape_string() to escape your input.
Make sure you are not mixing mysqli_* and mysql_* functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick with mysqli_*. See below for why.)
Other tips
mysql_* functions should not be used for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.
Error occurred here was due to the use of single quotes ('). You can put your query like this:
mysql_query("
SELECT * FROM Users
WHERE UserName
LIKE '".mysql_real_escape_string ($username)."'
");
It's using mysql_real_escape_string for prevention of SQL injection.
Though we should use MySQLi or PDO_MYSQL extension for upgraded version of PHP (PHP 5.5.0 and later), but for older versions mysql_real_escape_string will do the trick.
As scompt.com explained, the query might fail. Use this code the get the error of the query or the correct result:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("
SELECT * FROM Users
WHERE UserName LIKE '".mysql_real_escape_string($username)."'
");
if($result)
{
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
} else {
echo 'Invalid query: ' . mysql_error() . "\n";
echo 'Whole query: ' . $query;
}
See the documentation for mysql_query() for further information.
The actual error was the single quotes so that the variable $username was not parsed. But you should really use mysql_real_escape_string($username) to avoid SQL injections.
Put quotes around $username. String values, as opposed to numeric values, must be enclosed in quotes.
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
Also, there is no point in using the LIKE condition if you're not using wildcards: if you need an exact match use = instead of LIKE.
Please check once the database selected are not because some times database is not selected
Check
mysql_select_db('database name ')or DIE('Database name is not available!');
before MySQL query
and then go to next step
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
f($result === FALSE) {
die(mysql_error());
Your code should be something like this
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM Users WHERE UserName LIKE '$username'";
echo $query;
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error("error message for the user"));
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Once done with that, you would get the query printed on the screen. Try this query on your server and see if it produces the desired results. Most of the times the error is in the query. Rest of the code is correct.
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
You define the string using single quotes and PHP does not parse single quote delimited strings. In order to obtain variable interpolation you will need to use double quotes OR string concatenation (or a combination there of). See http://php.net/manual/en/language.types.string.php for more information.
Also you should check that mysql_query returned a valid result resource, otherwise fetch_*, num_rows, etc will not work on the result as is not a result! IE:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
if( $result === FALSE ) {
trigger_error('Query failed returning error: '. mysql_error(),E_USER_ERROR);
} else {
while( $row = mysql_fetch_array($result) ) {
echo $row['username'];
}
}
http://us.php.net/manual/en/function.mysql-query.php for more information.
This query should work:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
The problem is single quotes, thus your query fails and returns FALSE and your WHILE loop can't execute. Using % allows you to match any results containing your string (such as SomeText-$username-SomeText).
This is simply an answer to your question, you should implement stuff mentioned in the other posts: error handling, use escape strings (users can type anything into the field, and you MUST make sure it is not arbitrary code), use PDO instead mysql_connect which is now depricated.
If you tried everything here, and it does not work, you might want to check your MySQL database collation. Mine was set to to a Swedish collation. Then I changed it to utf8_general_ci and everything just clicked into gear.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Sometimes suppressing the query as #mysql_query(your query);
$query = "SELECT Name,Mobile,Website,Rating FROM grand_table order by 4";
while( $data = mysql_fetch_array($query))
{
echo("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td></tr>");
}
Instead of using a WHERE query, you can use this ORDER BY query. It's far better than this for use of a query.
I have done this query and am getting no errors like parameter or boolean.
Try this, it must be work, otherwise you need to print the error to specify your problem
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from Users WHERE UserName LIKE '$username'";
$result = mysql_query($sql,$con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
There might be two reasons:
Have you opened the connection to the database prior to calling mysql_query function? I don't see that in your code. Use mysql_connect before making the query. See php.net/manual/en/function.mysql-connect.php
The variable $username is used inside a single quote string, so its value will not be evaluated inside the query. The query will definitely fail.
Thirdly, the structure of query is prone to SQL injection. You may use prepared statements to avoid this security threat.
Try the following code. It may work fine.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName ='$username'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Go to your config.php. I had the same problem. Verify the username and the password, and also sql select is the same name as the config.
Don't use the depricated mysql_* function (depricated in php 5.5 will be removed in php 7). and you can make this with mysqli or pdo
here is the complete select query
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// code here
}
} else {
echo "0 results";
}
$conn->close();
?>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '".$username."'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
?>
And if there is a user with a unique user name, you can use "=" for that. There is no need to like.
Your query will be:
mysql_query("SELECT * FROM Users WHERE UserName ='".$username."'");
Include a connection string variable before the MySQL query. For example, $connt in this code:
$results = mysql_query($connt, "SELECT * FROM users");
Any time you get the...
"Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given"
...it is likely because there is an issue with your query. The prepare() or query() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!
First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.
Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
// any additional code you need would go here.
} else {
$error = $mysqli->errno . ' ' . $mysqli->error; // 1054 Unknown column 'foo' in 'field list'
// handle error
}
If something is wrong you can spit out an error message which takes you directly to the issue. In this case, there is no foo column in the table, solving the problem is trivial.
If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '".mysql_real_escape_string($username)."'")or die(mysql_error());
while($row=mysql_fetch_array($result))
{
echo $row['FirstName'];
}
?>
Try This
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query('SELECT * FROM Users WHERE UserName LIKE $username');
if($result){
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
}
}
First, check your connection to the database. Is it connected successfully or not?
If it's done, then after that I have written this code, and it works well:
if (isset($_GET['q1mrks']) && isset($_GET['marks']) && isset($_GET['qt1'])) {
$Q1mrks = $_GET['q1mrks'];
$marks = $_GET['marks'];
$qt1 = $_GET['qt1'];
$qtype_qry = mysql_query("
SELECT *
FROM s_questiontypes
WHERE quetype_id = '$qt1'
");
$row = mysql_fetch_assoc($qtype_qry);
$qcode = $row['quetype_code'];
$sq_qry = "
SELECT *
FROM s_question
WHERE quetype_code = '$qcode'
ORDER BY RAND() LIMIT $Q1mrks
";
$sq_qry = mysql_query("
SELECT *
FROM s_question
WHERE quetype_code = '$qcode'
LIMIT $Q1mrks
");
while ($qrow = mysql_fetch_array($sq_qry)) {
$qm = $qrow['marks'] . "<br />";
$total += $qm . "<br />";
}
echo $total . "/" . $marks;
}
Make Sure You're Not Closing Database By using db_close() Before To
Running Your Query:
If you're using multiple queries in a script even you're including other pages which contains queries or database connection, then it might be possible that at any place you use db_close() that would close your database connection so make sure you're not doing this mistake in your scripts.
If you don't have any MySQL Error appearing while checking, make sure that you properly created your database table. This happened to me. Look for any unwanted commas or quotes.
Check your connection first.
Then if you want to fetch the exact value from the database then you should write:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName =`$usernam`");
Or you want to fetch the LIKE type of value then you should write:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
You can also check wether $result is failing like so, before executing the fetch array
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
if(!$result)
{
echo "error executing query: "+mysql_error();
}else{
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
}
Usually an error occurs when your database conectivity fails, so be sure to connect your database or to include the database file.
include_once(db_connetc.php');
OR
// Create a connection
$connection = mysql_connect("localhost", "root", "") or die(mysql_error());
//Select database
mysql_select_db("db_name", $connection) or die(mysql_error());
$employee_query = "SELECT * FROM employee WHERE `id` ='".$_POST['id']."'";
$employee_data = mysql_query($employee_query);
if (mysql_num_rows($employee_data) > 0) {
while ($row = mysql_fetch_array($employee_data)){
echo $row['emp_name'];
} // end of while loop
} // end of if
Best practice is to run the query in sqlyog and then copy it into your page code.
Always store your query in a variable and then echo that variable. Then pass to mysql_query($query_variable);.
Traditionally PHP has been tolerant to bad practice and failures in code,
which makes debugging quite hard.
The problem in this specific case is that both mysqli and PDO
by default don't tell you, when a query failed and just return FALSE.
(I will not talk about the depricated mysql extention.
The support for prepared statements is reason anough to switch either to PDO or mysqli.)
But you can change the default behavior of PHP to always throw exceptions when a query fails.
For PDO: Use $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
error_reporting(E_ALL);
$pdo = new PDO("mysql:host=localhost;dbname=test", "test","");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->query('select emal from users');
$data = $result->fetchAll();
This will show you the following:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\pdo.php on line 8
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\pdo.php on line 8
As you see, it tells you exactly, what is wrong with the query, and where to fix it in your code.
Without $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
you will get
Fatal error: Call to a member function fetchAll() on boolean in E:\htdocs\test\mysql_errors\pdo.php on line 9
For mysqli: Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'test', '', 'test');
$result = $mysqli->query('select emal from users');
$data = $result->fetch_all();
You will get
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
mysqli_sql_exception: Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
Without mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); you only get
Fatal error: Call to a member function fetch_all() on boolean in E:\htdocs\test\mysql_errors\mysqli.php on line 10
Of course, you could manually check the MySQL errors.
But I would go crazy if I had to do that every time I made a typo -
or worse - every time I want to query the database.
Try this code it work fine
assign the post variable to the variable
$username = $_POST['uname'];
$password = $_POST['pass'];
$result = mysql_query('SELECT * FROM userData WHERE UserName LIKE $username');
if(!empty($result)){
while($row = mysql_fetch_array($result)){
echo $row['FirstName'];
}
}

for loop call procedure mysql_fetch_array() expects parameter 1 to be resource, boolean given in [duplicate]

I am trying to select data from a MySQL table, but I get one of the following error messages:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
This is my code:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
while($row = mysql_fetch_array($result)) {
echo $row['FirstName'];
}
A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return false from their respective query functions/methods. You need to test for that error condition and handle it accordingly.
mysql_ extension:
NOTE The mysql_ functions are deprecated and have been removed in php version 7.
Check $result before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the [mysql_query][1] documentation for possible return values and suggestions for how to deal with them.
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
trigger_error(mysql_error(), E_USER_ERROR);
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
This error message is displayed when you have an error in your query which caused it to fail. It will manifest itself when using:
mysql_fetch_array/mysqli_fetch_array()
mysql_fetch_assoc()/mysqli_fetch_assoc()
mysql_num_rows()/mysqli_num_rows()
Note: This error does not appear if no rows are affected by your query. Only a query with an invalid syntax will generate this error.
Troubleshooting Steps
Make sure you have your development server configured to display all errors. You can do this by placing this at the top of your files or in your config file: error_reporting(-1);. If you have any syntax errors this will point them out to you.
Use mysql_error(). mysql_error() will report any errors MySQL encountered while performing your query.
Sample usage:
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name) or die("cannot select DB");
$sql = "SELECT * FROM table_name";
$result = mysql_query($sql);
if (false === $result) {
echo mysql_error();
}
Run your query from the MySQL command line or a tool like phpMyAdmin. If you have a syntax error in your query this will tell you what it is.
Make sure your quotes are correct. A missing quote around the query or a value can cause a query to fail.
Make sure you are escaping your values. Quotes in your query can cause a query to fail (and also leave you open to SQL injections). Use mysql_real_escape_string() to escape your input.
Make sure you are not mixing mysqli_* and mysql_* functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick with mysqli_*. See below for why.)
Other tips
mysql_* functions should not be used for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.
Error occurred here was due to the use of single quotes ('). You can put your query like this:
mysql_query("
SELECT * FROM Users
WHERE UserName
LIKE '".mysql_real_escape_string ($username)."'
");
It's using mysql_real_escape_string for prevention of SQL injection.
Though we should use MySQLi or PDO_MYSQL extension for upgraded version of PHP (PHP 5.5.0 and later), but for older versions mysql_real_escape_string will do the trick.
As scompt.com explained, the query might fail. Use this code the get the error of the query or the correct result:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("
SELECT * FROM Users
WHERE UserName LIKE '".mysql_real_escape_string($username)."'
");
if($result)
{
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
} else {
echo 'Invalid query: ' . mysql_error() . "\n";
echo 'Whole query: ' . $query;
}
See the documentation for mysql_query() for further information.
The actual error was the single quotes so that the variable $username was not parsed. But you should really use mysql_real_escape_string($username) to avoid SQL injections.
Put quotes around $username. String values, as opposed to numeric values, must be enclosed in quotes.
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
Also, there is no point in using the LIKE condition if you're not using wildcards: if you need an exact match use = instead of LIKE.
Please check once the database selected are not because some times database is not selected
Check
mysql_select_db('database name ')or DIE('Database name is not available!');
before MySQL query
and then go to next step
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
f($result === FALSE) {
die(mysql_error());
Your code should be something like this
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM Users WHERE UserName LIKE '$username'";
echo $query;
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error("error message for the user"));
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Once done with that, you would get the query printed on the screen. Try this query on your server and see if it produces the desired results. Most of the times the error is in the query. Rest of the code is correct.
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
You define the string using single quotes and PHP does not parse single quote delimited strings. In order to obtain variable interpolation you will need to use double quotes OR string concatenation (or a combination there of). See http://php.net/manual/en/language.types.string.php for more information.
Also you should check that mysql_query returned a valid result resource, otherwise fetch_*, num_rows, etc will not work on the result as is not a result! IE:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
if( $result === FALSE ) {
trigger_error('Query failed returning error: '. mysql_error(),E_USER_ERROR);
} else {
while( $row = mysql_fetch_array($result) ) {
echo $row['username'];
}
}
http://us.php.net/manual/en/function.mysql-query.php for more information.
This query should work:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
The problem is single quotes, thus your query fails and returns FALSE and your WHILE loop can't execute. Using % allows you to match any results containing your string (such as SomeText-$username-SomeText).
This is simply an answer to your question, you should implement stuff mentioned in the other posts: error handling, use escape strings (users can type anything into the field, and you MUST make sure it is not arbitrary code), use PDO instead mysql_connect which is now depricated.
If you tried everything here, and it does not work, you might want to check your MySQL database collation. Mine was set to to a Swedish collation. Then I changed it to utf8_general_ci and everything just clicked into gear.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Sometimes suppressing the query as #mysql_query(your query);
$query = "SELECT Name,Mobile,Website,Rating FROM grand_table order by 4";
while( $data = mysql_fetch_array($query))
{
echo("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td></tr>");
}
Instead of using a WHERE query, you can use this ORDER BY query. It's far better than this for use of a query.
I have done this query and am getting no errors like parameter or boolean.
Try this, it must be work, otherwise you need to print the error to specify your problem
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from Users WHERE UserName LIKE '$username'";
$result = mysql_query($sql,$con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
There might be two reasons:
Have you opened the connection to the database prior to calling mysql_query function? I don't see that in your code. Use mysql_connect before making the query. See php.net/manual/en/function.mysql-connect.php
The variable $username is used inside a single quote string, so its value will not be evaluated inside the query. The query will definitely fail.
Thirdly, the structure of query is prone to SQL injection. You may use prepared statements to avoid this security threat.
Try the following code. It may work fine.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName ='$username'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
Go to your config.php. I had the same problem. Verify the username and the password, and also sql select is the same name as the config.
Don't use the depricated mysql_* function (depricated in php 5.5 will be removed in php 7). and you can make this with mysqli or pdo
here is the complete select query
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// code here
}
} else {
echo "0 results";
}
$conn->close();
?>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '".$username."'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
?>
And if there is a user with a unique user name, you can use "=" for that. There is no need to like.
Your query will be:
mysql_query("SELECT * FROM Users WHERE UserName ='".$username."'");
Include a connection string variable before the MySQL query. For example, $connt in this code:
$results = mysql_query($connt, "SELECT * FROM users");
Any time you get the...
"Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given"
...it is likely because there is an issue with your query. The prepare() or query() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!
First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.
Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
// any additional code you need would go here.
} else {
$error = $mysqli->errno . ' ' . $mysqli->error; // 1054 Unknown column 'foo' in 'field list'
// handle error
}
If something is wrong you can spit out an error message which takes you directly to the issue. In this case, there is no foo column in the table, solving the problem is trivial.
If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '".mysql_real_escape_string($username)."'")or die(mysql_error());
while($row=mysql_fetch_array($result))
{
echo $row['FirstName'];
}
?>
Try This
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query('SELECT * FROM Users WHERE UserName LIKE $username');
if($result){
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
}
}
First, check your connection to the database. Is it connected successfully or not?
If it's done, then after that I have written this code, and it works well:
if (isset($_GET['q1mrks']) && isset($_GET['marks']) && isset($_GET['qt1'])) {
$Q1mrks = $_GET['q1mrks'];
$marks = $_GET['marks'];
$qt1 = $_GET['qt1'];
$qtype_qry = mysql_query("
SELECT *
FROM s_questiontypes
WHERE quetype_id = '$qt1'
");
$row = mysql_fetch_assoc($qtype_qry);
$qcode = $row['quetype_code'];
$sq_qry = "
SELECT *
FROM s_question
WHERE quetype_code = '$qcode'
ORDER BY RAND() LIMIT $Q1mrks
";
$sq_qry = mysql_query("
SELECT *
FROM s_question
WHERE quetype_code = '$qcode'
LIMIT $Q1mrks
");
while ($qrow = mysql_fetch_array($sq_qry)) {
$qm = $qrow['marks'] . "<br />";
$total += $qm . "<br />";
}
echo $total . "/" . $marks;
}
Make Sure You're Not Closing Database By using db_close() Before To
Running Your Query:
If you're using multiple queries in a script even you're including other pages which contains queries or database connection, then it might be possible that at any place you use db_close() that would close your database connection so make sure you're not doing this mistake in your scripts.
If you don't have any MySQL Error appearing while checking, make sure that you properly created your database table. This happened to me. Look for any unwanted commas or quotes.
Check your connection first.
Then if you want to fetch the exact value from the database then you should write:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName =`$usernam`");
Or you want to fetch the LIKE type of value then you should write:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
You can also check wether $result is failing like so, before executing the fetch array
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
if(!$result)
{
echo "error executing query: "+mysql_error();
}else{
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
}
Usually an error occurs when your database conectivity fails, so be sure to connect your database or to include the database file.
include_once(db_connetc.php');
OR
// Create a connection
$connection = mysql_connect("localhost", "root", "") or die(mysql_error());
//Select database
mysql_select_db("db_name", $connection) or die(mysql_error());
$employee_query = "SELECT * FROM employee WHERE `id` ='".$_POST['id']."'";
$employee_data = mysql_query($employee_query);
if (mysql_num_rows($employee_data) > 0) {
while ($row = mysql_fetch_array($employee_data)){
echo $row['emp_name'];
} // end of while loop
} // end of if
Best practice is to run the query in sqlyog and then copy it into your page code.
Always store your query in a variable and then echo that variable. Then pass to mysql_query($query_variable);.
Traditionally PHP has been tolerant to bad practice and failures in code,
which makes debugging quite hard.
The problem in this specific case is that both mysqli and PDO
by default don't tell you, when a query failed and just return FALSE.
(I will not talk about the depricated mysql extention.
The support for prepared statements is reason anough to switch either to PDO or mysqli.)
But you can change the default behavior of PHP to always throw exceptions when a query fails.
For PDO: Use $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
error_reporting(E_ALL);
$pdo = new PDO("mysql:host=localhost;dbname=test", "test","");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->query('select emal from users');
$data = $result->fetchAll();
This will show you the following:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\pdo.php on line 8
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\pdo.php on line 8
As you see, it tells you exactly, what is wrong with the query, and where to fix it in your code.
Without $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
you will get
Fatal error: Call to a member function fetchAll() on boolean in E:\htdocs\test\mysql_errors\pdo.php on line 9
For mysqli: Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'test', '', 'test');
$result = $mysqli->query('select emal from users');
$data = $result->fetch_all();
You will get
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
mysqli_sql_exception: Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
Without mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); you only get
Fatal error: Call to a member function fetch_all() on boolean in E:\htdocs\test\mysql_errors\mysqli.php on line 10
Of course, you could manually check the MySQL errors.
But I would go crazy if I had to do that every time I made a typo -
or worse - every time I want to query the database.
Try this code it work fine
assign the post variable to the variable
$username = $_POST['uname'];
$password = $_POST['pass'];
$result = mysql_query('SELECT * FROM userData WHERE UserName LIKE $username');
if(!empty($result)){
while($row = mysql_fetch_array($result)){
echo $row['FirstName'];
}
}

Categories