PHP Update Prepared Statement Issue - php

Here is the updated code for anyone looking to update their database. Thank you everyone for all your help.
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("UPDATE test SET title=:title WHERE id=:id");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':id', $id);
// Update a row
$title = $_POST['title'];
$id = $_POST['id'];
$stmt->execute();
echo "Row updated";
echo "<br />";
echo "<strong>$title</strong> and <strong>$id</strong>";
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

You still have a bit of a mix of PDO and MySQLi although only in your call to bindParam now, which you are calling as if it was MySQLi::bind_param. Also in your last edit the query string got messed up with the addition of Values=? I'm not sure why you did that? Anyway, this should do what you want:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("UPDATE test SET title=:title WHERE id=:id");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':id', $id);
// Update a row
$title = $_POST['title'];
$stmt->execute();
echo "Row updated";
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;

Use bind_param() :
<?php
$statement = $conn->prepare("UPDATE test SET title= ? WHERE id= ?");
$statement->bind_param('si', $title,$id);
$statement->execute();
if ($statement->affected_rows >0) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$statement->close();
?>

use this.hope it will help you.
<?php
$statement = $conn->prepare("UPDATE myTable SET name = ? WHERE id = ?");
$statement->bind_param("si", $_POST['title'],$id);
$statement->execute();
$statement->close();
?>

Related

Can't figure out this bindParam issue

I'm trying to fetch some data from a MySql db using PDO but no matter what I do, I can't get anything when using a prepared statement... please tell me what I'm doing wrong.
The following code runs but returns nothing.
try {
$dbh = new PDO('mysql:host=localhost;dbname=banim', 'root', '');
$uName = "banim"; //$_POST['uName'];
$email = "Rabak#gmail.com"; //$_POST['email'];
$query = $dbh->prepare("SELECT * from users WHERE email = :email OR WHERE uName = :name");
$query->setFetchMode(PDO::FETCH_ASSOC);
$query->bindParam(":name", $uName);
$query->bindParam(":email", $email);
$query->execute();
foreach ($query as $row) {
print_r($query);
}
} catch (PDOException $e) {
echo "PDOException: " . $e->getMssage() . PHP_EOL;
}
What Alive To Die wrote was correct, and there was also an extra WHERE in the SQL string which also messed up the answer, this is the final code:
try {
$dbh = new PDO('mysql:host=localhost;dbname=banim', 'root', '');
$uName = "banim"; //$_POST['uName'];
$email = "Rabak#gmail.com"; //$_POST['email'];
$query = $dbh->prepare("SELECT * from users WHERE email = :email OR uName = :name");
$query->setFetchMode(PDO::FETCH_ASSOC);
$query->bindParam(":name", $uName);
$query->bindParam(":email", $email);
$query->execute();
while($row = $query->fetch()){
print_r($row);
}
} catch (PDOException $e) {
echo "PDOException: " . $e->getMssage() . PHP_EOL;
}

MYSQL Update PHP File Stop Updating

I have updated my code to include prepared as suggested below. However, I am getting "0 records UPDATED successfully". Once again the database is not being updated.
My new code is
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE mailinglist ". "SET optout = '$optout'".
"WHERE email = '$email'" ;
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Has anyone experienced this before and if so, does anyone know how to fix it?
Thank you in advanced.
$sql = "UPDATE mailinglist SET optout = ".$optout." WHERE email = ".$email;
Hello,
Just try out this.
I have made some changes i.n above line, just replace it with your line.

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

bindValue is not working

