I tried to use TRIM() in a PDO SELECT query and got a syntax error message as "Syntax error or access violation: 1064 You have an error in your SQL syntax;". What should I do to correct this error?
DB:
tblrecord (firstname, lastname, score)
PHP:
$firstname = trim('Mary');
$lastname = trim('Lamb');
$sql = "SELECT * FROM tblrecord WHERE TRIM(firstname) AS firstname = ? AND TRIM(lastname) AS lastname = ?";
$stmt = $connection->prepare($sql);
$stmt->execute( array($firstname, $lastname) );
Dont use alias on the WHERE
$sql = "SELECT * FROM tblrecord WHERE TRIM(firstname) = ? AND TRIM(lastname) = ?";
Related
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.
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.'%');
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
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I currently have a Get varible
$name = $_GET['user'];
and I am trying to add it to my sql statement like so:
$sql = "SELECT * FROM uc_users WHERE user_name = ". $name;
and run
$result = $pdo -> query($sql);
I get an invalid column name. But that doesn't make sense because if I manually put the request like so
$sql = "SELECT * FROM uc_users WHERE user_name = 'jeff'";
I get the column data, just not when I enter it as a get variable. What am I doing wrong. I am relatively new to pdo.
Update:
Now I have the following:
$name = $_GET['user'];
and
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
//run the query and save the data to the $bio variable
$result = $pdo -> query($sql);
$result->bindParam( ":name", $name, PDO::PARAM_STR );
$result->execute();
but I am getting
> 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 ':name' at line
> 1
For your query with the variable to work like the one without the variable, you need to put quotes around the variable, so change your query to this:
$sql = "SELECT * FROM uc_users WHERE user_name = '$name'";
However, this is vulnerable to SQL injection, so what you really want is to use a placeholder, like this:
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
And then prepare it as you have:
$result = $pdo->prepare( $sql );
Next, bind the parameter:
$result->bindParam( ":name", $name, PDO::PARAM_STR );
And lastly, execute it:
$result->execute();
I find this best for my taste while preventing SQL injection:
Edit: As pointed out by #YourCommonSense you should use a safe connection as per these guidelines
// $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = 'SELECT * FROM uc_users WHERE user_name = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
// perhaps you'll need these as well
$count = $result->num_rows;
$row = $result->fetch_assoc();
/* you can also use it for multiple rows results like this
while ($row = $result->fetch_assoc()) {
// code here...
} */
BTW, if you had more parameters e.g.
$sql = 'SELECT * FROM table WHERE id_user = ? AND date = ? AND location = ?'
where first ? is integer and second ? and third ? are string/date/... you would bind them with
$stmt->bind_param('iss', $id_user, $date, $location);
/*
* i - corresponding variable has type integer
* d - corresponding variable has type double
* s - corresponding variable has type string
* b - corresponding variable is a blob and will be sent in packets
*/
Source: php.net
EDIT:
Beware! You cannot concatenate $variables inside bind_param
Instead you concatenate before:
$full_name = $family_name . ' ' . $given_name;
$stmt->bind_param('s', $full_name);
Try this .You didn't put sigle quote against variable.
$sql = "SELECT * FROM uc_users WHERE user_name = '". $name."'";
Note: Try to use Binding method.This is not valid way of fetching data.
$sql = "SELECT * FROM 'uc_users' WHERE user_name = '". $name."' ";
I am trying to change to prepared statements but keep getting the following error:
Warning: PDO::query(): 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 ':fname AND
Here is the code im using:
$street = 'astreet';
$lname = 'alname';
$fname = 'afname';
$list = '1,2,3,4,5';
$var = 'admin';
$db = new PDO("mysql:dbname=customers;host=localhost",$var,$var);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$sql = "SELECT * FROM `table` WHERE `id` in ($list) AND `first_name` LIKE :fname AND `last_name` LIKE :lname AND `street_name` LIKE :street";
$stmt = $db->prepare($sql);
$stmt->execute(array(':street' => $street));
$stmt->execute(array(':fname' => $fname));
$stmt->execute(array(':lname' => $lname));
$result = $db->query($sql);
foreach ($result as $row) {
echo $row['post_code'];
}
if I run the query as normal - not a prepared staement, it works fine - its only when I start adding the :variables to the query I get the error
Is there any code missing/incorrect?
Thanks
$stmt = $db->prepare($sql);
$stmt->execute(array(':street' => $street));
$stmt->execute(array(':fname' => $fname));
$stmt->execute(array(':lname' => $lname));
You're running the same query three times, with a different parameter each time. You need to run the query as so:
$stmt = $db->prepare($sql);
$stmt->execute(array(':street' => $street, ':fname' => $fname, ':lname' => $lname));
And pass all three parameters in one go.
Edited to add:
You can also try binding the parameters explicitly:
$stmt = $db->prepare($sql);
$stmt->bindParam(':street', $street);
$stmt->bindParam(':fname', $fname);
$stmt->bindParam(':lname', $lname);
$stmt->execute();
Or adding them as an array:
$sql = "SELECT * FROM `table` WHERE `id` in ($list) AND `first_name` LIKE ? AND `last_name` LIKE ? AND `street_name` LIKE ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($fname, $lname, $street));
As far as I know you have to escape strings in SQL.
So I would replace
$sql = "SELECT * FROM `table` WHERE `id` in ($list) AND `first_name` LIKE :fname AND `last_name` LIKE :lname AND `street_name` LIKE :street";
by
$sql = "SELECT * FROM `table` WHERE `id` in ($list) AND `first_name` LIKE ':fname' AND `last_name` LIKE ':lname' AND `street_name` LIKE ':street' ";