a very simple query is not working PHP - php

i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S
here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!
<?php
$email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];
$connection = mysql_connect('localhost','root','') ;
$db_selected = mysql_select_db("lab5" , $connection) ;
$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
while($row=mysql_fetch_array($result))
{
echo $row['name'];
}
mysql_close($connection);
?>

You use single quotes in the query variable. Single quotes does not substitute variables - so it looks for literal string $email not the variable email. Either use double quotes or even better use something like PDO which would do the work for you.
You should also sanitize your inputs from SQL/XSS vulnerabilities.

The basic debugging steps are 1. adding
if (!$result) echo "Error: ".mysql_error();
to see any errors from the SQL query and 2. outputting
echo "Query: $query";
to see what the variables contain. One of these will point you to the problem.
Also, your query is vulnerable to SQL injection. You should add a
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password );
after fetching the values from the POST array.

Your error probably resides in the fact that you don’t escape your parameters.
While you are at it, use MySQLi or PDO (maybe even some prepared statements)
Someone mentioned your use of single-quotes, that’s the real error, my bad.
But my advice still stands. Having used prepared statements, you wouldn’t have fell for that mistake

try
$query = 'select * From user where email="' . $email . '" and password="'. $password . '" ' ;
or
$query = "select * From user where email='$email' and password='$password'" ;

Try this instead:
$query = "select * From user where email='" . $email . "' and password='" . $password . "';
Then immediately change that to this instead:
$query = "select * From user where email='" . mysql_real_escape_string($email) . "' and password='" . mysql_real_escape_string($password) . "';

Try
$query = "SELECT * FROM user WHERE email = '".$email."' AND password = '".$password."'";

You've confused the single and double quotes
You have:
$query = 'select * From user where email="$email" and password="$password" ' ;
You want:
$query = "select * From user where email='$email' and password='$password' " ;
Single quotes evaluate to whats literally inside. Double quotes will parse for variables inside. Theres also a curly brace {$variable} syntax you can use.
Suggestions from other posters for using mysql_real_escape or using newer mysqli or PDO are important as well. At the very least use mysql_real_escape on parameters that come from user input.

the problem is the way you are quoting the variables. Suppose that $email= 'some#gmail.com' and $password= 'securenot'.
what we want is the final interpreted string to be the following
select * from user where email='some#gmail.com' and password='securenot'
to achieve this we simply replace the some#gmail.com for $email and securenot for $password and get the following:
select * from user where email='$email' and password='$password'.
and then in php code ...
$query = "select * from user where email='$email' and password='$password'";
hope that is of some help

mysql_fetch_assoc() for associative array. You cannot use normal array as assoc array.
while($row=mysql_fetch_assoc($result))
{
echo $row['name'];
}

Related

getting an error while passing this query to get login name from table

