mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc… expects parameter 1 to be...
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
or
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
or
Call to a member function fetch_array() on boolean / non-object
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'];
}
The same applies to code like
$result = mysqli_query($mysqli, 'SELECT ...');
// mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
while( $row=mysqli_fetch_array($result) ) {
...
and
$result = $mysqli->query($mysqli, 'SELECT ...');
// Call to a member function fetch_assoc() on a non-object
while( $row=$result->fetch_assoc($result) ) {
...
and
$result = $pdo->query('SELECT ...', PDO::FETCH_ASSOC);
// Invalid argument supplied for foreach()
foreach( $result as $row ) {
...
and
$stmt = $mysqli->prepare('SELECT ...');
// Call to a member function bind_param() on a non-object
$stmt->bind_param(...);
and
$stmt = $pdo->prepare('SELECT ...');
// Call to a member function bindParam() on a non-object
$stmt->bindParam(...);
php mysql
|
show 2 more comments
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
or
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
or
Call to a member function fetch_array() on boolean / non-object
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'];
}
The same applies to code like
$result = mysqli_query($mysqli, 'SELECT ...');
// mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
while( $row=mysqli_fetch_array($result) ) {
...
and
$result = $mysqli->query($mysqli, 'SELECT ...');
// Call to a member function fetch_assoc() on a non-object
while( $row=$result->fetch_assoc($result) ) {
...
and
$result = $pdo->query('SELECT ...', PDO::FETCH_ASSOC);
// Invalid argument supplied for foreach()
foreach( $result as $row ) {
...
and
$stmt = $mysqli->prepare('SELECT ...');
// Call to a member function bind_param() on a non-object
$stmt->bind_param(...);
and
$stmt = $pdo->prepare('SELECT ...');
// Call to a member function bindParam() on a non-object
$stmt->bindParam(...);
php mysql
14
you can get more useful eroor msg using:: QUERY or die(mysql_error());
– nik
Jun 4 '10 at 10:26
120
Also the obligatory note: Your code is prone to SQL injection. You should validate and/or escape the user input. Have a look atmysql_real_escape_string
. Never trust user data.
– Felix Kling
Jun 4 '10 at 10:26
7
Actually, the OP's code will cause a syntax error on the MySQL server, but at least it is not vulnerable to SQL Injection because single quotes doesn't have variable interpolation.
– szgal
Jul 4 '14 at 14:06
3
@FelixKling I realize this is very old, and likely the most accurate possible at the time, but your comment is now dangerously wrong in one way:mysql_real_escape_string
is not the be-all and end-all of SQL injection protection; it's still vulnerable to a number of attacks. (No, you never said it's perfect, but you implied it was the only required solution) The best solution now is PDO, as far as I know.
– Nic Hartley
Mar 13 '17 at 0:30
1
Besides the first error, what you posted would have thrown another error, this forLIKE $username
since we're more than likely dealing with a string here and not an integer. Therefore it would require it to be quoted.
– Funk Forty Niner
Nov 20 '18 at 18:56
|
show 2 more comments
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
or
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
or
Call to a member function fetch_array() on boolean / non-object
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'];
}
The same applies to code like
$result = mysqli_query($mysqli, 'SELECT ...');
// mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
while( $row=mysqli_fetch_array($result) ) {
...
and
$result = $mysqli->query($mysqli, 'SELECT ...');
// Call to a member function fetch_assoc() on a non-object
while( $row=$result->fetch_assoc($result) ) {
...
and
$result = $pdo->query('SELECT ...', PDO::FETCH_ASSOC);
// Invalid argument supplied for foreach()
foreach( $result as $row ) {
...
and
$stmt = $mysqli->prepare('SELECT ...');
// Call to a member function bind_param() on a non-object
$stmt->bind_param(...);
and
$stmt = $pdo->prepare('SELECT ...');
// Call to a member function bindParam() on a non-object
$stmt->bindParam(...);
php mysql
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
or
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
or
Call to a member function fetch_array() on boolean / non-object
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'];
}
The same applies to code like
$result = mysqli_query($mysqli, 'SELECT ...');
// mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
while( $row=mysqli_fetch_array($result) ) {
...
and
$result = $mysqli->query($mysqli, 'SELECT ...');
// Call to a member function fetch_assoc() on a non-object
while( $row=$result->fetch_assoc($result) ) {
...
and
$result = $pdo->query('SELECT ...', PDO::FETCH_ASSOC);
// Invalid argument supplied for foreach()
foreach( $result as $row ) {
...
and
$stmt = $mysqli->prepare('SELECT ...');
// Call to a member function bind_param() on a non-object
$stmt->bind_param(...);
and
$stmt = $pdo->prepare('SELECT ...');
// Call to a member function bindParam() on a non-object
$stmt->bindParam(...);
php mysql
php mysql
edited Jan 17 at 19:58
AbraCadaver
57.3k73966
57.3k73966
asked Jun 4 '10 at 10:18
iamjonesyiamjonesy
10.3k37121194
10.3k37121194
14
you can get more useful eroor msg using:: QUERY or die(mysql_error());
– nik
Jun 4 '10 at 10:26
120
Also the obligatory note: Your code is prone to SQL injection. You should validate and/or escape the user input. Have a look atmysql_real_escape_string
. Never trust user data.
– Felix Kling
Jun 4 '10 at 10:26
7
Actually, the OP's code will cause a syntax error on the MySQL server, but at least it is not vulnerable to SQL Injection because single quotes doesn't have variable interpolation.
– szgal
Jul 4 '14 at 14:06
3
@FelixKling I realize this is very old, and likely the most accurate possible at the time, but your comment is now dangerously wrong in one way:mysql_real_escape_string
is not the be-all and end-all of SQL injection protection; it's still vulnerable to a number of attacks. (No, you never said it's perfect, but you implied it was the only required solution) The best solution now is PDO, as far as I know.
– Nic Hartley
Mar 13 '17 at 0:30
1
Besides the first error, what you posted would have thrown another error, this forLIKE $username
since we're more than likely dealing with a string here and not an integer. Therefore it would require it to be quoted.
– Funk Forty Niner
Nov 20 '18 at 18:56
|
show 2 more comments
14
you can get more useful eroor msg using:: QUERY or die(mysql_error());
– nik
Jun 4 '10 at 10:26
120
Also the obligatory note: Your code is prone to SQL injection. You should validate and/or escape the user input. Have a look atmysql_real_escape_string
. Never trust user data.
– Felix Kling
Jun 4 '10 at 10:26
7
Actually, the OP's code will cause a syntax error on the MySQL server, but at least it is not vulnerable to SQL Injection because single quotes doesn't have variable interpolation.
– szgal
Jul 4 '14 at 14:06
3
@FelixKling I realize this is very old, and likely the most accurate possible at the time, but your comment is now dangerously wrong in one way:mysql_real_escape_string
is not the be-all and end-all of SQL injection protection; it's still vulnerable to a number of attacks. (No, you never said it's perfect, but you implied it was the only required solution) The best solution now is PDO, as far as I know.
– Nic Hartley
Mar 13 '17 at 0:30
1
Besides the first error, what you posted would have thrown another error, this forLIKE $username
since we're more than likely dealing with a string here and not an integer. Therefore it would require it to be quoted.
– Funk Forty Niner
Nov 20 '18 at 18:56
14
14
you can get more useful eroor msg using:: QUERY or die(mysql_error());
– nik
Jun 4 '10 at 10:26
you can get more useful eroor msg using:: QUERY or die(mysql_error());
– nik
Jun 4 '10 at 10:26
120
120
Also the obligatory note: Your code is prone to SQL injection. You should validate and/or escape the user input. Have a look at
mysql_real_escape_string
. Never trust user data.– Felix Kling
Jun 4 '10 at 10:26
Also the obligatory note: Your code is prone to SQL injection. You should validate and/or escape the user input. Have a look at
mysql_real_escape_string
. Never trust user data.– Felix Kling
Jun 4 '10 at 10:26
7
7
Actually, the OP's code will cause a syntax error on the MySQL server, but at least it is not vulnerable to SQL Injection because single quotes doesn't have variable interpolation.
– szgal
Jul 4 '14 at 14:06
Actually, the OP's code will cause a syntax error on the MySQL server, but at least it is not vulnerable to SQL Injection because single quotes doesn't have variable interpolation.
– szgal
Jul 4 '14 at 14:06
3
3
@FelixKling I realize this is very old, and likely the most accurate possible at the time, but your comment is now dangerously wrong in one way:
mysql_real_escape_string
is not the be-all and end-all of SQL injection protection; it's still vulnerable to a number of attacks. (No, you never said it's perfect, but you implied it was the only required solution) The best solution now is PDO, as far as I know.– Nic Hartley
Mar 13 '17 at 0:30
@FelixKling I realize this is very old, and likely the most accurate possible at the time, but your comment is now dangerously wrong in one way:
mysql_real_escape_string
is not the be-all and end-all of SQL injection protection; it's still vulnerable to a number of attacks. (No, you never said it's perfect, but you implied it was the only required solution) The best solution now is PDO, as far as I know.– Nic Hartley
Mar 13 '17 at 0:30
1
1
Besides the first error, what you posted would have thrown another error, this for
LIKE $username
since we're more than likely dealing with a string here and not an integer. Therefore it would require it to be quoted.– Funk Forty Niner
Nov 20 '18 at 18:56
Besides the first error, what you posted would have thrown another error, this for
LIKE $username
since we're more than likely dealing with a string here and not an integer. Therefore it would require it to be quoted.– Funk Forty Niner
Nov 20 '18 at 18:56
|
show 2 more comments
31 Answers
31
active
oldest
votes
1 2
next
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
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) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
mysqli extension
procedural style:
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");
// mysqli_query returns false if something went wrong with the query
if($result === FALSE) {
yourErrorHandler(mysqli_error($mysqli));
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
oo-style:
$username = $mysqli->escape_string($_POST['username']);
$result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
using a prepared statement:
$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?');
if ( !$stmt ) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else if ( !$stmt->bind_param('s', $_POST['username']) ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else if ( !$stmt->execute() ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else {
$result = $stmt->get_result();
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
These examples only illustrate what should be done (error handling), not how to do it. Production code shouldn't use or die
when outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.
8
Right, but using a die() if the query fails is a little to much.
– 2ndkauboy
Jun 4 '10 at 10:28
28
I was going to design an entire error handling mechanism for the OP, but decided that might be beyond the scope of my answer.
– scompt.com
Jun 4 '10 at 10:29
@scompt.com Yes it's also covered in several other answers. I guess I was just making the point that since this is the accepted answer on a high visibility question, in addition to the (excellent) advice about how to properly catch errors in future, it should (IMHO) actually answer the specific question (ie explain why there's an error in this case).
– Sepster
Apr 23 '13 at 22:17
2
Instead ofif($result === FALSE)
you can useif(! $result)
. Correct me if I'm wrong
– anestv
Jun 17 '14 at 12:52
1
mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli
– Greg
Dec 25 '14 at 17:24
add a comment |
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_*
andmysql_*
functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick withmysqli_*
. 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.
1
Given this question today stackoverflow.com/q/43804651/1415724 and other similar ones lately; I think it may be worthwhile to update your answer to contain something like "That error can also be caused by not executing the query withmysql_query()
/mysqli_query($connection)
etc."; thoughts? Since no other answers in this Q&A mentions this.
– Funk Forty Niner
May 5 '17 at 12:17
add a comment |
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.
5
Why adding noise with string concatenation instead of just putting the variable in the query string?
– Matteo Riva
Jun 4 '10 at 16:53
1
@Matteo Riva Yeah, but I thought this is little cleaner way to separate variables from string. :)
– nik
Aug 7 '12 at 7:32
add a comment |
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.
add a comment |
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
.
1
And what if $username is: " '; DROP TABLES;" ? That is the advantage to using prepared statements and bound values, which I think the asker would like to retain.
– HoldOffHunger
Mar 20 '16 at 15:59
add a comment |
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());
add a comment |
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.
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:38
add a comment |
$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.
Do not use this code, even if you add quotes. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:36
add a comment |
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.
add a comment |
$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);
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
add a comment |
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.
I hope this helps someone.
add a comment |
$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.
Remember to usehtmlspecialchars()
when using arbitrary data in the context of HTML. Otherwise, you risk creating valid HTML when reserved characters are used in the data.
– Brad
Dec 7 '14 at 17:29
add a comment |
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'];
}
5
1) Wide open to SQL injection, 2) does not include error handling which is causing the error in OP's case.
– deceze♦
Feb 25 '13 at 13:39
+1. @deceze Yes it is wide open. But no more so that the OP's or the accepted answerer's code ;-) And it's not the lack of error handling in the OP's code causing the error... it's the error, and this answer at least attempts to resolve that (by putting single quotes around the string literal in theLIKE
expression).
– Sepster
Apr 23 '13 at 12:54
1
+1 Please add a space between LIKE and '$username', rest appears to be fine except the SQL injection. Why not use = instead of LIKE operator username must be exactly matched
– asim-ishaq
May 4 '13 at 19:08
add a comment |
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'];
}
2
This code is subject to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
add a comment |
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.
add a comment |
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.
add a comment |
<?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."'");
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:32
@Brad Why this code is wide open to sql injection?
– Anuj Garg
Jun 29 '15 at 10:11
@AnujGarg This code takes direct input and concatenates it into the query. Someone could write their own SQL in the post data forusername
and it will be executed.
– Brad
Jun 29 '15 at 14:19
So what to use to prevent the code from SQL injection?
– Anuj Garg
Jun 29 '15 at 18:10
add a comment |
Include a connection string variable before the MySQL query. For example, $connt
in this code:
$results = mysql_query($connt, "SELECT * FROM users");
add a comment |
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();
?>
add a comment |
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'];
}
}
4
@panjehra mysql_* is depricated now and will removed from php 7 . Use mysqli_* instead
– Manoj Kumar
May 25 '15 at 4:57
add a comment |
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;
}
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
add a comment |
<?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'];
}
?>
add a comment |
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;
echo $error; // 1054 Unknown column 'foo' in 'field list'
}
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.
add a comment |
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.
add a comment |
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%'");
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
add a comment |
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.
add a comment |
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'];
}
}
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:35
But if the code works, I feel you should edit the code and input the needed filters instead of castigating the code.
– user28864
Dec 8 '14 at 12:28
Simple usage of filters will not fix what is wrong with this code. The best solution is to use prepared/parameterized queries with PDO or similar. I don't see any point in fixing it, as the correct answer has already been posted here. Ideally, this answer will be deleted. However, you are welcome to fix your answer and I will happily up-vote it if it is correct.
– Brad
Dec 8 '14 at 14:28
Well, if you feel the answer isn't worth considering you can go ahead and get read of it. However, I thought the whole point of this community is to share and contribute knowledge. If you have something to share instead of showing and putting people off.
– user28864
Dec 8 '14 at 20:34
1
You are correct, the whole point of this community is to share knowledge. That's why added explanation with my downvote, and further explained why your filter suggestion was not sufficient. I'd much prefer to alert you, along with anyone else who finds your answer, that the code above is insecure. It's better for everyone to learn the correct methods rather than perpetuating bad code. And, I cannot delete your answer, nor would I. That's up to you, if you choose to do so.
– Brad
Dec 8 '14 at 20:44
add a comment |
You can try this code. I found it earlier when I was encountered a problem similar to yours.
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;
}
This code is wide open to SQL injection attacks, and does not actually solve the problem posed in the question.
– Brad
Dec 7 '14 at 17:28
add a comment |
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);
.
2
1) You don't know if I have or have not voted on any answer here, up or down. 2) As I explained in my first comment; your answer doesn't reference the problem (boolean passed to mysql_fetch_array) and you have syntax errors
– Phil
Jan 21 '14 at 5:06
2
You have incorrect quotes in both your code examples. The syntax highlighting applied to your second code block is a dead give-away that something is wrong
– Phil
Jan 21 '14 at 5:35
2
This code is subject to SQL injection and should not be used. @EngrZardari if you are using this code on your production systems, you have undoubtedly been hacked and should remedy the situation buy using prepared/parameterized queries with PDO or similar. There are bots that have automated testing for such vulnerabilities.
– Brad
Dec 7 '14 at 17:31
1
@EngrZardari About your "there is no any error, i have pasted here code which i currently using." comment above. There was a missing quote in the query which I corrected. That would have thrown a (PHP) parse error.
– Funk Forty Niner
Nov 20 '18 at 18:51
add a comment |
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'];
}
}
1
This code is subject to SQL injection attacks and should not be used.
– Brad
Dec 7 '14 at 17:29
add a comment |
1 2
next
31 Answers
31
active
oldest
votes
31 Answers
31
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
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
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) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
mysqli extension
procedural style:
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");
// mysqli_query returns false if something went wrong with the query
if($result === FALSE) {
yourErrorHandler(mysqli_error($mysqli));
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
oo-style:
$username = $mysqli->escape_string($_POST['username']);
$result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
using a prepared statement:
$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?');
if ( !$stmt ) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else if ( !$stmt->bind_param('s', $_POST['username']) ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else if ( !$stmt->execute() ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else {
$result = $stmt->get_result();
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
These examples only illustrate what should be done (error handling), not how to do it. Production code shouldn't use or die
when outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.
8
Right, but using a die() if the query fails is a little to much.
– 2ndkauboy
Jun 4 '10 at 10:28
28
I was going to design an entire error handling mechanism for the OP, but decided that might be beyond the scope of my answer.
– scompt.com
Jun 4 '10 at 10:29
@scompt.com Yes it's also covered in several other answers. I guess I was just making the point that since this is the accepted answer on a high visibility question, in addition to the (excellent) advice about how to properly catch errors in future, it should (IMHO) actually answer the specific question (ie explain why there's an error in this case).
– Sepster
Apr 23 '13 at 22:17
2
Instead ofif($result === FALSE)
you can useif(! $result)
. Correct me if I'm wrong
– anestv
Jun 17 '14 at 12:52
1
mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli
– Greg
Dec 25 '14 at 17:24
add a comment |
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
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) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
mysqli extension
procedural style:
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");
// mysqli_query returns false if something went wrong with the query
if($result === FALSE) {
yourErrorHandler(mysqli_error($mysqli));
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
oo-style:
$username = $mysqli->escape_string($_POST['username']);
$result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
using a prepared statement:
$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?');
if ( !$stmt ) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else if ( !$stmt->bind_param('s', $_POST['username']) ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else if ( !$stmt->execute() ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else {
$result = $stmt->get_result();
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
These examples only illustrate what should be done (error handling), not how to do it. Production code shouldn't use or die
when outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.
8
Right, but using a die() if the query fails is a little to much.
– 2ndkauboy
Jun 4 '10 at 10:28
28
I was going to design an entire error handling mechanism for the OP, but decided that might be beyond the scope of my answer.
– scompt.com
Jun 4 '10 at 10:29
@scompt.com Yes it's also covered in several other answers. I guess I was just making the point that since this is the accepted answer on a high visibility question, in addition to the (excellent) advice about how to properly catch errors in future, it should (IMHO) actually answer the specific question (ie explain why there's an error in this case).
– Sepster
Apr 23 '13 at 22:17
2
Instead ofif($result === FALSE)
you can useif(! $result)
. Correct me if I'm wrong
– anestv
Jun 17 '14 at 12:52
1
mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli
– Greg
Dec 25 '14 at 17:24
add a comment |
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
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) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
mysqli extension
procedural style:
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");
// mysqli_query returns false if something went wrong with the query
if($result === FALSE) {
yourErrorHandler(mysqli_error($mysqli));
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
oo-style:
$username = $mysqli->escape_string($_POST['username']);
$result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
using a prepared statement:
$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?');
if ( !$stmt ) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else if ( !$stmt->bind_param('s', $_POST['username']) ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else if ( !$stmt->execute() ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else {
$result = $stmt->get_result();
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
These examples only illustrate what should be done (error handling), not how to do it. Production code shouldn't use or die
when outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.
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
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) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
mysqli extension
procedural style:
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");
// mysqli_query returns false if something went wrong with the query
if($result === FALSE) {
yourErrorHandler(mysqli_error($mysqli));
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
oo-style:
$username = $mysqli->escape_string($_POST['username']);
$result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
using a prepared statement:
$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?');
if ( !$stmt ) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else if ( !$stmt->bind_param('s', $_POST['username']) ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else if ( !$stmt->execute() ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else {
$result = $stmt->get_result();
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
These examples only illustrate what should be done (error handling), not how to do it. Production code shouldn't use or die
when outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.
edited May 23 '17 at 12:02
Community♦
11
11
answered Jun 4 '10 at 10:19
scompt.comscompt.com
22.2k978120
22.2k978120
8
Right, but using a die() if the query fails is a little to much.
– 2ndkauboy
Jun 4 '10 at 10:28
28
I was going to design an entire error handling mechanism for the OP, but decided that might be beyond the scope of my answer.
– scompt.com
Jun 4 '10 at 10:29
@scompt.com Yes it's also covered in several other answers. I guess I was just making the point that since this is the accepted answer on a high visibility question, in addition to the (excellent) advice about how to properly catch errors in future, it should (IMHO) actually answer the specific question (ie explain why there's an error in this case).
– Sepster
Apr 23 '13 at 22:17
2
Instead ofif($result === FALSE)
you can useif(! $result)
. Correct me if I'm wrong
– anestv
Jun 17 '14 at 12:52
1
mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli
– Greg
Dec 25 '14 at 17:24
add a comment |
8
Right, but using a die() if the query fails is a little to much.
– 2ndkauboy
Jun 4 '10 at 10:28
28
I was going to design an entire error handling mechanism for the OP, but decided that might be beyond the scope of my answer.
– scompt.com
Jun 4 '10 at 10:29
@scompt.com Yes it's also covered in several other answers. I guess I was just making the point that since this is the accepted answer on a high visibility question, in addition to the (excellent) advice about how to properly catch errors in future, it should (IMHO) actually answer the specific question (ie explain why there's an error in this case).
– Sepster
Apr 23 '13 at 22:17
2
Instead ofif($result === FALSE)
you can useif(! $result)
. Correct me if I'm wrong
– anestv
Jun 17 '14 at 12:52
1
mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli
– Greg
Dec 25 '14 at 17:24
8
8
Right, but using a die() if the query fails is a little to much.
– 2ndkauboy
Jun 4 '10 at 10:28
Right, but using a die() if the query fails is a little to much.
– 2ndkauboy
Jun 4 '10 at 10:28
28
28
I was going to design an entire error handling mechanism for the OP, but decided that might be beyond the scope of my answer.
– scompt.com
Jun 4 '10 at 10:29
I was going to design an entire error handling mechanism for the OP, but decided that might be beyond the scope of my answer.
– scompt.com
Jun 4 '10 at 10:29
@scompt.com Yes it's also covered in several other answers. I guess I was just making the point that since this is the accepted answer on a high visibility question, in addition to the (excellent) advice about how to properly catch errors in future, it should (IMHO) actually answer the specific question (ie explain why there's an error in this case).
– Sepster
Apr 23 '13 at 22:17
@scompt.com Yes it's also covered in several other answers. I guess I was just making the point that since this is the accepted answer on a high visibility question, in addition to the (excellent) advice about how to properly catch errors in future, it should (IMHO) actually answer the specific question (ie explain why there's an error in this case).
– Sepster
Apr 23 '13 at 22:17
2
2
Instead of
if($result === FALSE)
you can use if(! $result)
. Correct me if I'm wrong– anestv
Jun 17 '14 at 12:52
Instead of
if($result === FALSE)
you can use if(! $result)
. Correct me if I'm wrong– anestv
Jun 17 '14 at 12:52
1
1
mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli
– Greg
Dec 25 '14 at 17:24
mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli
– Greg
Dec 25 '14 at 17:24
add a comment |
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_*
andmysql_*
functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick withmysqli_*
. 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.
1
Given this question today stackoverflow.com/q/43804651/1415724 and other similar ones lately; I think it may be worthwhile to update your answer to contain something like "That error can also be caused by not executing the query withmysql_query()
/mysqli_query($connection)
etc."; thoughts? Since no other answers in this Q&A mentions this.
– Funk Forty Niner
May 5 '17 at 12:17
add a comment |
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_*
andmysql_*
functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick withmysqli_*
. 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.
1
Given this question today stackoverflow.com/q/43804651/1415724 and other similar ones lately; I think it may be worthwhile to update your answer to contain something like "That error can also be caused by not executing the query withmysql_query()
/mysqli_query($connection)
etc."; thoughts? Since no other answers in this Q&A mentions this.
– Funk Forty Niner
May 5 '17 at 12:17
add a comment |
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_*
andmysql_*
functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick withmysqli_*
. 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.
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_*
andmysql_*
functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick withmysqli_*
. 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.
edited Nov 10 '14 at 15:21
answered Jul 26 '12 at 17:00
John CondeJohn Conde
185k80372423
185k80372423
1
Given this question today stackoverflow.com/q/43804651/1415724 and other similar ones lately; I think it may be worthwhile to update your answer to contain something like "That error can also be caused by not executing the query withmysql_query()
/mysqli_query($connection)
etc."; thoughts? Since no other answers in this Q&A mentions this.
– Funk Forty Niner
May 5 '17 at 12:17
add a comment |
1
Given this question today stackoverflow.com/q/43804651/1415724 and other similar ones lately; I think it may be worthwhile to update your answer to contain something like "That error can also be caused by not executing the query withmysql_query()
/mysqli_query($connection)
etc."; thoughts? Since no other answers in this Q&A mentions this.
– Funk Forty Niner
May 5 '17 at 12:17
1
1
Given this question today stackoverflow.com/q/43804651/1415724 and other similar ones lately; I think it may be worthwhile to update your answer to contain something like "That error can also be caused by not executing the query with
mysql_query()
/ mysqli_query($connection)
etc."; thoughts? Since no other answers in this Q&A mentions this.– Funk Forty Niner
May 5 '17 at 12:17
Given this question today stackoverflow.com/q/43804651/1415724 and other similar ones lately; I think it may be worthwhile to update your answer to contain something like "That error can also be caused by not executing the query with
mysql_query()
/ mysqli_query($connection)
etc."; thoughts? Since no other answers in this Q&A mentions this.– Funk Forty Niner
May 5 '17 at 12:17
add a comment |
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.
5
Why adding noise with string concatenation instead of just putting the variable in the query string?
– Matteo Riva
Jun 4 '10 at 16:53
1
@Matteo Riva Yeah, but I thought this is little cleaner way to separate variables from string. :)
– nik
Aug 7 '12 at 7:32
add a comment |
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.
5
Why adding noise with string concatenation instead of just putting the variable in the query string?
– Matteo Riva
Jun 4 '10 at 16:53
1
@Matteo Riva Yeah, but I thought this is little cleaner way to separate variables from string. :)
– nik
Aug 7 '12 at 7:32
add a comment |
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.
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.
edited Nov 19 '15 at 8:08
answered Jun 4 '10 at 10:24
niknik
3,35121629
3,35121629
5
Why adding noise with string concatenation instead of just putting the variable in the query string?
– Matteo Riva
Jun 4 '10 at 16:53
1
@Matteo Riva Yeah, but I thought this is little cleaner way to separate variables from string. :)
– nik
Aug 7 '12 at 7:32
add a comment |
5
Why adding noise with string concatenation instead of just putting the variable in the query string?
– Matteo Riva
Jun 4 '10 at 16:53
1
@Matteo Riva Yeah, but I thought this is little cleaner way to separate variables from string. :)
– nik
Aug 7 '12 at 7:32
5
5
Why adding noise with string concatenation instead of just putting the variable in the query string?
– Matteo Riva
Jun 4 '10 at 16:53
Why adding noise with string concatenation instead of just putting the variable in the query string?
– Matteo Riva
Jun 4 '10 at 16:53
1
1
@Matteo Riva Yeah, but I thought this is little cleaner way to separate variables from string. :)
– nik
Aug 7 '12 at 7:32
@Matteo Riva Yeah, but I thought this is little cleaner way to separate variables from string. :)
– nik
Aug 7 '12 at 7:32
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited May 23 '17 at 12:34
Community♦
11
11
answered Jun 4 '10 at 10:31
2ndkauboy2ndkauboy
8,35822059
8,35822059
add a comment |
add a comment |
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
.
1
And what if $username is: " '; DROP TABLES;" ? That is the advantage to using prepared statements and bound values, which I think the asker would like to retain.
– HoldOffHunger
Mar 20 '16 at 15:59
add a comment |
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
.
1
And what if $username is: " '; DROP TABLES;" ? That is the advantage to using prepared statements and bound values, which I think the asker would like to retain.
– HoldOffHunger
Mar 20 '16 at 15:59
add a comment |
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
.
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
.
answered Jun 4 '10 at 10:22
Matteo RivaMatteo Riva
19.2k106199
19.2k106199
1
And what if $username is: " '; DROP TABLES;" ? That is the advantage to using prepared statements and bound values, which I think the asker would like to retain.
– HoldOffHunger
Mar 20 '16 at 15:59
add a comment |
1
And what if $username is: " '; DROP TABLES;" ? That is the advantage to using prepared statements and bound values, which I think the asker would like to retain.
– HoldOffHunger
Mar 20 '16 at 15:59
1
1
And what if $username is: " '; DROP TABLES;" ? That is the advantage to using prepared statements and bound values, which I think the asker would like to retain.
– HoldOffHunger
Mar 20 '16 at 15:59
And what if $username is: " '; DROP TABLES;" ? That is the advantage to using prepared statements and bound values, which I think the asker would like to retain.
– HoldOffHunger
Mar 20 '16 at 15:59
add a comment |
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());
add a comment |
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());
add a comment |
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());
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());
edited Jul 11 '12 at 10:19
RAS
6,566145376
6,566145376
answered Apr 25 '12 at 5:14
yasinyasin
44743
44743
add a comment |
add a comment |
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.
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:38
add a comment |
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.
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:38
add a comment |
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.
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.
edited Jan 5 '12 at 11:06
Ghostman
4,33862650
4,33862650
answered Jun 4 '10 at 11:28
ChaitannyaChaitannya
7631616
7631616
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:38
add a comment |
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:38
1
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:38
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:38
add a comment |
$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.
Do not use this code, even if you add quotes. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:36
add a comment |
$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.
Do not use this code, even if you add quotes. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:36
add a comment |
$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.
$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.
answered Jan 8 '12 at 3:48
derokorianderokorian
37532
37532
Do not use this code, even if you add quotes. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:36
add a comment |
Do not use this code, even if you add quotes. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:36
Do not use this code, even if you add quotes. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:36
Do not use this code, even if you add quotes. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:36
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Apr 23 '13 at 13:49
answered Apr 23 '13 at 9:34
Enis P. AginićEnis P. Aginić
61969
61969
add a comment |
add a comment |
$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);
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
add a comment |
$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);
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
add a comment |
$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);
$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);
edited Apr 4 '14 at 16:57
Jack Tuck
1,30611223
1,30611223
answered May 10 '13 at 13:46
Dip PokhrelDip Pokhrel
48349
48349
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
add a comment |
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
add a comment |
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.
I hope this helps someone.
add a comment |
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.
I hope this helps someone.
add a comment |
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.
I hope this helps someone.
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.
I hope this helps someone.
edited Apr 13 '14 at 22:31
Peter Mortensen
13.6k1985111
13.6k1985111
answered Sep 6 '12 at 15:32
kolexinfoskolexinfos
63011735
63011735
add a comment |
add a comment |
$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.
Remember to usehtmlspecialchars()
when using arbitrary data in the context of HTML. Otherwise, you risk creating valid HTML when reserved characters are used in the data.
– Brad
Dec 7 '14 at 17:29
add a comment |
$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.
Remember to usehtmlspecialchars()
when using arbitrary data in the context of HTML. Otherwise, you risk creating valid HTML when reserved characters are used in the data.
– Brad
Dec 7 '14 at 17:29
add a comment |
$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.
$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.
edited Oct 29 '14 at 18:46
John Conde
185k80372423
185k80372423
answered Jul 21 '13 at 16:20
Gears.of.CodesGears.of.Codes
25932
25932
Remember to usehtmlspecialchars()
when using arbitrary data in the context of HTML. Otherwise, you risk creating valid HTML when reserved characters are used in the data.
– Brad
Dec 7 '14 at 17:29
add a comment |
Remember to usehtmlspecialchars()
when using arbitrary data in the context of HTML. Otherwise, you risk creating valid HTML when reserved characters are used in the data.
– Brad
Dec 7 '14 at 17:29
Remember to use
htmlspecialchars()
when using arbitrary data in the context of HTML. Otherwise, you risk creating valid HTML when reserved characters are used in the data.– Brad
Dec 7 '14 at 17:29
Remember to use
htmlspecialchars()
when using arbitrary data in the context of HTML. Otherwise, you risk creating valid HTML when reserved characters are used in the data.– Brad
Dec 7 '14 at 17:29
add a comment |
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'];
}
5
1) Wide open to SQL injection, 2) does not include error handling which is causing the error in OP's case.
– deceze♦
Feb 25 '13 at 13:39
+1. @deceze Yes it is wide open. But no more so that the OP's or the accepted answerer's code ;-) And it's not the lack of error handling in the OP's code causing the error... it's the error, and this answer at least attempts to resolve that (by putting single quotes around the string literal in theLIKE
expression).
– Sepster
Apr 23 '13 at 12:54
1
+1 Please add a space between LIKE and '$username', rest appears to be fine except the SQL injection. Why not use = instead of LIKE operator username must be exactly matched
– asim-ishaq
May 4 '13 at 19:08
add a comment |
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'];
}
5
1) Wide open to SQL injection, 2) does not include error handling which is causing the error in OP's case.
– deceze♦
Feb 25 '13 at 13:39
+1. @deceze Yes it is wide open. But no more so that the OP's or the accepted answerer's code ;-) And it's not the lack of error handling in the OP's code causing the error... it's the error, and this answer at least attempts to resolve that (by putting single quotes around the string literal in theLIKE
expression).
– Sepster
Apr 23 '13 at 12:54
1
+1 Please add a space between LIKE and '$username', rest appears to be fine except the SQL injection. Why not use = instead of LIKE operator username must be exactly matched
– asim-ishaq
May 4 '13 at 19:08
add a comment |
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'];
}
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'];
}
edited May 30 '15 at 19:43
answered Feb 25 '13 at 13:33
Amjad OmariAmjad Omari
72711231
72711231
5
1) Wide open to SQL injection, 2) does not include error handling which is causing the error in OP's case.
– deceze♦
Feb 25 '13 at 13:39
+1. @deceze Yes it is wide open. But no more so that the OP's or the accepted answerer's code ;-) And it's not the lack of error handling in the OP's code causing the error... it's the error, and this answer at least attempts to resolve that (by putting single quotes around the string literal in theLIKE
expression).
– Sepster
Apr 23 '13 at 12:54
1
+1 Please add a space between LIKE and '$username', rest appears to be fine except the SQL injection. Why not use = instead of LIKE operator username must be exactly matched
– asim-ishaq
May 4 '13 at 19:08
add a comment |
5
1) Wide open to SQL injection, 2) does not include error handling which is causing the error in OP's case.
– deceze♦
Feb 25 '13 at 13:39
+1. @deceze Yes it is wide open. But no more so that the OP's or the accepted answerer's code ;-) And it's not the lack of error handling in the OP's code causing the error... it's the error, and this answer at least attempts to resolve that (by putting single quotes around the string literal in theLIKE
expression).
– Sepster
Apr 23 '13 at 12:54
1
+1 Please add a space between LIKE and '$username', rest appears to be fine except the SQL injection. Why not use = instead of LIKE operator username must be exactly matched
– asim-ishaq
May 4 '13 at 19:08
5
5
1) Wide open to SQL injection, 2) does not include error handling which is causing the error in OP's case.
– deceze♦
Feb 25 '13 at 13:39
1) Wide open to SQL injection, 2) does not include error handling which is causing the error in OP's case.
– deceze♦
Feb 25 '13 at 13:39
+1. @deceze Yes it is wide open. But no more so that the OP's or the accepted answerer's code ;-) And it's not the lack of error handling in the OP's code causing the error... it's the error, and this answer at least attempts to resolve that (by putting single quotes around the string literal in the
LIKE
expression).– Sepster
Apr 23 '13 at 12:54
+1. @deceze Yes it is wide open. But no more so that the OP's or the accepted answerer's code ;-) And it's not the lack of error handling in the OP's code causing the error... it's the error, and this answer at least attempts to resolve that (by putting single quotes around the string literal in the
LIKE
expression).– Sepster
Apr 23 '13 at 12:54
1
1
+1 Please add a space between LIKE and '$username', rest appears to be fine except the SQL injection. Why not use = instead of LIKE operator username must be exactly matched
– asim-ishaq
May 4 '13 at 19:08
+1 Please add a space between LIKE and '$username', rest appears to be fine except the SQL injection. Why not use = instead of LIKE operator username must be exactly matched
– asim-ishaq
May 4 '13 at 19:08
add a comment |
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'];
}
2
This code is subject to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
add a comment |
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'];
}
2
This code is subject to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
add a comment |
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'];
}
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'];
}
edited Apr 13 '14 at 22:36
Peter Mortensen
13.6k1985111
13.6k1985111
answered May 30 '13 at 7:40
raviravi
371313
371313
2
This code is subject to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
add a comment |
2
This code is subject to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
2
2
This code is subject to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
This code is subject to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Apr 13 '14 at 22:35
Peter Mortensen
13.6k1985111
13.6k1985111
answered May 4 '13 at 18:57
asim-ishaqasim-ishaq
1,35122143
1,35122143
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Dec 15 '13 at 20:47
peterh
6,246154770
6,246154770
answered Oct 1 '13 at 13:48
user2835116user2835116
15112
15112
add a comment |
add a comment |
<?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."'");
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:32
@Brad Why this code is wide open to sql injection?
– Anuj Garg
Jun 29 '15 at 10:11
@AnujGarg This code takes direct input and concatenates it into the query. Someone could write their own SQL in the post data forusername
and it will be executed.
– Brad
Jun 29 '15 at 14:19
So what to use to prevent the code from SQL injection?
– Anuj Garg
Jun 29 '15 at 18:10
add a comment |
<?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."'");
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:32
@Brad Why this code is wide open to sql injection?
– Anuj Garg
Jun 29 '15 at 10:11
@AnujGarg This code takes direct input and concatenates it into the query. Someone could write their own SQL in the post data forusername
and it will be executed.
– Brad
Jun 29 '15 at 14:19
So what to use to prevent the code from SQL injection?
– Anuj Garg
Jun 29 '15 at 18:10
add a comment |
<?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."'");
<?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."'");
edited Apr 13 '14 at 22:40
Peter Mortensen
13.6k1985111
13.6k1985111
answered Sep 19 '13 at 8:39
Janak PrajapatiJanak Prajapati
814719
814719
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:32
@Brad Why this code is wide open to sql injection?
– Anuj Garg
Jun 29 '15 at 10:11
@AnujGarg This code takes direct input and concatenates it into the query. Someone could write their own SQL in the post data forusername
and it will be executed.
– Brad
Jun 29 '15 at 14:19
So what to use to prevent the code from SQL injection?
– Anuj Garg
Jun 29 '15 at 18:10
add a comment |
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:32
@Brad Why this code is wide open to sql injection?
– Anuj Garg
Jun 29 '15 at 10:11
@AnujGarg This code takes direct input and concatenates it into the query. Someone could write their own SQL in the post data forusername
and it will be executed.
– Brad
Jun 29 '15 at 14:19
So what to use to prevent the code from SQL injection?
– Anuj Garg
Jun 29 '15 at 18:10
1
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:32
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:32
@Brad Why this code is wide open to sql injection?
– Anuj Garg
Jun 29 '15 at 10:11
@Brad Why this code is wide open to sql injection?
– Anuj Garg
Jun 29 '15 at 10:11
@AnujGarg This code takes direct input and concatenates it into the query. Someone could write their own SQL in the post data for
username
and it will be executed.– Brad
Jun 29 '15 at 14:19
@AnujGarg This code takes direct input and concatenates it into the query. Someone could write their own SQL in the post data for
username
and it will be executed.– Brad
Jun 29 '15 at 14:19
So what to use to prevent the code from SQL injection?
– Anuj Garg
Jun 29 '15 at 18:10
So what to use to prevent the code from SQL injection?
– Anuj Garg
Jun 29 '15 at 18:10
add a comment |
Include a connection string variable before the MySQL query. For example, $connt
in this code:
$results = mysql_query($connt, "SELECT * FROM users");
add a comment |
Include a connection string variable before the MySQL query. For example, $connt
in this code:
$results = mysql_query($connt, "SELECT * FROM users");
add a comment |
Include a connection string variable before the MySQL query. For example, $connt
in this code:
$results = mysql_query($connt, "SELECT * FROM users");
Include a connection string variable before the MySQL query. For example, $connt
in this code:
$results = mysql_query($connt, "SELECT * FROM users");
edited Dec 7 '14 at 17:32
Brad
115k27230393
115k27230393
answered Oct 30 '13 at 5:11
DurairajDurairaj
14113
14113
add a comment |
add a comment |
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();
?>
add a comment |
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();
?>
add a comment |
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();
?>
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();
?>
answered Apr 16 '15 at 6:53
Manoj KumarManoj Kumar
3,26041642
3,26041642
add a comment |
add a comment |
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'];
}
}
4
@panjehra mysql_* is depricated now and will removed from php 7 . Use mysqli_* instead
– Manoj Kumar
May 25 '15 at 4:57
add a comment |
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'];
}
}
4
@panjehra mysql_* is depricated now and will removed from php 7 . Use mysqli_* instead
– Manoj Kumar
May 25 '15 at 4:57
add a comment |
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'];
}
}
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'];
}
}
edited Jan 4 '16 at 5:28
answered Apr 28 '15 at 6:05
Suresh RattenSuresh Ratten
1,16711836
1,16711836
4
@panjehra mysql_* is depricated now and will removed from php 7 . Use mysqli_* instead
– Manoj Kumar
May 25 '15 at 4:57
add a comment |
4
@panjehra mysql_* is depricated now and will removed from php 7 . Use mysqli_* instead
– Manoj Kumar
May 25 '15 at 4:57
4
4
@panjehra mysql_* is depricated now and will removed from php 7 . Use mysqli_* instead
– Manoj Kumar
May 25 '15 at 4:57
@panjehra mysql_* is depricated now and will removed from php 7 . Use mysqli_* instead
– Manoj Kumar
May 25 '15 at 4:57
add a comment |
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;
}
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
add a comment |
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;
}
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
add a comment |
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;
}
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;
}
edited Apr 13 '14 at 22:33
Peter Mortensen
13.6k1985111
13.6k1985111
answered Apr 29 '13 at 10:24
user2155518
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
add a comment |
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:34
add a comment |
<?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'];
}
?>
add a comment |
<?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'];
}
?>
add a comment |
<?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'];
}
?>
<?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'];
}
?>
answered Apr 6 '15 at 18:01
Dennis KiptugenDennis Kiptugen
18317
18317
add a comment |
add a comment |
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;
echo $error; // 1054 Unknown column 'foo' in 'field list'
}
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.
add a comment |
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;
echo $error; // 1054 Unknown column 'foo' in 'field list'
}
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.
add a comment |
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;
echo $error; // 1054 Unknown column 'foo' in 'field list'
}
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.
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;
echo $error; // 1054 Unknown column 'foo' in 'field list'
}
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.
answered Aug 5 '15 at 20:53
Jay BlanchardJay Blanchard
35.7k125596
35.7k125596
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Oct 13 '14 at 15:07
A.Aleem11A.Aleem11
98399
98399
add a comment |
add a comment |
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%'");
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
add a comment |
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%'");
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
add a comment |
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%'");
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%'");
edited Apr 13 '14 at 22:37
Peter Mortensen
13.6k1985111
13.6k1985111
answered Jul 6 '13 at 13:02
OmdevOmdev
8912
8912
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
add a comment |
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
1
1
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
This code is wide open to SQL injection and should not be used.
– Brad
Dec 7 '14 at 17:33
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Nov 8 '14 at 13:36
user1012181user1012181
3,43064374
3,43064374
add a comment |
add a comment |
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'];
}
}
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:35
But if the code works, I feel you should edit the code and input the needed filters instead of castigating the code.
– user28864
Dec 8 '14 at 12:28
Simple usage of filters will not fix what is wrong with this code. The best solution is to use prepared/parameterized queries with PDO or similar. I don't see any point in fixing it, as the correct answer has already been posted here. Ideally, this answer will be deleted. However, you are welcome to fix your answer and I will happily up-vote it if it is correct.
– Brad
Dec 8 '14 at 14:28
Well, if you feel the answer isn't worth considering you can go ahead and get read of it. However, I thought the whole point of this community is to share and contribute knowledge. If you have something to share instead of showing and putting people off.
– user28864
Dec 8 '14 at 20:34
1
You are correct, the whole point of this community is to share knowledge. That's why added explanation with my downvote, and further explained why your filter suggestion was not sufficient. I'd much prefer to alert you, along with anyone else who finds your answer, that the code above is insecure. It's better for everyone to learn the correct methods rather than perpetuating bad code. And, I cannot delete your answer, nor would I. That's up to you, if you choose to do so.
– Brad
Dec 8 '14 at 20:44
add a comment |
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'];
}
}
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:35
But if the code works, I feel you should edit the code and input the needed filters instead of castigating the code.
– user28864
Dec 8 '14 at 12:28
Simple usage of filters will not fix what is wrong with this code. The best solution is to use prepared/parameterized queries with PDO or similar. I don't see any point in fixing it, as the correct answer has already been posted here. Ideally, this answer will be deleted. However, you are welcome to fix your answer and I will happily up-vote it if it is correct.
– Brad
Dec 8 '14 at 14:28
Well, if you feel the answer isn't worth considering you can go ahead and get read of it. However, I thought the whole point of this community is to share and contribute knowledge. If you have something to share instead of showing and putting people off.
– user28864
Dec 8 '14 at 20:34
1
You are correct, the whole point of this community is to share knowledge. That's why added explanation with my downvote, and further explained why your filter suggestion was not sufficient. I'd much prefer to alert you, along with anyone else who finds your answer, that the code above is insecure. It's better for everyone to learn the correct methods rather than perpetuating bad code. And, I cannot delete your answer, nor would I. That's up to you, if you choose to do so.
– Brad
Dec 8 '14 at 20:44
add a comment |
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'];
}
}
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'];
}
}
answered Dec 15 '13 at 20:27
user28864user28864
2,0191817
2,0191817
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:35
But if the code works, I feel you should edit the code and input the needed filters instead of castigating the code.
– user28864
Dec 8 '14 at 12:28
Simple usage of filters will not fix what is wrong with this code. The best solution is to use prepared/parameterized queries with PDO or similar. I don't see any point in fixing it, as the correct answer has already been posted here. Ideally, this answer will be deleted. However, you are welcome to fix your answer and I will happily up-vote it if it is correct.
– Brad
Dec 8 '14 at 14:28
Well, if you feel the answer isn't worth considering you can go ahead and get read of it. However, I thought the whole point of this community is to share and contribute knowledge. If you have something to share instead of showing and putting people off.
– user28864
Dec 8 '14 at 20:34
1
You are correct, the whole point of this community is to share knowledge. That's why added explanation with my downvote, and further explained why your filter suggestion was not sufficient. I'd much prefer to alert you, along with anyone else who finds your answer, that the code above is insecure. It's better for everyone to learn the correct methods rather than perpetuating bad code. And, I cannot delete your answer, nor would I. That's up to you, if you choose to do so.
– Brad
Dec 8 '14 at 20:44
add a comment |
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:35
But if the code works, I feel you should edit the code and input the needed filters instead of castigating the code.
– user28864
Dec 8 '14 at 12:28
Simple usage of filters will not fix what is wrong with this code. The best solution is to use prepared/parameterized queries with PDO or similar. I don't see any point in fixing it, as the correct answer has already been posted here. Ideally, this answer will be deleted. However, you are welcome to fix your answer and I will happily up-vote it if it is correct.
– Brad
Dec 8 '14 at 14:28
Well, if you feel the answer isn't worth considering you can go ahead and get read of it. However, I thought the whole point of this community is to share and contribute knowledge. If you have something to share instead of showing and putting people off.
– user28864
Dec 8 '14 at 20:34
1
You are correct, the whole point of this community is to share knowledge. That's why added explanation with my downvote, and further explained why your filter suggestion was not sufficient. I'd much prefer to alert you, along with anyone else who finds your answer, that the code above is insecure. It's better for everyone to learn the correct methods rather than perpetuating bad code. And, I cannot delete your answer, nor would I. That's up to you, if you choose to do so.
– Brad
Dec 8 '14 at 20:44
1
1
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:35
Do not use this code. It is wide open to SQL injection attacks.
– Brad
Dec 7 '14 at 17:35
But if the code works, I feel you should edit the code and input the needed filters instead of castigating the code.
– user28864
Dec 8 '14 at 12:28
But if the code works, I feel you should edit the code and input the needed filters instead of castigating the code.
– user28864
Dec 8 '14 at 12:28
Simple usage of filters will not fix what is wrong with this code. The best solution is to use prepared/parameterized queries with PDO or similar. I don't see any point in fixing it, as the correct answer has already been posted here. Ideally, this answer will be deleted. However, you are welcome to fix your answer and I will happily up-vote it if it is correct.
– Brad
Dec 8 '14 at 14:28
Simple usage of filters will not fix what is wrong with this code. The best solution is to use prepared/parameterized queries with PDO or similar. I don't see any point in fixing it, as the correct answer has already been posted here. Ideally, this answer will be deleted. However, you are welcome to fix your answer and I will happily up-vote it if it is correct.
– Brad
Dec 8 '14 at 14:28
Well, if you feel the answer isn't worth considering you can go ahead and get read of it. However, I thought the whole point of this community is to share and contribute knowledge. If you have something to share instead of showing and putting people off.
– user28864
Dec 8 '14 at 20:34
Well, if you feel the answer isn't worth considering you can go ahead and get read of it. However, I thought the whole point of this community is to share and contribute knowledge. If you have something to share instead of showing and putting people off.
– user28864
Dec 8 '14 at 20:34
1
1
You are correct, the whole point of this community is to share knowledge. That's why added explanation with my downvote, and further explained why your filter suggestion was not sufficient. I'd much prefer to alert you, along with anyone else who finds your answer, that the code above is insecure. It's better for everyone to learn the correct methods rather than perpetuating bad code. And, I cannot delete your answer, nor would I. That's up to you, if you choose to do so.
– Brad
Dec 8 '14 at 20:44
You are correct, the whole point of this community is to share knowledge. That's why added explanation with my downvote, and further explained why your filter suggestion was not sufficient. I'd much prefer to alert you, along with anyone else who finds your answer, that the code above is insecure. It's better for everyone to learn the correct methods rather than perpetuating bad code. And, I cannot delete your answer, nor would I. That's up to you, if you choose to do so.
– Brad
Dec 8 '14 at 20:44
add a comment |
You can try this code. I found it earlier when I was encountered a problem similar to yours.
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;
}
This code is wide open to SQL injection attacks, and does not actually solve the problem posed in the question.
– Brad
Dec 7 '14 at 17:28
add a comment |
You can try this code. I found it earlier when I was encountered a problem similar to yours.
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;
}
This code is wide open to SQL injection attacks, and does not actually solve the problem posed in the question.
– Brad
Dec 7 '14 at 17:28
add a comment |
You can try this code. I found it earlier when I was encountered a problem similar to yours.
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;
}
You can try this code. I found it earlier when I was encountered a problem similar to yours.
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;
}
edited Feb 7 '15 at 6:56
vaultah
27.3k975103
27.3k975103
answered Nov 26 '14 at 11:12
Mithun DebnathMithun Debnath
3721519
3721519
This code is wide open to SQL injection attacks, and does not actually solve the problem posed in the question.
– Brad
Dec 7 '14 at 17:28
add a comment |
This code is wide open to SQL injection attacks, and does not actually solve the problem posed in the question.
– Brad
Dec 7 '14 at 17:28
This code is wide open to SQL injection attacks, and does not actually solve the problem posed in the question.
– Brad
Dec 7 '14 at 17:28
This code is wide open to SQL injection attacks, and does not actually solve the problem posed in the question.
– Brad
Dec 7 '14 at 17:28
add a comment |
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);
.
2
1) You don't know if I have or have not voted on any answer here, up or down. 2) As I explained in my first comment; your answer doesn't reference the problem (boolean passed to mysql_fetch_array) and you have syntax errors
– Phil
Jan 21 '14 at 5:06
2
You have incorrect quotes in both your code examples. The syntax highlighting applied to your second code block is a dead give-away that something is wrong
– Phil
Jan 21 '14 at 5:35
2
This code is subject to SQL injection and should not be used. @EngrZardari if you are using this code on your production systems, you have undoubtedly been hacked and should remedy the situation buy using prepared/parameterized queries with PDO or similar. There are bots that have automated testing for such vulnerabilities.
– Brad
Dec 7 '14 at 17:31
1
@EngrZardari About your "there is no any error, i have pasted here code which i currently using." comment above. There was a missing quote in the query which I corrected. That would have thrown a (PHP) parse error.
– Funk Forty Niner
Nov 20 '18 at 18:51
add a comment |
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);
.
2
1) You don't know if I have or have not voted on any answer here, up or down. 2) As I explained in my first comment; your answer doesn't reference the problem (boolean passed to mysql_fetch_array) and you have syntax errors
– Phil
Jan 21 '14 at 5:06
2
You have incorrect quotes in both your code examples. The syntax highlighting applied to your second code block is a dead give-away that something is wrong
– Phil
Jan 21 '14 at 5:35
2
This code is subject to SQL injection and should not be used. @EngrZardari if you are using this code on your production systems, you have undoubtedly been hacked and should remedy the situation buy using prepared/parameterized queries with PDO or similar. There are bots that have automated testing for such vulnerabilities.
– Brad
Dec 7 '14 at 17:31
1
@EngrZardari About your "there is no any error, i have pasted here code which i currently using." comment above. There was a missing quote in the query which I corrected. That would have thrown a (PHP) parse error.
– Funk Forty Niner
Nov 20 '18 at 18:51
add a comment |
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);
.
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);
.
edited Nov 20 '18 at 18:50
Funk Forty Niner
1
1
answered Jan 21 '14 at 4:21
Engr ZardariEngr Zardari
6941126
6941126
2
1) You don't know if I have or have not voted on any answer here, up or down. 2) As I explained in my first comment; your answer doesn't reference the problem (boolean passed to mysql_fetch_array) and you have syntax errors
– Phil
Jan 21 '14 at 5:06
2
You have incorrect quotes in both your code examples. The syntax highlighting applied to your second code block is a dead give-away that something is wrong
– Phil
Jan 21 '14 at 5:35
2
This code is subject to SQL injection and should not be used. @EngrZardari if you are using this code on your production systems, you have undoubtedly been hacked and should remedy the situation buy using prepared/parameterized queries with PDO or similar. There are bots that have automated testing for such vulnerabilities.
– Brad
Dec 7 '14 at 17:31
1
@EngrZardari About your "there is no any error, i have pasted here code which i currently using." comment above. There was a missing quote in the query which I corrected. That would have thrown a (PHP) parse error.
– Funk Forty Niner
Nov 20 '18 at 18:51
add a comment |
2
1) You don't know if I have or have not voted on any answer here, up or down. 2) As I explained in my first comment; your answer doesn't reference the problem (boolean passed to mysql_fetch_array) and you have syntax errors
– Phil
Jan 21 '14 at 5:06
2
You have incorrect quotes in both your code examples. The syntax highlighting applied to your second code block is a dead give-away that something is wrong
– Phil
Jan 21 '14 at 5:35
2
This code is subject to SQL injection and should not be used. @EngrZardari if you are using this code on your production systems, you have undoubtedly been hacked and should remedy the situation buy using prepared/parameterized queries with PDO or similar. There are bots that have automated testing for such vulnerabilities.
– Brad
Dec 7 '14 at 17:31
1
@EngrZardari About your "there is no any error, i have pasted here code which i currently using." comment above. There was a missing quote in the query which I corrected. That would have thrown a (PHP) parse error.
– Funk Forty Niner
Nov 20 '18 at 18:51
2
2
1) You don't know if I have or have not voted on any answer here, up or down. 2) As I explained in my first comment; your answer doesn't reference the problem (boolean passed to mysql_fetch_array) and you have syntax errors
– Phil
Jan 21 '14 at 5:06
1) You don't know if I have or have not voted on any answer here, up or down. 2) As I explained in my first comment; your answer doesn't reference the problem (boolean passed to mysql_fetch_array) and you have syntax errors
– Phil
Jan 21 '14 at 5:06
2
2
You have incorrect quotes in both your code examples. The syntax highlighting applied to your second code block is a dead give-away that something is wrong
– Phil
Jan 21 '14 at 5:35
You have incorrect quotes in both your code examples. The syntax highlighting applied to your second code block is a dead give-away that something is wrong
– Phil
Jan 21 '14 at 5:35
2
2
This code is subject to SQL injection and should not be used. @EngrZardari if you are using this code on your production systems, you have undoubtedly been hacked and should remedy the situation buy using prepared/parameterized queries with PDO or similar. There are bots that have automated testing for such vulnerabilities.
– Brad
Dec 7 '14 at 17:31
This code is subject to SQL injection and should not be used. @EngrZardari if you are using this code on your production systems, you have undoubtedly been hacked and should remedy the situation buy using prepared/parameterized queries with PDO or similar. There are bots that have automated testing for such vulnerabilities.
– Brad
Dec 7 '14 at 17:31
1
1
@EngrZardari About your "there is no any error, i have pasted here code which i currently using." comment above. There was a missing quote in the query which I corrected. That would have thrown a (PHP) parse error.
– Funk Forty Niner
Nov 20 '18 at 18:51
@EngrZardari About your "there is no any error, i have pasted here code which i currently using." comment above. There was a missing quote in the query which I corrected. That would have thrown a (PHP) parse error.
– Funk Forty Niner
Nov 20 '18 at 18:51
add a comment |
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'];
}
}
1
This code is subject to SQL injection attacks and should not be used.
– Brad
Dec 7 '14 at 17:29
add a comment |
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'];
}
}
1
This code is subject to SQL injection attacks and should not be used.
– Brad
Dec 7 '14 at 17:29
add a comment |
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'];
}
}
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'];
}
}
edited Jul 14 '14 at 14:01
answered Apr 28 '14 at 8:52
Ritesh d joshiRitesh d joshi
69111014
69111014
1
This code is subject to SQL injection attacks and should not be used.
– Brad
Dec 7 '14 at 17:29
add a comment |
1
This code is subject to SQL injection attacks and should not be used.
– Brad
Dec 7 '14 at 17:29
1
1
This code is subject to SQL injection attacks and should not be used.
– Brad
Dec 7 '14 at 17:29
This code is subject to SQL injection attacks and should not be used.
– Brad
Dec 7 '14 at 17:29
add a comment |
1 2
next
14
you can get more useful eroor msg using:: QUERY or die(mysql_error());
– nik
Jun 4 '10 at 10:26
120
Also the obligatory note: Your code is prone to SQL injection. You should validate and/or escape the user input. Have a look at
mysql_real_escape_string
. Never trust user data.– Felix Kling
Jun 4 '10 at 10:26
7
Actually, the OP's code will cause a syntax error on the MySQL server, but at least it is not vulnerable to SQL Injection because single quotes doesn't have variable interpolation.
– szgal
Jul 4 '14 at 14:06
3
@FelixKling I realize this is very old, and likely the most accurate possible at the time, but your comment is now dangerously wrong in one way:
mysql_real_escape_string
is not the be-all and end-all of SQL injection protection; it's still vulnerable to a number of attacks. (No, you never said it's perfect, but you implied it was the only required solution) The best solution now is PDO, as far as I know.– Nic Hartley
Mar 13 '17 at 0:30
1
Besides the first error, what you posted would have thrown another error, this for
LIKE $username
since we're more than likely dealing with a string here and not an integer. Therefore it would require it to be quoted.– Funk Forty Niner
Nov 20 '18 at 18:56