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 ] );
Related
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I was wondering if it was possible to get a value from mysqli query and use it in the same page, if so how would I do that here?
$sql2 = "select artistName from ARTIST";
$result2 = $conn->query($sql2);
if($result2->num_rows != 0){
echo "<p>Artist: <select artistname=\"artistName\">";
while ($val2 = $result2->fetch_assoc()) {
echo "<option value='$val2[artistName]'>$val2[artistName]</option>";
}
echo "</select></p>";
}
I am trying to make this request below:
$addArt = "update ARTIST set Aname='$fileName' where artistName='$val2[artistName]'";
where filename is an arbitrary file
Multiple issues:
Mixed quotes:
"<option value='$val2[artistName]'>$val2[artistName]</option>"
"update ARTIST set Aname='$fileName' where artistName='$val2[artistName]'"
Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
Reference: https://www.php.net/manual/en/language.types.string.php
SQL Injection
"update ARTIST set Aname='$fileName' where artistName='$val2[artistName]'"
You need to be careful with how you get the value $val2[artistName] else it may lead to SQL Injection attack
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
PDO: error handling
(2 answers)
Closed 3 years ago.
I get this error Invalid parameter number: parameter was not defined in C:\wamp\www\stage\core\addtUsers.php on line 20
if(!empty($_POST["add_record"])) {
require_once("connection.php");
$data = [
'username' =>$_POST["username"],
'password' =>$_POST["password"],
'role' =>$_POST["role"],
'photo' =>$_POST["photo"],
'nom-prenom' =>$_POST["nom-prenom"]
];
$sql = "INSERT INTO users(username,password,role,photo,nom-prenom) VALUES (:username,:password,:role,:photo,:nom-prenom)";
$statement = $pdo->prepare( $sql );
$result = $statement->execute($data);
if (!empty($result) ){
header('location:users.php');
}
}
You can't use - in the name of a placeholder. This will be understood as an arithmetic subtraction.
Consider this example:
$pdo->prepare('SELECT :num-1')->execute(['num'=>5]);
It looks for a param called :num or num and then it will subtract 1 from it.
A good IDE might even help you out by highlighting this:
Although with letters it would highlight it the same color as a column name, which could also be missed.
Try to use a different placeholder name e.g. :nom_prenom
This question already has answers here:
Use an array in a mysqli prepared statement: `WHERE .. IN(..)` query [duplicate]
(8 answers)
Closed 11 months ago.
I'm trying to create a select query with dynamic where clause and dynamic parameters but I always get error :
Warning: mysqli_stmt::bind_param(): Number of elements in type
definition string doesn't match number of bind variables
Which I sincerely do not understand since it seems the count is alright. So this is what the code really looks like in its rude format. I can't see what I'm doing wrong.
//get variables
$mediaArray ='Facebook,Twitter,Twitch,';
$otherMedia = 'House';
//convert string to array
$socialArray = explode(',', $mediaArray)
//declare some variables to be used later
$andwhere = '';
$bp = '';
$socialmarray = ''
//get every value from array of social media
foreach($socialArray as $socialmedia){
$socialmarray .=$socialmedia.',';
$andwhere .= " AND socialmedianame=?";
$bp .='s';
}
//test strings
echo $wheres = $andwhere;//AND socialmedianame=? AND socialmedianame=? AND socialmedianame=?
echo $bip = $bp.'s';//ssss
echo $validarayy = rtrim($socialmarray,',');//Facebook,Twitter,Twitch
//select query
$selectquery = $conn->prepare("select * from mediaservices where socialmedianame=? $wheres");
$selectquery->bind_param("$bip",$otherMedia,$validarayy);
$selectquery->execute();
$resultquery = $selectquery->get_result();
Because:
You are using user-supplied data, you must assume that your query is vulnerable to a malicious injection attack and
the amount of data that is to be built into the query is variable/indefinite and
you are only writing conditional checks on a single table column
You should use a prepared statement and merge all of the WHERE clause logic into a single IN statement.
Building this dynamic prepared statement is more convoluted (in terms of syntax) than using pdo, but it doesn't mean that you need to abandon mysqli simply because of this task.
$mediaArray ='Facebook,Twitter,Twitch,';
$otherMedia = 'House';
$media = array_unique(explode(',', $mediaArray . $otherMedia));
$count = count($media);
$conn = new mysqli("localhost", "root", "", "myDB");
$sql = "SELECT * FROM mediaservices";
if ($count) {
$stmt = $conn->prepare("$sql WHERE socialmedianame IN (" . implode(',', array_fill(0, $count, '?')) . ")");
$stmt->bind_param(str_repeat('s', $count), ...$media);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = $conn->query($sql);
}
foreach ($result as $row) {
// access values like $row['socialmedianame']
}
For anyone looking for similar dynamic querying techniques:
SELECT with dynamic number of LIKE conditions
INSERT dynamic number of rows with one execute() call
In your query:
$selectquery = $conn->prepare("select * from mediaservices where socialmedianame=? $wheres");
The ? represents one parameter to pass in, and the evaluation of $wheres adds another three, giving you four total parameters.
bind_param() should take a string representing the types of the variables to insert as the first parameter, and the variables themselves as the subsequent parameters.
In your bind:
$selectquery->bind_param("$bip",$otherMedia,$validarayy);
$bip evaluates to ssss and $otherMedia is a single string ("House"). You might expect $validarayy to be three strings, but rtrim() returns a string. Thus, it is only one string ("Facebook,Twitter,Twitch"). You pass through two variables when the query is expecting four:
$conn->prepare("select * from mediaservices where socialmedianame=House AND socialmedianame=Facebook,Twitter,Twitch AND socialmedianame=? AND socialmedianame=? AND socialmedianame=?"
To correct this, you'll want to convert $validarayy back to an array, and use the index for the various inputs:
$socialmarray2 = explode(',', $validarayy);
$selectquery->bind_param("$bip", $otherMedia, $socialmarray2[0], $socialmarray2[1], $socialmarray2[2]);
Also note that your sample code has a few missing semicolons; you'll need to fix these in order for your code to work correctly.
This can be seen working here.
Finally, note that even if you were to split the three strings out correctly, the selection of ... AND socialmedianame=Facebook AND socialmedianame=Twitter AND socialmedianame=Twitch will never match any results; socialmedianame can only contain one value. You're probably looking to substitute your AND statements with OR statements.
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(?)");
This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 10 years ago.
I'm was trying to get my function to work and after a while I slammed my keyboard down and then everything worked and I noticed that:
{
function get_people_fullname($db, $people_id) {
$query = 'SELECT
people_fullname
FROM
people
WHERE
people_id = '.$people_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
$row = mysql_fetch_assoc($result);
return $row['people_fullname'];}
}
where there query goes
people_id = '.$people_id;
which works
I originally had
people_id = $people_id';
which doesn't work
I'm just lost and I think this is a simple thing someone more experienced can explain this to Me?
thanks
you need to use double quotes in order to get the value of the variable,
$query = "SELECT
people_fullname
FROM
people
WHERE
people_id = $people_id";
in php, let's say $a = 5,
echo 'a is $a'; // will result: a is $s
echo "a is $a"; // will result: a is 5
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
single quotes do not have variable substitution - double quotes is what you want if you want to replace $var with a value