This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
<?php
$abc = $objpdo->prepare("SELECT * FROM testdb.users WHERE user = ':login' AND user_pass=PASSWORD(':password')");
$abc->bindParam(':login', $_POST['name']);
$abc->bindParam(':password', $_POST['pw']);
$abc->execute();
echo $abc->rowCount();
// the example above doesn't work rowCount is always 0
$abc = $objpdo->prepare("SELECT * FROM testdb.users WHERE user = '?' AND user_pass=PASSWORD('?')");
$abc->execute([$_POST['name'], $_POST['pw']]);
echo $abc->rowCount();
// and again rowCount is always 0
$abc = $objpdo->query("SELECT * FROM testdb.users WHERE user = '".$_POST['name']."' AND user_pass=PASSWORD('".$_POST['pw']."')");
echo $abc->rowCount();
// this thing here is working
?>
The prepared statements i have at my code doesn't seem to work,
the strange thing is when i try running query() without preparing it but just directly passing the values to the string its working.
Note that i always try this code with existed users/passwords.
The placeholders don't need quotes around them or else the query will just treat them as strings, not placeholders.
$abc = $objpdo->prepare("SELECT * FROM testdb.users WHERE user = :login AND user_pass=PASSWORD(:password)");
Same with the ordinal placeholders (question marks):
$abc = $objpdo->prepare("SELECT * FROM testdb.users WHERE user = ? AND user_pass=PASSWORD(?)");
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
If you create a variable inside a if statement is it available outside the if statement?
(4 answers)
How to replace "if" statement with a ternary operator ( ? : )?
(16 answers)
If variable equals value php [duplicate]
(4 answers)
Closed 2 years ago.
There are a lot of examples on SO of using str_replace to modify a query that uses variables in MYSQL but I can't find one that solves my problem.
I have the following legacy query that I'm debugging written in PHP and MySQL.
Somewhat simplified it is:
$sql = "SELECT * from MOVIES WHERE cat = '$cat'";
In the event that cat has a certain value, say, "action" I want to check for "adventure";
Let's say you start with query:
$cat = "action";
$sql = "SELECT * FROM MOVIES WHERE cat='$cat'";
I'm trying to modify the query with:
$needle = "cat=".$cat;
$altcat = "adventure";
$altwhere = "cat=".altcat;
$sql = str_replace($needle,$altwhere,$sql); //NOTHING GETS REPLACED...NOT MATCHING Needle
How can I do this? I'm thinking the problem has something to do with use of spaces or apostrophes in the sql string but can't get it to work.
Thanks for any suggestions.
You want to replace "cat='".$cat."'" with "cat='adventure'", not "cat=".$cat with "cat=adventure".
(Though you are inconsistent in saying if there are spaces around the =.)
But you should not do this and should use a placeholder instead.
I would not try to do string substitution on the SQL query. Instead, just use query parameters.
$cat = 'action'; // suppose this is the input to your program
$sql = "SELECT * from MOVIES WHERE cat = ?";
if ($cat == 'action') {
$cat = 'adventure';
}
$stmt = $db->prepare($sql);
$stmt->execute( [ $cat ] );
This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I have been using the same code for years and all of a sudden I'm having problems that I cannot figure out. I am making a very simple query to MySQL in PHP using a variable in the statement. When I use the variable, it returns no results. When I manually type in the value of the variable instead, it works. I use this syntax all day long and never have had a problem. What on earth is wrong?
$name = "Fred";
$query = "SELECT * FROM database WHERE name='".$name."'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) != 0) {
echo "Found record.";
}
If I replace the $name variable with Fred, it finds the record. If I echo the query with the variable before it executes and place that exact statement into MySQL directly in phpMyAdmin, I also get the result. If I leave the statement as-is with the variable in place, I get no result. Please help.
your query states SELECT * FROM database WHERE name='".$name."', this means that your table name is database, now i dont know how you actually created this table but database is a MYSQL reserved keyword change the name of your table to something else or just change your query to
$query = "SELECT * FROM `database` WHERE name='$name'";
assuming that your database connection is fine your code should now work
also worth noting, whenever acquiring data from a database use prepared statements instead of raw data as it makes you vulnerable to sql injection, in your case your code should be something like this
$name = "Fred";
$stmt = $dbconnection->prepare("SELECT * FROM table_name WHERE name=?")
$stmt->bind_param("s", $name);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows != 0)
{
echo "Found record.";
}
this is more secure
You shouldn't use mysqli excepted for old projects you can't upgrade, it's outdated and suffers from potential sql injection vulnerabilities.
Instead, I recommand you to learn PDO and prepared statements.
Your request should look like this :
$name = 'Fred';
$sql = "SELECT * FROM my_user_table WHERE name = :name";
// You should have set your pdo instance in a script handling your database connexion and reusing it in any script making requests.
$result = $pdo->prepare($sql);
// Here you dynamically inject values in your request and tells pdo what type of data you are expecting
$result->bindValue(':name', $name, PDO::PARAM_STR);
$result->execute();
if( $result->rowCount()) {
echo "{$result->rowCount()} result(s) found";
}
else {
echo 'No result found';
}
Here's the official doc :
https://www.php.net/manual/fr/book.pdo.php
This will also more than probably fix your problem.
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 7 years ago.
i've got this part of code in my php app
$find_user = "SELECT * FROM tcms_module_profiles WHERE profile_contact_email = ".$_POST['email'];
$num_rows = mysql_num_rows(mysql_query($find_user));
that return this error message:
mysql_num_rows() expects parameter 1 to be resource, boolean given
But i'm passing a query result to mysql_num_rows(). I've checked the query and it's correct (because if i execute it on phpMyAdmin it return the record).
Thanks in advance for all the help
You need to put your profile_contact_email values in quotes because to insert VARCARE field we need quotes around it. And use mysql_real_escape_string in your query to prevent sql injection
$email = mysql_real_escape_string($_POST['email']);
$find_user = "SELECT * FROM tcms_module_profiles WHERE
profile_contact_email = '".$email."'";
$result = mysql_query($find_user);
$num_rows = mysql_num_rows($result);
Note:- mysql is deprecated instead use mysqli or PDO
Your SQL query failed, resulting in mysql_query returning a boolean FALSE value. It failed because you didn't use quotes around your email.
Your script is also open to SQL injection, btw.
Use the following code:
$find_user = "SELECT * FROM `tcms_module_profiles` WHERE `profile_contact_email`='{$_POST['email']}';";
$result = mysql_query($find_user);
if(!$result){die("ERROR");}
$num_rows = mysql_num_rows($result);
Your code was missing '' around $_POST['email'] and you should check first for the query to be true. mysql_ is deprecated use mysqli_ or PDO extension. Mysqli & PDO
A mysqli version of above code
$find_user = "SELECT * FROM `tcms_module_profiles` WHERE `profile_contact_email`='{$_POST['email']}'";
$result = mysqli_query($find_user);
if(!$result){die("ERROR");}
$num_rows = mysqli_num_rows($result);
Note - you also need to change your mysql connection variables according to mysqli.
Try this...
$find_user = "SELECT * FROM tcms_module_profiles WHERE profile_contact_email = '".$_POST['email']."'";
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
Every question which I asked on stackoverflow I received a question that It was easy to do a php injection into my script.
I've now a example and checked some tutorials on youtube.
Am I doing this right now?
This is an example how I'm working now
if($user->isLoggedIn()) {
$pakuser = $user->data()->username;
$sql = $db->query("SELECT * FROM users
INNER JOIN post ON users.username = post.add
WHERE post.id = $id AND post.add = '$pakuser'")
or die(mysql_error());
if ($sql === FALSE) {
}
if($row = $sql->fetch_object())
if($row->add)
{
?>
<p>edit this post<br><br>BEWARE OF DELETING YOUR CONTENT THERE IS NO GO-BACK<BR>Delete this post </p>
<?php
}
}
Everytime the user can manipulate your sql-query without any restriction, there is a security-issue. Here is an example:
$query_string = "SELECT * FROM user WHERE (name='$username' AND password='$password')";
if the user sends a password like:
"something') OR ('1' = '1"
the query will change to:
$query_string = "SELECT * FROM user WHERE (name='Name' AND password='something') OR ('1' = '1')";
Because '1'='1' is always true, this will return each user in your database.
Instead you can change the example above to:
$query = mysqli->prepare('SELECT * FROM user WHERE (name=? AND password=?)');
$query->bind_param('ss', $username, $password);
$query->execute();
This will filter all strings that could break your sql-query.
It seems like you are still just passing variables straight through into the query. Yes, this may work, but is not necessary secure.
You could have a look at using PDO instead, which has means of being able to verify the data type that you are wanting to pass through into your query rather than just passing a variable into the query string.
In terms of using mysqli, have a look at mysqli_real_escape_string if you have not already. It is well documented.
This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
MySQLi Bind Param with an array for IN [duplicate]
(2 answers)
Closed 9 years ago.
I'm trying to write code that basically finds your facebook friends that are on my website. I succeed in phpmyadmin running the query but for some reason when i try to run the code from php it doesn't work
Here's the php code. Whenever i take the $string echo and place it in mysql it works just fine, but for whatever reason when running it in php the query is not returning any results.
$fql = "SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = 100000903067831) AND is_app_user = 'true'";
$param = array(
'method' => 'fql.query',
'query' => $fql
);
$this->load->library('facebook');
echo $this->facebook->getLoginUrl();
$fqlResult = $this->facebook->api($param);
$userIDarray = array();
foreach($fqlResult as $result)
{
echo $result['uid']."<br>";
array_push($userIDarray, intval($result['uid']));
}
$string = implode(', ',$userIDarray);
echo $string;
$vars = array($string);
$query = $this->db->query("SELECT * FROM users WHERE users.facebook_id IN (?)", $vars);
echo var_dump($query);
foreach($query->result() as $data)
{
echo var_dump($data);
}
You cannot pass multiple parameters in a single ?.
You need to construct the options for IN yourself using concatenation.
Like so:
foreach($fqlResult as $result)
{
echo $result['uid']."<br>";
array_push($userIDarray, intval($result['uid']));
}
$string = implode(', ',$userIDarray);
$query = $this->db->query("SELECT * FROM users WHERE users.facebook_id
IN ('.$string.')");
Note that you need to make sure your items in the $userIDarray are properly escaped.
Because you're not using parameters, but you've injected these values into your SQL you are in danger of SQL injection attacks.
You are passing them through intval which guarantees that the strings will only contain 0..9 and - so you are safe from that here.
If the data is not numeric, you need use mysqli_real_escape_string to compensate for the fact that you're bypassing PDO's parameters.