Want to delete a row from a table using php pdo - php

I want to delete a row from a table using php pdo.I am using the following code,
$dsn = 'mysql:host=127.0.0.1;dbname=as1';
$user = 'root';
$password = '';
try {
// Connect and create the PDO object
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'Database connection failed - ';
echo $e->getMessage();
exit;
}
$sql1="DELETE FROM photo WHERE id=?";
$q1=array($result);
try {
$stmt1 = $pdo->prepare($sql1);
$stmt1->execute($q1);
$stmt1->setFetchMode(PDO::FETCH_BOTH);
$result1= $stmt1->fetchColumn();
}
catch (PDOException $e) {
die("Failed to run query: " . $e->getMessage());
}
But my datas in a table are not deleting ...It shows failed to run query..

You did not provide a value for ?
$stmt1->execute($q); // Where is $q defined?
Should be something like
$q=array(1);
$stmt1->execute($q);

Related

PHP executes sql inside a false condition of IF statement with $_POST

Please help with this difficult to understand bug: php always execute sql update inside IF with $_POST in condition.
When condition is false: the code i) not executes the echo command, but ii) it still executes the sql command
if ($_POST["scanned_set"] != "saved") {
try {
$conn = new PDO("mysql:host=$servername;dbname=abc", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update
$sql = "UPDATE `id_scan` SET `scan_count` = 10 WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
and the strange thing is that, if I try the iF condition with "IF (1 ==2)" then code works well. In other words, it does not execute the sql.
The full code
<html>
<body>
<?php
$servername = "localhost";
$username = "reviinve_vchain";
$password = "";
var_dump($_POST["scanned_set"]);
try {
$conn = new PDO("mysql:host=$servername;dbname=reviinve_vchain", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Retrieve data from db
$sql = "SELECT * FROM `id_scan` WHERE `id` = 1";
foreach ($conn->query($sql) as $row) {
echo "print scan number after retrieving statement ".$row['scan_count'] . "\t";
// print $row['color'] . "\t";
$count_update = $row['scan_count'] + 1;
}
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
if ($_POST["scanned_set"] != "saved") {
try {
$conn = new PDO("mysql:host=$servername;dbname=reviinve_vchain", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update count number to db
echo 'new count number' . $count_update;
$sql = "UPDATE `id_scan` SET `scan_count` = $count_update WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
?>
</body>
</html>
Try scrubbing your request variable first:
$do_update = !(trim(strtolower($_REQUEST["scanned_set"])) == "saved")
if ($do_update) {
try {
$conn = new PDO("mysql:host=$servername;dbname=abc", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update
$sql = "UPDATE `id_scan` SET `scan_count` = 10 WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}

sent last id inserted variable to another page in php [duplicate]

This question already has answers here:
How to get last inserted inserted row id from PDO
(2 answers)
Closed 5 years ago.
in this code i have to insert some value in DB, then i have to take last id inserted in DB and sent it to another page to show the value of that id row. here is my code for insert data in DB :
try {
$con = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql_basic = "INSERT INTO user_basic_info (first_name,last_name,address,profile_pic,resume_file)
VALUES ('$FirstName','$LastName','$Address','$pic_destination','$resume_destination')";
$con->exec($sql_basic);
$last_id = $con->$lastInsertId();
} catch (PDOException $e) {
echo $sql_basic . "<br>" . $e->getMessage() . "<br>";
}
$con = null;
header('Location: DB-Read.php?id=' . $last_id);
in another php page i have to take $last_id and use it. here is my code:
try {
$user_id = $id;
$conn = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT first_name FROM user_basic_info where user_id = ".$user_id);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
echo "this is username: " . $result;
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
header('Location: show-edit.php?id=' . $last_id);
first of all $lastInsertId() not working !!
after that, is my way true to take $last_id from first page ?
lastInsertId is a method of the PDO object. You need to call $conn->lastInsertId();.
Your given syntax $conn->$lastInsertId(); is valid, however, it does not do, what you are expecting. It considers $lastInsertId to be a variable containing the method name to be called. The following example would work as well:
$method_name = 'lastInsertId';
$conn->$method_name();
Be aware that your solution enables anyone to fetch any row of your table. Consider using sessions.
TRY THIS:
use session:
try {
$con = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql_basic = "INSERT INTO user_basic_info (first_name,last_name,address,profile_pic,resume_file)
VALUES ('$FirstName','$LastName','$Address','$pic_destination','$resume_destination')";
$con->exec($sql_basic);
$_SESSION['id'] = $con->lastInsertId(); //it's a method
} catch (PDOException $e) {
echo $sql_basic . "<br>" . $e->getMessage() . "<br>";
$con = null;
header('Location: DB-Read.php?id=' . $last_id);
Now use this code
try {
$user_id = $_SESSION['id'];
$conn = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT first_name FROM user_basic_info where user_id = ".$user_id);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
echo "this is username: " . $result;
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
header('Location: show-edit.php?id=' . $last_id);

How do I make an if statement which checks if a variable is in the mysql database

try {
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM us WHERE username='$suser' and password='$shashpass'"; // SQL Query
$conn->exec($sql);
Thats some of my code, how do I make it so if suser and shashpass are correct it can
execute some code, else it executes other code
This won't work either
<?php
try
{
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password"); $query->bindParam(':user',$suser);
$query->bindParam(':password',$shashpass); $query->execute(); $result = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){ } else { } }
catch(PDOException $e) {
echo $sql . $e->getMessage();
}
You don't pre-hash the password when verifying it. Instead you SELECT the password hash from that user (if it exists) and then use password_verify() to verify that it's correct based on the plain text password sent by the web form.
$stmt = $conn->prepare("SELECT password FROM us WHERE username=?");
$stmt->execute([$suser]);
if ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (password_verify($plain_text_password, $user['password'])) {
// Successful login
}
else {
// Valid user, but invalid password
}
}
else {
// User doesn't exist
}
If you're not using password_hash() and password_verify(), You're Doing It Wrong™.
you are using PDO in wrong way , you need to use prepared statements in PDO to be secure from mysql injections, try to use the code below:
try {
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password");
$query->bindParam(':user',$suser);
$query->bindParam(':password',$shashpass);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
// user is in database
} else {
// user is not there
}
exec will return the number of affected rows so:
$rows = $conn->exec($sql);
if($rows > 0){
//suser and shashpass are correct
}else{
//suser and shashpass are incorrect
}
//Use below PDO code
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
$sql = "SELECT * FROM us WHERE username='$suser' and password='$shashpass'";
// SQL Query
$conn->exec($sql);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

Changing from mysqli to PDO did not work?

I previously used mysqli and now i would like to use PDO instead but I did not echo any result from my database. I have read so many articles about PDO tutorial but they teach different things. I tried to pick piece by piece and came up with this code, but i did not echo any result from my database or throw any error.
try{
$stmt = $conn->query("SELECT * FROM memberpost ORDER BY poststart DESC LIMIT $start_from,$num_rec_per_page");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
if(count($row)>0){
while($row = $stmt->fetch()) {
echo $row['title']."<br>";
}
}
else{
echo "NO result found";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Here is my database connect code:
try {
$conn = new PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', $username, $password); //new PDO
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Edit your database connection code to this:
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
And try this code in your .php file :
$sth = $conn->prepare(SELECT * FROM memberpost)
$sth->execute();
$red = $sth->fetchAll();
print_r($red);
I found this on the internet, it might help:
// defining query
$sql = 'SELECT name, surname, zip FROM table';
// showing results
foreach($db->query($sql) as $row){
echo $row['name']. '<br>';
echo $row['surname']. '<br>';
echo $row['zip']. '<br>';
}
Source (ita): http://www.mrwebmaster.it/php/guida-utilizzo-pdo_7594_4.html

Storing MySQL connection details as a function in PHP (PDO)

I'm trying out the PDO extension, and was wondering if it were possible to store the opening of the DB connection as a function that could be called whenever needed. I tried some basic stuff, but it doesn't seem to work. Can it?
Example Function
function DB() {
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!$conn) {
echo "<br />MySQL SERVER CONNECTION ERROR.<br />\n";
}
if($conn) {
return $conn;
}
}
Example Useage
function is_post_id($submitted) {
try {
$id = $submitted;
DB();
//check to see if there is a post
//with an id matching the submitted query
$qPOST= $conn->prepare('SELECT COUNT(*) FROM posts WHERE id = :id');
$qPOST->execute(array('id' => $id));
//results counted
$cPOST= (int)$qPOST->fetchColumn();
if($cPOST > 0) {
return TRUE;
}
else {
return FALSE;
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
call it as :
$conn = $this->DB();
OR
$conn = $className->DB();

Categories