PDO prepare stops script without giving error - php

I looked all over for solutions but couldn't find any. I checked my code and can't seem to find any errors with it.
try
{
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
$handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
$sendData = $handle->prepare("INSERT INTO 'posts' (body, user, comments, likes, username, datetime) VALUES(:body, :userid, 'none', 'none', :username, :datetime)");
$sendData->bindParam(':body',$this->body);
$sendData->bindParam(':userid',$this->userID);
$sendData->bindParam(':username',$this->username);
$sendData->bindParam(':datetime',$this->datetime);
$sendData->execute();
I determined that the code stops before it even reaches the "bindParam" part. It stops right after the prepare call.
EDIT: As it turns out the error was in the $handle part. I declared handle elsewhere and didn't use "global" to add it inside this function. I feel so stupid.

Try:
try {
$db = new PDO('mysql:host=localhost;dbname=DATEBASE;charset=utf8', 'USER', 'PASSWORD');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex) {
echo "something";
die();
}
$body = $_POST['body'];
$userID = $_POST['userID'];
$username = $_POST['username'];
$datetime = $_POST['datetime'];
$none = "none";
$sendData = $sb->prepare("INSERT INTO `posts` (body, user, comments, likes, username, datetime) VALUES(:body, :userid, :none, :none, :username, :datetime)");
$sendData->bindValue(':body', $body);
$sendData->bindValue(':none', $none);
$sendData->bindValue(':userid', $userID);
$sendData->bindValue(':username', $username);
$sendData->bidnValue(':datetime', $datetime);
$sendData->execute();
Edited:
`posts` instead 'posts'

Related

Pdo Transaction does not roll back when while DELETE did not execute

I am building am app that should execute multiple queries that involve insert, delete and update commands. There is no syntax error but I discovered that the delete command did not delete entry but the insert command inserted row and the action did not rollback. If the delete action did not happen, insert and others should be cancelled is the desired result.
<?
try {
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->beginTransaction();
$D = 2;
$Dn = 3;
$dumpi = $pdo->prepare("INSERT INTO `dumpi` .... SELECT .... FROM .... ");
$dumpi->execute();
$matchi = $pdo->prepare("DELETE FROM `marchi` WHERE `id`=....");
$matchi->execute();
$usri = $pdo->prepare("UPDATE `users` SET `status`='0' WHERE `id`='$Dn' ");
$usri->execute();
$donati = $pdo->prepare("UPDATE `dnsn` SET `status`='d' WHERE `id`='$D' ");
$donati->execute();
$donatidel = $pdo->prepare("UPDATE `dnsn` SET `status`='d',`deleted_by`='m' WHERE `dn`='$Dn' AND `status`='1' ");
$donatidel->execute();
$navwal = $pdo->prepare("UPDATE `wlt` SET `status`='0' WHERE `user`='$Dn'");
$navwal->execute();
$navwalt = $pdo->prepare("UPDATE `wlt` SET `status`='0' WHERE `dn`='$Dn' ");
$navwalt->execute();
// dont let te $D and Dn confuse you, its not the one causing any error
$pdo->commit();
// echo 'it works';
} catch (PDOException $e) {
$pdo->rollBack();
echo "Failed: " . $e->getMessage();
}
?>
The code ended here...
my connection to Db is of this script here...(just added for ref. php7)
$pdoOptions = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => true);
try {
$pdo = new PDO(
"mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, //DSN
MYSQL_USER, //Username
MYSQL_PASSWORD, //Password
$pdoOptions //Options
);} catch (Exception $e) {
// design this well to make sense
die(
// conmment out in launch
$e->getMessage())
);
}
Well, if a query do not find any data, it is not an error.
If it's important for you that the delete query should necessarily find the the record to delete, then you have to verify that manually and than throw an exception.
$stmt = $pdo->prepare("DELETE FROM `marchi` WHERE `id`=?");
$stmt->execute([....]);
if (!$stmt->rowCount())
{
throw new Exception("Delete didn't find a record")
}
And then catch Exception, not PDOException.
Note that for some reason you aren't using prepared statements while you should

Inserting time into MySQL Database with PDO

