PDO escape & in query - php

I'm using PDO for my querys and try to escape some '&' since they make the request invalid. I already tried with mysql_real_escape_string and pdo quote... both didn't escaped the '&'. My values are for example "James & Jack".
As Connector:
$this->connect = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
As Query:
function check_exist($query,$parameter)
{
try
{
$this->connect->prepare($query);
$this->connect->bindParam(':parameter', $parameter, PDO::PARAM_STR);
$this->connect->execute();
return $this->connect->fetchColumn();
unset ($query);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Finaly the Call to action
$db = new database;
$db->connect('framework','localhost','root','');
$result = $db->check_exist('SELECT COUNT(*) FROM cat_merge WHERE cat=:parameter',$cat);

Try using prepared statements this way:
<?php
// Connect to the database
$db = new PDO('mysql:host=127.0.0.1;dbname=DB_NAME_HERE', 'username', 'password');
// Don't emulate prepared statements, use the real ones
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// Prepare the query
$query = $db->prepare('SELECT * FROM foo WHERE id = ?');
// Execute the query
$query->execute($_GET['id']);
// Get the result as an associative array
$result = $query->fetchAll(PDO::FETCH_ASSOC);
// Output the result
print_r($result);
?>

Related

How can I convert this mysqli to PDO?

<?php
require_once('dbconfig.php');
global $con;
$query = $con->prepare("SELECT * FROM userinfo order by id DESC");
$query->execute();
mysqli_stmt_bind_result($query, $id, $name, $username, $password);
You should use ->bindColumn Manual
See also This answer.
Best Practise: Do not use SELECT * instead define each column you need to grab from the table.
Do not globalise your connection variable. This is a security risk as well as adding bloat and should be unneeded on your code.
Because it is a static statement you can use ->query rather than prepare, as nothing needs to be prepared.
Solution:
$query = $con->query("SELECT id,name,username,password FROM userinfo ORDER BY id DESC");
try {
$query->execute();
$query->bindColumn(1, $id);
$query->bindColumn(2, $name);
$query->bindColumn(3, $username);
$query->bindColumn(4, $password);
}
catch (PDOException $ex) {
error_log(print_r($ex,true);
}
Alternatively:
A nice feature of PDO::query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement. From the manual
foreach ($conn->query('SELECT id,name,username,password FROM userinfo ORDER BY id DESC') as $row) {
print $row['id'] . " is the ID\n";
print $row['name'] . " is the Name\n";
print $row['username'] . " is the Username\n";
}
See Also:
Mzea Has some good hints on their answer, you should use their $options settings as well as using their suggested utf8mb4 connection character set.
And their suggestion for using ->fetchAll is also completely valid too.
Try this
$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
$pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
error_log($e->getMessage());
exit('Something weird happened'); //something a user can understand
}
$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);

Select returning empty query

I'm trying to select data where by acc_id
What I get in my localhost: []
However, when I set a specific acc_id i get the correct row is there something in my syntax?
<?php
header('Access-Control-Allow-Origin: *');
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'ringabell';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
$data = array();
// Attempt to query database table and retrieve data
try {
$acc_id = $pdo->prepare('SELECT acc_id FROM account_info');
$stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = "$acc_id"');
$stmt->execute([$acc_id]);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
It seems like you want to use the prepared statement but instead executing your query instantly. If you want to bind the value to your query use something like this:
$acc_id = // get the $acc_id value from somewhere you want
$stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = ?');
$stmt->execute([$acc_id]);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
// Assign each row of data to associative array
$data[] = $row;
}
Example with using a placeholder
Instead of executing your statement with the array of params, you could also use the bindValue() or the bindParam() method:
$stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = :acc_id');
$stmt->bindValue(':acc_id', $acc_id);
$stmt->execute();
// everything else works as previous
The difference between these two methods is written in docs:
bindValue():
Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement.
bindParam():
Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

How to wite PHP code with the following SQL query?

I am trying to query out a result, it works in SQL query, but I'm trying to get the result using PHP
SELECT prs_amtdb FROM `prs` WHERE prs_amtcrck = 0
Using mysqli
Note: Make sure you bind your value. mysqli does not automatically
secure your query
$connection= mysqli_connect($host, $user, $password, $database);
$query="SELECT prs_amtdb FROM prs WHERE prs_amtcrck = 0";
$result= mysqli_query($connection, $query);//$connection is your database
//connection
//fetch the result
while($row= mysqli_fetch_array($result)){
echo $row['column_name'].'<br/>';
}
Using PDO:
$query = $db->query("SELECT `prs_amtdb` FROM prs WHERE `prs_amtcrck` = 0");
$results = $query->fetchAll();
foreach($results as $result) {
echo $result;
}
http://php.net/manual/en/pdo.query.php
If you have user input that you're using in your query you should always use prepared statements eg:
$query = $db->prepare("SELECT `prs_amtdb` FROM prs WHERE `prs_amtcrck` = :atmcrck");
$query->bindParam(':atmcrck', 0); // 0 will be the user input
$query->execute();
$results = $query->fetchAll();
foreach($results as $result) {
echo $result;
}
Make sure you have a database connection setup in PDO:
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
die($e->getMessage());
}
http://php.net/manual/en/pdo.connections.php

