Insert a PHP variable in a MySql SQL Statement - php

I'm trying to do like this using PHP and MySql PDO:
//PHP Variables
$msg_a = 'Too Little';
$msg_b = 'Score OK';
$sql = "select if(stdScore >= stdRequired, $msg_a, $msg_b) from scores;"
$results = $conn->prepare($Sql);
$results->execute();
AFAIK this should have worked. But I keep getting the following error message:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
How can something like this be done?

$results = $conn->prepare($Sql);
---------------------------------------------^ (capital S)
it should be with a lowercase s
$results = $conn->prepare($sql);
because you have:
$sql = "select if(stdScore >= stdRequired, $msg_a, $msg_b)
from scores";(//semicolon after double quotes)
---^
with a lowercase s ($sql)

Can you try this,
$sql = "select if(stdScore >= stdRequired, $msg_a, $msg_b) from scores";
$results = $conn->prepare($sql);

Have you tried it this way ?
$sql = "select if(stdScore >= stdRequired, "'.$msg_a.'", "'.$msg_b.'") from scores;"

Since you're already using PDO don't do query string interpolation leaving your code vulnerable to sql injections and value escaping problems. Instead use prepared statements properly.
Your code could've looked something like
$msg_a = 'Too Little';
$msg_b = 'Score OK';
// use placeholders in a query string
$sql = "SELECT IF(stdScore >= stdRequired, :msg_a, :msg_b) msg FROM scores";
// prepare the statement
$query = $conn->prepare($sql);
// bind parameters and execute the query
$query->execute(array(':msg_a' => $msg_a, ':msg_b' => $msg_b));
// fetch the resultset
$rows = $query->fetchall(PDO::FETCH_ASSOC);

Related

Prepared statements in Extbase TYPO3 7.6 not working

I want to submit the query as a prepared statement, like below.
$query = $this->createQuery();
$query->getQuerySettings()->usePreparedStatement(TRUE);
$sqlParamList[] = 'test#gamil.com';
$sql = 'SELECT uid FROM table_name WHERE email = ?';
$query->statement($sql, $sqlParamList);
$result = $query->execute();
But I always get errors like below.
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use near '?' at line 1'
Where I am wrong?
You need to parse your $sql to a prepared statement first:
$preparedSql = $this->objectManager->get(\TYPO3\CMS\Core\Database\PreparedStatement::class, $sql, 'table_name');
With $this->objectManager->get() you instantiiate the class PreparedStatement with the arguments $sql and 'table_name'.
This will change your $sql and parse the ? to be used as prepared statement.
Another approach:
$query = $this->createQuery();
$query->getQuerySettings()->usePreparedStatement(TRUE);
$sqlParamList = [
':email' => 'test#gamil.com'
];
$sql = 'SELECT uid FROM table_name WHERE email = :email';
$query->statement($sql, $sqlParamList);
$result = $query->execute();
Cannot test it, just an approach.

php pdo sql query Error : 1064 with LIKE

My PDO query is throwing an error
42000 1064 You have an error in your SQL syntax
$sql = "SELECT * FROM {$this->config->__get('table_medicine')} WHERE patient_id = ? AND medicine LIKE %?%";
$query = $this->dbh->prepare($sql);
$data = array($patient_id, $medicine);
$response = $query->execute($data) or die(implode(" ", $query->errorInfo()));
Can someone see what am I doing wrong?
The % need to be inside the string argument to LIKE. Either use CONCAT() in the SQL:
$sql = "SELECT * FROM {$this->config->__get('table_medicine')}
WHERE patient_id = ? AND medicine LIKE CONCAT('%', ?, '%')";
or do the concatenation in PHP:
$data = array($patient_id, '%'.$medicine.'%');

PDO SQLSTATE[42000] on simple select query

