I receive a post and want to do some actions only if the value of variable received in post exists in a specific column of the table. So i did this:
$pedidoID = $_POST["pedidoID"];
$con = mysql_connect("127.0.0.1", "root", "password") or die("Could not connect: " . mysql_error());
$result = mysql_query('SELECT id FROM listapagamento WHERE numeroPedido = "pedidoID"');
if(mysql_num_rows($result) == 0) {
//Some actions
}
So if the value from pedidoID doesn't exist in the column numeroPedido it will do the actions, because result will be 0 (because no rows are found).
What is happenning is that the $result is returning as bool(false) in both cases (if the value exists or not). I guess that my problem is how I'm using the variable inside the SELECT to compare to the column. I've tried to insert $_POST["pedidoID"] inside the SELECT also but my syntax was also wrong.
Does anyone know the correct syntax to use?
Try:
$pedidoID = mysql_real_escape_string($_POST["pedidoID"]);
$con = mysql_connect("127.0.0.1", "root", "password") or die("Could not connect: " . mysql_error());
mysql_select_db('<your_database_name>', $con);
$result = mysql_query("SELECT id FROM listapagamento WHERE numeroPedido = 'pedidoID'");
if(mysql_num_rows($result) == 0) {
//Some actions
}
Right now you are comparing the column's value with a fixed string, hence your error. Put the variable in the code instead.
$pedidoID = $_POST["pedidoID"];
$con = mysql_connect("127.0.0.1", "root", "Password") or die("Could not connect: " . mysql_error());
$result = mysql_query('SELECT id FROM listapagamento WHERE numeroPedido = "' . $pedidoID . '"');
if(mysql_num_rows($result) == 0) {
//Some actions
}
HOWEVER this code is wide open to SQL injection attacks, you should always sanitize any input before using it. Which, as recommended, would look like:
$pedidoID = $_POST["pedidoID"];
$con = mysql_connect("127.0.0.1", "root", "Password") or die("Could not connect: " . mysql_error());
$result = mysql_query('SELECT id FROM listapagamento WHERE numeroPedido = "' . mysqli_real_escape_string($pedidoID) . '"');
if(mysql_num_rows($result) == 0) {
//Some actions
}
When you write code that deal with database, make always sure that it's not vulnerable to sql injection. Now for your case, you have to treat the post element before using it:
$pedidoID = mysql_real_escape_string ($_POST["pedidoID"]);
Then for your bug, you haven't select the database:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Connection to Mysql failed : ' . mysql_error());
}
$db_selected = mysql_select_db('database', $link);
if (!$db_selected) {
die ('connection to database failed : ' .mysql_error());
}
$result = mysql_query("SELECT id FROM listapagamento WHERE numeroPedido=$pedidoID");