PDO fetchAll() returns an empty array

in my code im trying to get data from my db with PDO and bind params but i keep on getting empty array, this is my code :
try{
$pdo =new PDO('mysql:host=localhost;dbname=***', '***','***');
$pdo->setAttribute(pdo::ATTR_ERRMODE,
pdo:: ERRMODE_EXCEPTION);
$pdo->query('set names "utf8"');
}
catch (PDOException $e) {
die('error connectin database');
}
$table = 'products';
$column = 'id';
$niddle = '70';
$sql = "SELECT * FROM `{$table}` WHERE ";
$sql .= ":column LIKE :niddle";
$pre = $pdo->prepare($sql);
$pre->bindParam(':column', $column ,PDO::PARAM_STR);
$pre->bindParam(':niddle', $niddle, PDO::PARAM_STR);
$result = $pre->setFetchMode(PDO::FETCH_ASSOC);
$pre->execute();
print_r($pre->fetchAll());
there is no exeption thrown, what could be the problem?
You should not bind the column name as a prepared statement parameter string as it will quote the column name. Do like you do with the table name just use it-- after whitelisting it.

PDO Bind Param Trouble

I'm trying to convert my codes to PDO from mysql_query, and starting with this function
function label_for_field($field_name, $table_name) {
$table = array();
// Bind variables to parameters
$param_array = array(':bundle' => $table_name, ':field_name' => $field_name);
// Prepare Query Statement
$query = "SELECT data FROM field_config_instance WHERE bundle = :bundle AND field_name = :field_name";
$STH = $DBH -> prepare($query);
// Execute
$STH -> execute($param_array);
// Set the fetch mode
$STH -> setFetchMode(PDO::FETCH_OBJ);
while ($row = $STH -> fetch()) {
$info = unserialize($row -> data);
$table[] = $info['label'];
}
return $table[0];
}
and I'm trying out just output it to see if it works
include_once ("includes/connect.php");
include ("includes/functions.php");
echo label_for_field("field_account_number", "account_table");
And here's the connect.php
// Include Constants
require_once ("constants.php");
//Establish Connection
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch (PDOException $e) {
echo $e -> getMessage();
}
I don't know if it's because I'm binding the parameters wrong, it just gave me an server error page
"Server error. The website encountered an error while retrieving ......."
Thanks in advance
You need to set the PDO error mode to produce exceptions before you can catch them.
In your connect.php:
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Then you can have a similar try/catch statement in your function to that of your connection file, and use it to show the error in your development environment.
Try this instead to see if you get valid objects returned from the query.
// Prepare Query Statement
$query = "SELECT data FROM field_config_instance WHERE bundle = :bundle AND field_name = :field_name";
$STH = $DBH -> prepare($query);
$STH->bindValue(":bundle", $table_name);
$STH->bindValue(":field_name", $field_name);
$STH->execute();
$STH->setFetchMode (PDO::FETCH_OBJ);
$result = $STH->fetchAll();
var_dump($result);

Categories