I'm working on a Pastebin clone kind of a thing (from scratch, not literally cloning pastebin, just making an alternative) and I've ran into an issue inserting time into the database.
<?php
require 'connection.php';
$paste = $_POST['paste'];
$title = $_POST['title'];
//$sql = "INSERT INTO pasteinfo (title, paste) VALUES (:title, :paste)";
$stmt = $con->prepare("INSERT INTO pasteinfo (title, paste) VALUES (:title, :paste)");
echo "hi";
$stmt->bindParam(':paste', $paste);
$stmt->bindParam(':title', $title);
$stmt->execute();
echo "Pasted!";
$pastetime = new DateTime();
$timeQuery = $con->prepare("INSERT INTO pasteinfo (pastetime) VALUES (:pastetime)");
$time->bindParam(':pastetime', $pastetime);
$con->exec($timeQuery);
//$con = null;
?>
So that's insert.php. I'm hoping that when a user 'pastes' their paste it will record time, and then on my viewpaste.php it will display the title, paste, and time the paste was made.
What's wrong with it?
By the way, just ignore the little echo "hi"; thrown in there. It's helped me troubleshoot a lot and continues to do so.
connection.php source:
<?php
try {
$con = new PDO('mysql:host=;dbname=;charset=utf8mb4','','');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $ex){
echo $ex->getMessage();return false;
}
function retrieve($query,$input) {
global $con;
$stmt = $con->prepare($query);
$stmt->execute($input);
$stmt->setFetchMode(PDO::FETCH_OBJ);
return $stmt;
}
#Drew:
<?php
require 'connection.php';
$paste = $_POST['paste'];
$title = $_POST['title'];
$timeQuery = "SELECT NOW()";
//$sql = "INSERT INTO pasteinfo (title, paste) VALUES (:title, :paste)";
$stmt = $con->prepare("INSERT INTO pasteinfo (title, paste, pastetime) VALUES (:title, :paste, :pastetime)");
echo "hi";
$stmt->bindParam(':paste', $paste);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':pastetime', $timeQuery);
$stmt->execute();
echo "Pasted!";
//$timeQuery = $con->prepare("INSERT pasteinfo(pastetime) SELECT NOW()");
//$timeQuery->execute();
//$con = null;
?>
Schema and end-state after running script once:
Schema:
drop table if exists pasteinfo2;
CREATE TABLE pasteinfo2
( ai INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(200) NOT NULL,
paste TEXT NOT NULL,
pastetime DATETIME NOT NULL
);
PHP script:
<?php
// turn on error reporting, or wonder why nothing is happening at times
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Begin Vault
// credentials from a secure Vault, not hard-coded (so the below is just for testing)
$servername="localhost";
$dbname="so_gibberish";
$username="nate";
$password="cannonBall##)x";
// End Vault
try {
$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$paste="Four score and seven years ago, our fore....";
$title="Gettysburg Address";
$stmt = $pdo->prepare("INSERT INTO pasteinfo2 (title, paste, pastetime) VALUES (:title, :paste, now())");
$stmt->bindParam(':paste', $paste);
$stmt->bindParam(':title', $title);
$stmt->execute();
echo "Yo I am here<br>";
} catch (PDOException $e) {
echo 'pdo problemo: ' . $e->getMessage(); // dev not production code
exit();
}
?>

PHP PDO query on MySQL does not return as expected

I've been working on an iOS web service using PHP, but I'm not having very much luck. I'm attempting to safely query the database and select the id of the user when the name and password match. Unfortunatly, nothing is showing up on the page. I would assume that means the query went wrong somewhere. I've attempted using static values, but to no avail. Any ideas?
P.S. I'm positive the values are correct.
P.P.S. Yes, I know, encrypt. For the simplicity, I'm not bothering.
error_reporting(E_ALL);
ini_set('display errors', 1);
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row = $STH->fetch(PDO::FETCH_ASSOC);
print '<pre>';
print_r($row);
Try it ,
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo /*here*/ $e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row =$STH->fetch(PDO::FETCH_ASSOC)
print '<pre>';
print_r($row);

Delete MySQL PHP

mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$insert="INSERT INTO inactive (ID_No, User_Password, First_Name, Last_Name, Email, Contact_Number)
VALUES('". $ID_No ."','". $UserPassword ."','". $FirstName ."','". $LastName ."','". $Email ."','". $ContactNumber ."')";
$result=mysql_query($insert);
$sql="DELETE FROM users WHERE ID_No = '$ID_No'";
$result2=mysql_query($sql);
if($result && $result2){
echo"Successful!";
} else {
echo "&nbsp Error";
}
Hi guys I have been stuck in delete function of MySQL, I have tried searching the net but when I ran my code it always goes to the else part which means there is an error, the insert is already okay but the delete is not.
PHP variables are allowed in double quotes. Hence try this,
$sql="DELETE FROM users WHERE ID_No = $ID_No";
Your first query was not properly escaped. Rewrite like
$insert="INSERT INTO inactive (`ID_No`, `User_Password`, `First_Name`, `Last_Name`, `Email`, `Contact_Number`)
VALUES('$ID_No','$UserPassword','$FirstName','$LastName','$Email','$ContactNumber')";
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
First, use PDO.
Make your connection Database like this:
function connectToDB(){
$host='localhost';
try {
$user = 'username';
$pass = 'password';
$bdd = 'databaseName';
$dns = 'mysql:host='.$host.';dbname='.$bdd.'';
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
return $connexion = new PDO($dns, $user, $pass, $options);
}catch ( Exception $e ) {
echo "Fail to connect: ", $e->getMessage();
die();
}
}
To delete something, here is an example:
function deleteUserWithId($ID_No){
$connexion = connectToDB();
try{
$connexion->exec('DELETE FROM users WHERE ID_No = '.$ID_No);
}catch(Exception $e){
echo "Error: ".$e->getMessage();
}
}
To insert something:
function addInactiveUser($UserPassword,$FirstName ,$LastName ,$Email,$ContactNumber){
$connexion = connectToDB();
$insert = $connexion->prepare('INSERT INTO inactive VALUES(:ID_No,
:User_Password,
:First_Name,
:Last_Name,
:Email,
:Contact_Number
)');
try {
// executing the request
$success = $insert->execute(array(
'ID_No'=>'',
'User_Password'=>$UserPassword,
'First_Name'=>$FirstName ,
'Last_Name'=>$LastName ,
'Email'=>$Email,
'Contact_Number'=>$ContactNumber
));
if($success)
// OK
else
// KO
}
catch (Exception $e){
echo "Error: ".$e->getMessage();
}
}
To make a select:
// If you want to display X user per pages for example
function getAllInactiveUsers($page, $numberInactiveUserPerPage){
$connexion = connectToDB();
$firstInactiveUser = ($page - 1) * $numberInactiveUserPerPage;
$selectAllInactiveUsers = $connexion->prepare('SELECT * FROM inactive ORDER BY ID_No DESC LIMIT '.$firstInactiveUser.','.$numberInactiveUserPerPage);
return $selectAllInactiveUsers ;
}
To get the results of this methods, just do something like this:
$inactiveUsers= getAllInactiveUsers(1,15); // for page 1, display 15 users
$inactiveUsers->execute();
while($row = $inactiveUsers->fetch(PDO::FETCH_OBJ)){
$id = $row->ID_No;
$first_name = $row->First_Name;
// etc...
}
Hope that's help :)
I am not sure if this helps you, but as an alternative you could delete the last entry in the table:
$delQ = mysql_query("SELECT * FROM ph ORDER BY id DESC LIMIT 1" );
while(( $ar = mysql_fetch_array($delQ)) !== false){
mysql_query("DELETE FROM ph WHERE id= $ar[id]");
}

How to handle PDO exceptions [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 7 years ago.
I'm trying to work with PDO class on php but I have some trouble to find the right way to handle errors, I've wrote this code:
<?php
// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type
$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";
try {
$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";
$statement = $connection->prepare ($sql);
$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);
$status = $statement->execute ();
} catch (PDOException $e) {
print $e->getMessage ();
}
print $status; // it returns a null value, and no errors are reported
?>
this portion of code doesn't report errors, but it simply doesn't work, the var $status at the bottom, return a null value.
can someone help me to find where I'm wrong?
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
on the PDO object?
You can add the attribute one time while you connect you mysql.
function connect($dsn, $user, $password){
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
Thanks

Categories