This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I'm doing a little ajax question-result system. When user types something into the textarea, the result is automatically searched and outputted.
Problem is that every time user types the question that contains "" or '' - the search is unsuccessful. Is there any way I can add backslash to "" or '' inside the string, so it'd be ignored?
Or is there any filter that ignores the "" or ''?
I need the question to be searched with quotes, because questions in database contains them.
Here's the code:
$q = $_POST['q'];
// for every " or ' in $q add \ before it
$results = array();
$result = array();
$count = 0;
$stmt = $dbh->prepare("SELECT result FROM quest WHERE quest LIKE '".$q."%'");
if($stmt->execute()){
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
$count= $stmt->rowCount();
}
if($result != NULL){
foreach($result as $part){
foreach($part as $item){
$results[] = $item;
}
}
echo htmlentities($results[0], ENT_QUOTES, "UTF-8");
}
You are not using prepared statements correctly, and that's why you are having this issue. If you use prepared statements correctly, they solve this issue for you. The docs for this are actually pretty good.
http://php.net/manual/en/pdo.prepared-statements.php
EDIT: Please take the time to learn how to use them correctly. If not, your code is susceptible to SQL injection.
Try using addslashes() Function
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:
How to avoid code repetition with PHP SQL prepared statements?
(2 answers)
Closed 2 years ago.
I'm trying to make a database for users to publish scripts for a game. Every single time I've had an issue using query and got it working one way or another. This time, I decided to make it a little easier to format the string for the query. Its not working. Heres my code:
function getSQLOperation($Data){
$returning = "INSERT INTO `ScriptDatabase`";
$keys = "(";
$values = ") VALUES (";
foreach ($Data as $Key => $Value){
$keys = $keys."`".$Key."`, ";
$values = $values."'".$Value."',";
}
return $returning.$keys.$values.")";
}
$values = array();
$values['Visibility'] = "Public";
$values['Name'] = "NameOfScript";
$values['Publisher'] = "UserID";
$values['Genres'] = "";
$values['PublishDate'] = Date('m-d-Y');
$values['Updated'] = $values['PublishDate'];
$values['Version'] = "1.0";
$values['Description'] = "None for now";
$values['Likes'] = "0";
$values['Dislikes'] = "0";
$values['Downloads'] = "0";
$operation = getSQLOperation($values);
mySQL table structure:
Anything I'm doing wrong here?
MySQL doesn't allow trailing commas in queries, but your query is generated as:
INSERT INTO `foo`(`bar`, `baz`,) VALUES ('x','y',)
Of note, there are much better ways to work with MySQL. Check out PDO, especially prepared statements.
I mean it. Your query is vulnerable to SQL Injection attack and that's serious.
This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
I searched the Internet for some Solutions but none of it works and I can't find out why. I'm new to PHP and MYSQL/MyAdmin so I really don't understand what I did wrong.
I've already tried several commands and "while $row = $result->fetch_array()" and stuff like that.
$Word = "SELECT Word FROM RandWord WHERE Number = '$Number'";
$Word = mysqli_query($data, $Word);
echo $Word;
$Amount = count($Word);
I want it to Output the "Count($Word);" for me, but it can't even echo because it can not be converted into a string. I want to see the word and use it.
You need to actually fetch the results first, before you can use it. You are also vulnerable to SQL injection attacks, so use a prepared statement instead.
In your code $Word is a result-object, which holds information - but you need to use a fetching method to retrieve the data first. count() in PHP is only usable on arrays (or on objects, but not that object which you get from mysqli_query()).
$query = "SELECT Word FROM RandWord WHERE Number = ?";
$stmt = $data->prepare($query);
$stmt->bind_param("s", $Number);
$stmt->execute();
$stmt->bind_result($word);
while ($stmt->fetch()) {
echo $word;
}
$stmt->close();
If you want it to be a count of each word, you have to run a query using the MySQL function COUNT() instead.
$query = "SELECT Word, COUNT(Word) as cnt FROM RandWord WHERE Number = ? GROUP BY Word";
$stmt = $data->prepare($query);
$stmt->bind_param("s", $Number);
$stmt->execute();
$stmt->bind_result($word, $count);
while ($stmt->fetch()) {
echo $word." has count ".$count;
}
$stmt->close();
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
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to print exact sql query in zend framework ?
In zend profiler, I can only either print the query with question markers (getQuery) or print the parameter array (getQueryParams).
Is there a way to replace all question markers, and print the real sql query?
Thanks!
Something like that should work:
$profile = $this->getQueryProfile($queryId);
$query = $profile->getQuery();
$params = $profile->getQueryParams();
foreach ($params as $par) {
$query = preg_replace('/\\?/', "'" . $par . "'", $query, 1);
}
The framework uses prepared statements so actually this is the real query - in reality its send to the database which parses it and then the params are binded to it and executed.
You can use the __toString() method.
$dbTable = new Application_Model_DbTable_TradeshowBooking();
$select = $dbTable->select();
$select->setIntegrityCheck(false);
$select->where('ends_on + INTERVAL 4 WEEK > ? ', $requestParams['ends_on']);
Zend_Registry::get('logger')->log($select->__toString(), Zend_Log::INFO);