Im just new with programming in OOP, so im writing a function but it gives an error, i think im using PDO wrong, actually i now it for sure, but i dont now how to fix it. This is my code im using currently:
public function takedrugs($soort, $hoeveelheid, $id){
$conn = $this->conn;
$drugsophalen = $conn->prepare('SELECT * FROM gebruikers WHERE id=:id');
$drugsophalen->execute(array(':id' => $id));
$result = $drugsophalen->fetch();
$huidigdrugs = $result[$soort];
if($huidigdrugs >= $hoeveelheid){
//Voldoende drugs dus drugs afnemen
$drugsafnemen = $conn->prepare('UPDATE gebruikers
SET :soort = :soort - :hoeveelheid,
WHERE id = :id');
$drugsafnemen->execute(array(
':soort' => $soort,
':hoeveelheid' => $hoeveelheid,
':id' => $id));
} else {
return false;
}
}
So when i use this function i get an error, its all about the SET :soort = :soort - :hoeveelheid.
This is the error i get:
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near ''Cannabis' =
'Cannabis' - '2000', WHERE id ' at line 2' in
I hope there are some people who now how to fix it since i dont :S
Thanks in advance!
You CANT bind column names SEE Complex Cases in PDO info.
Also as Jason states about lazy binding use bindParam OR bindValue
TRY
$drugsafnemen = $conn->prepare('UPDATE gebruikers
SET $soort = $soort - :hoeveelheid,
WHERE id = :id');
$drugsafnemen->bindParam(':hoeveelheid', $hoeveelheid, PDO::PARAM_INT);
$drugsafnemen->bindParam(':id', $id, PDO::PARAM_INT);
$drugsafnemen->execute();
You have two problems:
First, by using execute() all your values are being treated as a string. This results in the syntax error:
UPDATE gebruikers SET field = 'Cannabis' - '2000' ...
I assume this is not your intention. Instead, use bindParam() so you can define these parameters as integers.
$drugsafnemen->bindParam(':soort', $soort, PDO::PARAM_INT);
Second, you should are setting the column name dynamically (:soort). As such, it too is getting interpolated with $soort, which is probably not your intention.

PDO showing error

I have a query below which I did with mysql_query before and it executed properly.. But using PDO it's showing some error
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1'
This is my code with mysql_query :
$sql1 = "SELECT * FROM product WHERE id IN (";
foreach($_SESSION['cart'] as $id => $value){
$sql1 .= $id.',';
}
$sql1 = substr($sql1, 0, -1) .")";
$query = mysql_query($sql1);
Using PDO without prepare statement.. :
$sql1 = "SELECT * FROM product WHERE id IN (";
foreach($_SESSION['cart'] as $id => $value){
$sql1 .= $id.',';
}
$sql1 = substr($sql1, 0, -1) .")";
$query = $db->query($sql1);
You miss to "add" the string here:
$sql1 = substr($sql1, 0, -1);
$sql1 .= ")";
In the PDO tag (info) you will find the correct procedure for PDO Prepared statements and IN.
The following code uses this method to add unnamed placeholders from your SESSION array
$in = str_repeat('?,', count($_SESSION['cart']) - 1) . '?';
$sql1 = "SELECT * FROM product WHERE id IN ($in)";
$params = $_SESSION['cart'] ;
$stmt = $dbh->prepare($sql1);
$stmt->execute($params);
DEMO

PDO order by throws error

I am confused.
This is working:
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC';
$stmt = $conn->prepare($sql);
$stmt->execute();
This is not:
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD :orderbydateofupload';
$stmt = $conn->prepare($sql);
$stmt->bindValue(':orderbydateofupload', $orderbydateofupload, PDO::PARAM_STR);
$stmt->execute();
I have checked and set $orderbydateofupload by $orderbydateofupload='DESC', so it's definitely not null.
I get an error to the last line ($stmt->execute()):
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''DESC'' at line 1' in /home/gh6534/public_html/query.php:77 Stack trace: #0 /home/gh6534/public_html/query.php(77): PDOStatement->execute() #1 {main} thrown in /home/gh6534/public_html/query.php on line 77
I also tried to use the column as parameter:
$sort = 'DATEOFUPLOAD';
$sql = 'SELECT * FROM TABLE ORDER BY :sort :orderbydateofupload';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':sort', $sort);
$stmt->bindParam(':orderbydateofupload', $orderbydateofupload);
$stmt->execute();
This does not throw an exception, but all items are queried without any sorting. What's wrong?
Try this
$orderbydateofupload = 'ASC'; //Or DESC
if($orderbydateofupload == 'DESC')
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC';
else
$sql = 'SELECT * FROM TABLE'
You can't bind identifiers with PDO because prepared statements can be used only with data, but not with identifiers or syntax keywords.
So, you have to use whitelisting, as shown in the example I posted before
That's why in my own class I use identifier placeholder, which makes whole code into one line (when you need to set the order by field only):
$data = $db->getAll('SELECT * FROM TABLE ORDER BY ?n',$sort);
but with keywords whitelisting is the only choice:
$order = $db->whiteList($_GET['order'],array('ASC','DESC'),'ASC');
$data = $db->getAll("SELECT * FROM table ORDER BY ?n ?p", $sort, $order);

Categories