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.
Related
I have a PHP variable $col with a column name. I want to create a query with PDO, that selects the value of that column. I know how to use bindValue(), and tried the following:
$db = new PDO('mysql:host='. $db_host . ';dbname=' . $db_name . ';charset=utf8', $db_user, $db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function get_user($id, $column){
$sql = "
SELECT :col
FROM users
WHERE `id` = :id;";
try {
$st = $db->prepare($sql);
$st->bindValue('col', $column, PDO::PARAM_STR);
$st->bindValue(':id', $id, PDO::PARAM_INT);
$st->execute();
$result = $st->fetch();
return $result;
} catch (PDOException $e) {
echo "Database query exception: " . $e->getMessage();
return false;
}
}
That results in the following exception: Database query exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column ''name'' in 'field list' for $col = 'name'. Of course, the column name does exist.
It works well on WHERE = :value, but I can not get it working for a column. How to achieve this?
Addition: I did found the function bindColumn(), but I think that does the opposite, binding the column name to a PHP variable instead of binding a variable to the column.
You can use an array of allowed column names to sanitize the query.
$allowed_columns = array('name', 'type1',etc);//Array of allowed columns to sanatise query
Then check if column name is in array.
if (in_array($column, $allowed_columns)){
$result= get_user($id, $column);
}
function get_user($id, $column){
$sql = "
SELECT $column
FROM users
WHERE `id` = :id;";
try {
$st = $db->prepare($sql);
$st->bindValue(':id', $id, PDO::PARAM_INT);
$st->execute();
$result = $st->fetch();
return $result;
} catch (PDOException $e) {
echo "Database query exception: " . $e->getMessage();
return false;
}
}
I would use array_intersect something like a sanitizing function that would extract only the allowed fields. Example:
function get_fields_allowed($input_fields,$allowed){
$input_fields=explode(",",$input_fields);
$allowed=explode(",",$allowed);
return array_intersect($allowed,$input_fields);
}
$select_fields=$_POST["fields"]; //example: "id,name,email"
$fields=get_fields_allowed ($select_fields, "id,name" ) ;
So you then use the $fields as in:
$sql="Select $fields FROM [table] WHERE id=:id etc...";
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);
?>
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);
I need to make a PHP code that gets data from server, updates it and echos that updated data to user. I am beginner with PHP so I have no idea how to do this. This is the code I have have now.
So how do I change the code to make it update data ?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
one idea is to create a different database connection file consisting of a pdo connection and reuse it in your application. on how to do that.
in database.php you can do it like
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
and everywhere you want to use the connection you can do
require_once 'Database.php';
and some of the sample CRUD (Create, Read, Update, Delete) using PDO are.
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
you should also study about named and unnamed placeholders, to escape SQL injections etc. you can read more about PDO with a very easy to understand tutorial by nettuts here
hope this helps you.
Try this. I think it is along the lines of what you are looking for:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = #mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( #mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
This code is what i have tried to process the query, either delete or insert do not have affect.
The id is correct and conn.php is correct .
I just copy the sql query to phpmyadmin to test and it works.
And i put a echo "test"; between try{} it echo too.
Thank you
<?
include("../connection/conn.php");
session_start();
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// list out the pervious create list
//$id=$_GET['id'];
$id=3;
try{
$sql = 'INSERT INTO delete_list SELECT * FROM list WHERE ListID=?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
}
try{
$sql = 'INSERT INTO delete_user_list SELECT * FROM user_list WHERE ListID=?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
}
try{
$sql = 'INSERT INTO delete_require_attributes SELECT * FROM require_attributes WHERE ListID=?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
}
try{
$sql = 'INSERT INTO delete_subscriber SELECT * FROM subscriber WHERE ListID=?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
$count=$stmt->rowCount();
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
}
try{
$sql = 'INSERT INTO delete_list_sub SELECT * FROM list_sub WHERE ListID=?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
}
try{
$sql = 'DELETE FROM list WHERE ListID = ?';
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
}
echo "The list has been deleted.".$count." subscribers has been removed. <a href='view.php'> Back</a>";
?>
i added
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
and error is
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ListID' in 'where clause' Back
It doesn't work because in order for variables to be interpolated you need to use double quotes (") not single quotes. Single quotes makes it literally pass "$id" instead of the value.
But since you're using PDO you should be using prepared statements! Like this:
$sql = 'INSERT INTO delete_list SELECT * FROM list WHERE ListID=?'
$stmt = $conn->prepare($sql)
$stmt->execute(array($id));
The value of $id replaces the ?
EDIT: fixed the parameter
using single quotes in php may be the problem:
$sql = 'INSERT INTO delete_user_list SELECT * FROM user_list WHERE ListID=$id';
here, $id won't be resolved by php interpreter because of single quote which is 'raw string'
if you want $id to be resolved, use " (double quote)
$sql = "INSERT INTO delete_user_list SELECT * FROM user_list WHERE ListID=$id";
or use parameterized statements (preferred & much safer)
$sql = "INSERT INTO delete_user_list SELECT * FROM user_list WHERE ListID=?";
$stmt = $conn->prepare($sql);
$stmt->execute($id);
Which of the queries does not get executed? Can you check whether there is a connection at all (meaning are your credentials correct)?