Why the sql query do not execute? - php

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)?

Related

In a mysql transaction, can $pdo handle be used for multiple queries or just once?

I want to begin a transaction with multiple queries in MySQL and through self-learning, I write my code like:
$pdo = new PDO('mysql:host=localhost;dbname=project', '', '', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
));
$pdo->beginTransaction();
try {
// First Query
$sql = "SELECT * FROM table1 WHERE table1.id = 1";
$stmt = $pdo->prepare($sql);
$stmt->execute();
if ($row = $stmt->fetch()) {
// There should be only one row so I used if
}
else {
}
// Second Query
$sql2 = "SELECT * FROM table2 WHERE table2.id = 1";
$stmt2 = $pdo->prepare($sql2);
$stmt2->execute();
if ($row = $stmt2->fetch()) {
}
else {
}
$pdo->commit();
echo "OK!";
}
catch(Exception $e) {
echo $e->getMessage();
$pdo->rollBack();
}
So in my code I used the same $pdo twice like
$stmt = $pdo->prepare($sql);
$stmt2 = $pdo->prepare($sql2);
and then
$pdo->commit();
When it is just one stmt the code will show the database data fine.
I haven't successfully tested it since there are syntax errors in other files that prevent this from running. I'm very new to PDO, so could anyone tell me if this is fine to run? Thanks!
Example (PDO) using '?'
<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>
Looking to the example you can see your mistakes.
first:
$sql = "SELECT * FROM table1 WHERE table1.id = ?";
second:
$stmt = $pdo->prepare($sql);
for($id=1;$id<3;$id++){
$stmt->execute($id);
$result=$stmt->fetchAll();
}
Sorry for my English but it's not my mother tongue.

getting error for mysql when i am using if else in there

getting error for mysql when i am using if else in there. i dont know what should i do and when i am using duplicate condition to update then it not woring i am not be able to find where is error
this is the error which is i am getting.
ERROR:SQLSTATE[HY093]: Invalid parameter number: parameter was not
defined
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt=$conn->prepare("SELECT uniqueid FROM hotelcarttemp WHERE uniqueid=:uniqueid");
$stmt->execute(array(':uniqueid'=>$uniqueid));
$count=$stmt1->rowCount();
echo "count-".$count;
if($count>0)
{
$sql = "UPDATE hotelcarttemp SET `hotelname`='".$hotelname."',`roomtype`='".$roomtype."',`checkin`='".$checkin."',`checkout`='".$checkout."',`Country`='".$Country."',`Destination`='".$Destination."',`price`='".$price."' WHERE uniqueid='".$uniqueid."'";
echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
else
{
$sql = "INSERT INTO hotelcarttemp (timestamp, packageid, uniqueid, hotelname, roomtype, checkin, checkout, Country, Destination, hoteldetail, price)
VALUES ('"
.$timestamp."','"
.$packageid."','"
.$uniqueid."','"
.$hotelname."','"
.$roomtype."','"
.$checkin."','"
.$checkout."','"
.$Country."','"
.$Destination."','"
.addslashes($hoteldetail)."','"
.$price."'
)";
// echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
}
catch(PDOException $e) {
echo 'ERROR:' . $e->getMessage();
} here
Your SELECT query where condition is WHERE uniqueid=:uniqueid
And you are binding username to it
$stmt->execute(array(':username'=>$uniqueid));//:username invalid parameter
Change this to
$stmt->execute(array(':uniqueid'=>$uniqueid));

SQL UPDATE query executes correctly via MySQL Workbench but not via PHP

I have the following SQL query:
UPDATE uploads SET UserName='Test2', UserEmail='Test2', UploadCount='4'
WHERE Country = 'Algeria'
When I run this query via MySQL workbench it executes fine.
I am trying to run this via a website / PHP however, and am attempting to execute the query in the following way:
$sql = "UPDATE uploads SET UserName='$user_data[name]', UserEmail='$user_data[email]', UploadCount='$user_data[FilesUploaded]' WHERE Country = '$country'";
echo $sql;
try
{
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare($sql);
$stmt->execute();
# Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
The SQL query is being built via variables here, however I copy / pasted the echo of $sql into workbench to check that there were no syntax errors creeping in, the echo of $sql is what I pasted above.
When I run it via the web application, I get 0 row affected and the UPDATE is not made, where am I going wrong?
Thank you
UPDATE: A new paramatarized version of the PDO:
$sql = "UPDATE uploads SET ";
$sql .="UserName = :name,
UserEmail = :email,
UploadCount = :FilesUploaded";
$sql .=" WHERE Country = '$country'";
try
{
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":name", $user_data['name']);
$stmt->bindParam(":email", $user_data['email']);
$stmt->bindParam(":FilesUploaded", $user_data['FilesUploaded']);
$stmt->execute();
# Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
It looks like you're trying to insert information from an array while it's in quotes. Try this:
$sql = "UPDATE uploads SET UserName='".$user_data['name']."', UserEmail='".$user_data['email']."', UploadCount='".$user_data['FilesUploaded']."' WHERE Country = '$country'";

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.

Select data from database and update it PHP/PDO

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() .'}}';
}
?>

Categories