Help me getting login_name from database stored in table named users m working in ci
And applying this query and its giving a error in it
$sql = mysql_query("SELECT login_name FROM users WHERE email='".$_POST['email']."')"";
$row = mysql_fetch_array($sql);
echo $row['login_name'] ;
I'm getting this error
Parse error: syntax error, unexpected '"' in
K:\xampp\htdocs\codeigniter\application\controllers\users\users.php on
line 56
You have your quotes mixed up, try this
$sql = mysql_query("SELECT login_name FROM users WHERE email='".$_POST['email']."'");
$sql = mysql_query("SELECT login_name FROM users WHERE email='" . $_POST['email'] . "'");
Replace to this.
$sql = mysql_query("SELECT login_name FROM users WHERE email='".$_POST['email']."'");
It looks like you have an issue with your quotes.
Try something like this:
$sql = mysql_query("SELECT login_name FROM users WHERE email='" . $_POST['email'] . "'");
It has extra double quotes at the end of the line.
While this isn't directly an answer to your question, I strongly suggest you check out http://bobby-tables.com/php.html. It shows the correct syntax for what you're trying to do, as well as showing how to prevent sql injection, which the code you've shown is vulnerably to.

Textareas with dynamically-assigned name throws my code

I have a number of textareas, each with a unique assigned name (name="adcode$ID", for example). When I try to pass those names to the code below, it doesn't work because of the dynamic part.
if (isset($_POST['editadapp'])) { // Edit AD
$newadcode = mysql_real_escape_string($_POST['.adcode$ID.']);
$doedit = "UPDATE ads SET adcode = '".$newadcode."') WHERE ads_ID=$ID" or die(mysql_error());
$updatead = mysql_query($doedit) or die(mysql_error());
header("Location: " . $_SERVER['PHP_SELF']);
How can I resolve this?
There is so much wrong with this that it's frightening.
Firstly,
$doedit = "UPDATE ads SET adcode = '".$newadcode."') WHERE ads_ID=$ID" or die(mysql_error());
That code snippet is wrong on many levels.
The sql syntax is wrong
The sql is formatted with strings from user input (see parameterization of queries here
or die() should not be used here, you're creating a string
Ideally you should have code like:
$dbh = new PDO('connectionstring to connect to your database');
$sql = 'update ads set adcode = ? where ads_id = ?';
$sth = $dbh->prepare($sql);
$sth->execute(array($_POST['adcode' . $ID], $ID));
Other topics:
Are Paramerterized queries necessary in pdo?
prepared queries with pdo
Preventing sql injection in php
You seem to be attempting string concatenation. Here's how to do that correctly:
$newadcode = mysql_real_escape_string($_POST['adcode' . $ID]);
The following line should simply create a string containing your SQL query; you don't execute it until the next line, there is no function call so the or die is out of place. You also mix concatenation with interpolation (variable names within a double quoted string) which is fine but probably not helping you understand your syntax issues, so let's be consistent:
$doedit = "UPDATE ads SET adcode = '" . $newadcode . "' WHERE ads_ID = " . $ID;
you should use array like adcode[<?php echo $ID;?>] at your page where the text area is and a hidden field name=adID[$ID]. At the page where the query executes
$adID = $_POST['adID'];
$newadcode = mysql_real_escape_string($_POST['adcode']);
$N = count($adID);
for($i=0;$N<$i;$i++){
$doedit = mysql_query("UPDATE ads SET adcode = '$newadcode[$i]' WHERE ads_ID=$adID[$i];") or die(mysql_error());

What is the proper syntax for inserting variables into a SELECT statement?

I believe I have a simple syntax problem in my SQL statement. If I run this code, I get an error in the database query.
$user = $_GET['linevar'];
echo $user; // testing - url variable echos correctly
$sql = "SELECT * FROM `userAccounts` WHERE `name` = $user";
$result = mysql_query($sql) or die("Error in db query");
If I replace $user in the $sql string with 'actualName' or a known record in my table, the code works fine. Am I using the $ variable incorrectly in the SQL string?
You need to surround the value that you're getting from $user with quotes, since it's probably not a number:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
Just as a note, you should also read up on SQL injection, since this code is susceptible to it. A fix would be to pass it through mysql_real_escape_string():
$user = mysql_real_escape_string( $_GET['linevar']);
You can also replace your or die(); logic with something a bit more informative to get an error message when something bad happens, like:
or die("Error in db query" . mysql_error());
You need escape the get input, then quote it.
// this is important to prevent sql injection.
$user = mysql_real_escape_string($_GET['linevar']);
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
This should work:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '" . $user . "'";

How to escape quotes in a MYSQL query?

Example: The follwing query give me Quotes error in the field -> GET['email']
mysql_query(" select * from user_info where user_mail = '$_GET['email']' ")
You might want to escape the string first:
$_GET['email'] = mysql_real_escape_string($_GET['email']);
And then:
mysql_query(" select * from user_info where user_mail = '" . $_GET['email'] . "' ");
The dots put the strings together.
Use accolades like this.
mysql_query(" select * from user_info where user_mail = '{$_GET['email']}' ")
Also, make sure to escape your user input. Your current setup looks like it is vulnerable to SQL injection. Use http://php.net/manual/en/function.mysql-real-escape-string.php to clean up your user input (like $_GET values)
It's not really an answer to your question, but I'd strongly advise you to use PDO or mysqli prepared statements. Thus, your original problem -- the escaping parameter strings -- will be automatically taken care of.
If you do not want to follow this advice, do this:
$email = mysql_real_escape_string($_GET['email']);
mysql_query("select * from user_info where user_mail = '$email';");
You don't need quotation marks for associative array field names if you are already inside a doubly-quoted string:
$str = "Hello $_GET[email].";
Use it this way:
$SQL = "SELECT * FROM user_info WHERE user_mail = '".$_GET['email']."'";
mysql_query($SQL);
But I strongly advice to take some security actions with $_GET['email'], like this:
$email = mysql_real_escape_string($_GET['email']);
$SQL = "SELECT * FROM user_info WHERE user_mail = '".$email."'";
mysql_query($SQL);

Am I using mysql_real_escape_string right?

Is this the right way to use mysql_real_escape_string? I was using $GET but a friend told me to make it safer with real_escape_string:
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = $id") or die("err0r");
if(!$result) mysql_real_escape_string($id); {
No, you normally use mysql_real_escape_string to prepare variables for use in a query, but in your case:
you already use intval;
you use it in the wrong place.
You don't need it in your example.
No. That is entirely wrong, and I can't quite understand what you're intending the call to do.
The purpose of mysql_real_escape_string is to avoid SQL injection, which is one of the biggest security risks in a website. It stops your users giving input that manipulates the SQL in evil ways. For instance:
$sql = "SELECT FROM users WHERE username = '" . $_GET['username'] . "'";
If I put lonesomeday' or 'a' = 'a into $_GET['username'], your query becomes
SELECT FROM users WHERE username = 'lonesomeday' or 'a' = 'a'
and obviously arbitrary SQL could then be executed. mysql_real_escape_string escapes unsafe characters (such as ' in that example), so that they can't be used in this way.
$sql = "SELECT FROM users WHERE username = '" . mysql_real_escape_string($_GET['username']) . "'";
// SELECT FROM users WHERE username = 'lonesomeday\' or \'a\' = \'a'
The quotes are now escaped. so the query can't be manipulated into doing evil things.
With all that said, in this case, intval does all you need. It also ensures that nothing that is not an integer can be in $id, so your code is safe here from SQL injection.
NO, you need to escape before quering
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = '" . mysql_real_escape_string($id) . "'") or die("err0r");
if(!$result) {
}
Use:
$query = sprintf("SELECT *
FROM products
WHERE id = %d",
intval($_GET['id']));
$result = mysql_query($query) or die("err0r");
You use mysql_real_escape_string before the value is used in the query, otherwise you're not handling the SQL injection attack.
you want to escape it before you stick it in a query (Before it interacts with DB so you don't get injections).
// check if your $_GET is not empty otherwise you
// will run into "undefined variable"
if(!empty($_GET['id'])){
$id = intval($_GET['id']);
// to simplify you can escape here,
// or to be a bit more complex, you can escape in the query line.
$id = mysql_real_escape_string($id);
$result = mysql_query("SELECT *
FROM products
WHERE id = '$id'") or die("err0r");
}
else
print 'No ID';

Categories