Using PDO with MariaDB server. I am having trouble understanding why this code does not work. Whenever I have :value for the values it gives me an error " Invalid parameter number: parameter was not defined"
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':domain', $domain);
$stmt->bindValue(':flag', $flag);
$stmt->execute();
But then the code below does work.
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (?,?,?)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(1, $username);
$stmt->bindValue(2, $domain);
$stmt->bindValue(3, $flag);
$stmt->execute();
Below is the rest of the section for this code.
if(isset($_POST['addEditor'])){
$username = $_POST['formUsername'];
$domain = $_POST['formDomain'];
$flag = $_POST['formflg'];
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':domain', $domain);
$stmt->bindValue(':flag', $flag);
$stmt->execute();
try{
$stmt->execute();
}
catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
That code worked for me have read something about PDO here
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$username='a';
$domain ='b';
$flag ='c';
$sql = "INSERT INTO `table` (`USER`, `DOMAIN`, `FLG`) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->execute(
array(':username'=> $username,
':domain'=> $domain,
':flag'=> $flag)
);
I am having trouble understanding why this code does not work.
No wonder, as you're using wrong way to understand.
Get rid of all try and catch operators in your code, run it again and then read the full error message, that will make you understand which code does not work.
if($_POST)
{
$role ="student";
try{
$stmt = $db_con->prepare("INSERT INTO userinfo (role)
VALUES(:qrole)");
$stmt->bindParam(":qrole", $role);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
try this , if some errors occurred it will post it using catch

Inserting into DB sometimes doesn´t work (chat with PDO, AJAX, long polling)

I have chat that uses long polling to get messages from DB (there are no problems to load them). But i also have script that insert messages into DB and it sometimes doesnt work ... it just doesn´t insert the row but it says that it was inserted.
<?php
include_once "../conect.php";
$sprava = $_POST['sprava']; // received message
session_start();
echo $sprava;
$ja = $_SESSION['id'];
session_write_close();
$cas = time();
try {
$conn = new PDO($databaza, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT som FROM user WHERE id = :ja";
$stmt = $conn->prepare($query);
$stmt->bindValue(':ja', $ja, PDO::PARAM_STR);
if ($stmt->execute()) echo "works ";
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$on = $row["som"];
echo $on;
if ($on == "") return 0;
try {
$conn = new PDO($databaza, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "INSERT INTO chat (cas,text,od,pre) VALUES (:cas, :text, :od, :pre)";
$stmt = $conn->prepare($query);
$stmt->bindValue(':cas', $cas, PDO::PARAM_STR);
$stmt->bindValue(':text', $sprava, PDO::PARAM_STR);
$stmt->bindValue(':od', $ja, PDO::PARAM_STR);
$stmt->bindValue(':pre', $on, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount();
if ($affected_rows == 1) echo " works";
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();}
?>
i get no errors and outpus is still in form as it should be
for example
1 works 37 works
2 works 37 works
3 works 37 works
4 works 37 works
5 works 37 works
that first number is message I entered, the first "works" means that ID of user was loaded, the second nuber is loaded ID and the last "works" means that the message was inserted into DB but it sometimes wasn´t (just sometimes).
but in DB i have rows only with for example
1
2
4
and 3, 5 is missing
An INSTEAD OF INSERT trigger is doing this. Check your table's triggers.
You are returning 0 when $on is empty, when this happens , it won't insert the data
If you are going to SELECT an INSERT in the same script, then I suggest you to split that logic especially if the INSERT depend on what the SELECT returns.
Create 2 fucntions:
SELECT function
function select_som($conn, $ja){
try {
$query = "SELECT som FROM user WHERE id = :ja";
$stmt = $conn->prepare($query);
$stmt->bindValue(':ja', $ja, PDO::PARAM_STR);
$success = $stmt->execute();
if(!$success){
echo "SELECT failed";
}
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$on = $row["som"];
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
return $on;
}
INSERT function
function insert_data($conn, $cas, $sprava, $ja, $on){
try {
$query = "INSERT INTO chat (cas,text,od,pre) VALUES (:cas, :text, :od, :pre)";
$stmt = $conn->prepare($query);
$stmt->bindValue(':cas', $cas, PDO::PARAM_STR);
$stmt->bindValue(':text', $sprava, PDO::PARAM_STR);
$stmt->bindValue(':od', $ja, PDO::PARAM_STR);
$stmt->bindValue(':pre', $on, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount();
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
return $affected_rows;
}
Usage:
if(isset($_POST['sprava'])){
include_once "../conect.php";
//session
session_start();
$ja = $_SESSION['id'];
session_write_close();
//connection
$conn = new PDO($databaza, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//get "$on"
$on = select_som($conn, $ja);
//insert
if($on != ""){
$cas = time();
$sprava = $_POST['sprava'];
$success = insert_data($conn, $cas, $sprava, $ja, $on);
if($success==1){
echo "INSERT Successful";
}else{
echo "INSERT Failed!!";
}
}else{
echo "on is empty, cannot insert data";
}
}

Categories