Compare PHP Variable value with MySQL Column value - php

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
}

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");

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
}

Related

PHP: Warning: mysql_fetch_array() expects parameter 1 to be resource

I got this error while adding this code. Would appreciate some help. It's for a CS jackpot site.
$sitename = "website.com"; // YOUR DOMAIN
$link = mysql_connect("localhost", "db_user", "db_pass"); // MYSQL , LOCALHOOST , USERNAME , PASSWORD
$db_selected = mysql_select_db('db_name', $link); // MYSQL DATABASE
mysql_query("SET NAMES utf8");
function fetchinfo($rowname,$tablename,$finder,$findervalue) {
if($finder == "1") $result = mysql_query("SELECT $rowname FROM $tablename");
else $result = mysql_query("SELECT $rowname FROM $tablename WHERE `$finder`='$findervalue'");
while($row = mysql_fetch_assoc($query))
return $row[$rowname];
}
Some tips:
Use mysqli better than mysql
Split the vars in the query, like "SELECT ".$rowname." FROM ".$tablename;
Hope this help...
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Select Query
$result = $mysqli->query("SELECT id, product_name FROM products");
while($row = $results->fetch_assoc()) {
echo $row["id"].' - '.$row["product_name"].'<br>';
}
$results->free();
$mysqli->close();

Error occurred ... no database selected

I'm trying to connect to a database, check a column for whether a value exists or not, then execute a function based on whether or not that value exists.
Here's my code.
$con = mysql_connect('localhost','root','','users');
$sql = "SELECT * FROM allUsers WHERE username = '".mysql_real_escape_string($_POST["username"]) . "'";
$result = mysql_query($sql,$con) or die("Error occurred in [$sql]: " . mysql_error());
$count = mysql_num_rows($result);
if ($count != 0){
echo "Username is already taken";
echo "$count";
mysql_close($con);
}
else{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
The thrown error is:
Error occurred in [SELECT * FROM allUsers WHERE username = 'Admin']: No database selected.
I'm almost entirely sure that it comes from the $result line, but haven't a clue as to why.
I feel like this is a simple solution, and I'm just missing something minor.
I'm very new to MySQL (today is my first day, actually), so please keep solutions as simple as possible.
You forgot to call mysql_select_db after connecting:
$con = mysql_connect('localhost','root','');
mysql_select_db('users', $con);
Unlike MySQLi or PDO, mysql_* libraries does not take database as argument on the connection string, however if you were to migrate to either MySQLi or PDO.
MySQLi:
$con = new mysqli('localhost', 'root', '', 'users');
PDO:
$con = new PDO('mysql:host=localhost;dbname=users', 'root', '');
In MySQLi your code would look like this:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database = "users";
$con = mysqli_connect($host,$user,$pass,$database);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$stmt = $con->prepare("SELECT * FROM allUsers WHERE username = ? LIMIT 1");
$stmt->bind_param('s',$_POST["username"]);
if (!$stmt->execute())
die('Failed to excute with error ' . $con->error);
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if ($count > 0)
{
echo "Username is already taken.";
}
else
{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
I think your error is quite obvious, you need to specify the database you want.
mysql_select_db("databaseName", $con);
With that taken care of, please, please don't use mysql_ libraries the are vulnerable to SQL injection and will soon be removed.

MySQL won't update with URL variable

I'm having troubles getting my code to work properly. If I type it into phpMyAdmin it works, but when I try it in the code, it doesn't update the database.
<?php
$con = mysql_connect("SERVER","USER","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DATABASE", $con);
$sp=mysql_real_escape_string($_GET['file']);
$query = "UPDATE TDB SET WEIGHT=100000 WHERE PATH='$sp'";
mysql_close($con);
?>
Try out this code snippet and see how you get on.
<?php
$con = mysql_connect("SERVER","USER","PASSWORD");
if (!$con) {
die('Could not connect: ' . mysql_error());
} else {
mysql_select_db("DATABASE", $con);
$sp=mysql_real_escape_string($_GET['file']);
$query = "UPDATE TDB SET WEIGHT=100000 WHERE PATH='$sp'";
$result = mysql_query($query);
mysql_close($con);
}
?>
I would recommend doing it this way as mysql is no longer supported by PHP.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if (!$mysqli) {
die('Could not connect: ' . $mysqli->connect_error);
} else {
$sp = $mysqli->real_escape_string($_GET['file']);
$query = "UPDATE TDB SET WEIGHT=100000 WHERE PATH='$sp'";
$mysqli->query(query);
$mysqli->close();
}
?>
You're not EXECUTING your query. You're just defining a string that happens to contain some SQL, e.g.
$sql = "blah blah blah";
$result = mysql_query($sql) or die(mysql_error()); <--forgot this
<?php
$con = mysql_connect("SERVER","USER","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DATABASE", $con);
$sp=mysql_real_escape_string($_GET['file']);
$sql = "UPDATE TRACKDB SET WEIGHT=100000 WHERE PATH='$sp'";
$result = mysql_query($sql) or die(mysql_error());
mysql_close($con);
?>

undefined variable php updating mysql data [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
This is the code for attempting to do a update on mysql data errors stating undefined variable
mysql_connect ("localhost", "root", "");
mysql_select_db("supplierdetails");
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//Run a query
$result = mysql_query ("SELECT * FROM users WHERE id= '$id'");
while ($row = mysql_fetch_array($result))
{
$username=$row['username'];
$password=$row['password'];
}
$query = "UPDATE users SET username = '$username', password = '$password' WHERE id = '$id'";
$result = #mysql_query($query);
//Check whether the query was successful or not
if($result) {
header("message= Users Updated");
}else {
die("Query failed");
}
?>
You miss the $id value?
And can use echo to debug or check script result, not header
http://php.net/manual/en/function.header.php
Please be more specific with regards to which variable is undefined.
In the code you've posted $username and $password are only set if $result returns a result, if it doesn't then your while loop will not run and therefore $username and $password will never be set.
Also $id doesn't look as if that has been set either, unless this has been set outside of the code which you have included in your question.
Hope this helps :)
you used 2 connect no need to do while and you forgot $id
$con = mysql_connect("localhost", "root", "");
mysql_select_db("supplierdetails");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$id = $_POST['id'];
$username=$_POST['username'];
$password=$_POST['password'];
$query = "UPDATE users SET username = '".$username."', password = '".$password."' WHERE id = '".$id."'";
$result = mysql_query($query);
//Check whether the query was successful or not
if($result) {
echo "message= Users Updated";
}else {
die("Query failed");
}
?>

PHP not finding mySQL database?

I must be doing something wrong
I have a very simple script and a very simple database
No idea why it's not working..
Please help
<?php
error_reporting(E_ALL);
$link = mysql_connect('localhost', 'root', 'password');
if(!$link)
{
die('Could not connect: ' . mysql_error());
}
$database = mysql_select_db('test_db', $link);
if(!$database)
{
die('Could not connect to database: ' . mysql_error());
}
$result = mysqli_query($link, "SELECT forename FROM users WHERE id='1'");
if(!$result)
echo 'PROBLEM';
$row = mysqli_fetch_array($result);
echo $row[0];
?>
It's not even giving any errors, just echoing 'Problem'...
The database connects fine, and there is 1 user in the database with an ID of 1 and forename is Cristian.
In $result = mysqli_query try just useing $result = mysql_query same in $row = mysqli_fetch_array should help
Try replaceing you code from $result onward with this
$result = mysql_query("SELECT forename FROM users WHERE id='1'");
if(!$result)
echo 'PROBLEM';
$row = mysql_fetch_array($result);
echo $row[0];
?>

Categories