I have two or more statements on one page of my site. And it does not work properly.
The first code is like that:
$query = "SELECT gpname FROM guineapigs WHERE fbid=?";
if ($statement = $mysqli->prepare($query)) {
$statement->bind_param('s', $_SESSION[FBID]);
$statement->execute();
$statement->bind_result($gpname);
while($statement->fetch()) {
echo $gpname;
}
}
$statement->close();
The problem is when I try to add the second code to it:
if($_GET[buy]=='ch'){
$statement = $mysqli->prepare("UPDATE users SET `money` = `money`+ 22000 WHERE gpname=?");
$statement->bind_param('s', $gpname);
$results = $statement->execute();
header( "Location: /test.php?bsuccess=ch" );
}
if($_GET[bsuccess]=='ch'){
echo "Successfully added 22000 money..";
}
My code looks like this, but not working:
$query = "SELECT gpname FROM guineapigs WHERE fbid=?";
if ($statement = $mysqli->prepare($query)) {
$statement->bind_param('s', $_SESSION[FBID]);
$statement->execute();
$statement->bind_result($gpname);
while($statement->fetch()) {
if($_GET[buy]=='ch'){
$statement2 = $mysqli->prepare("UPDATE users SET `money` = `money`+ 22000 WHERE gpname=?");
$statement2->bind_param('s', $gpname);
$statement2->execute();
header( "Location: /test.php?bsuccess=ch" );
}
if($_GET[bsuccess]=='ch'){
echo "Successfully added 22000 money..";
}
}
}
$statement->close();
What am I doing wrong? I want to add even more UPDATE querys after selecting.
Ohh, I'm an idiot! That was the mistake:
Instead of
while ($stmt1->fetch()){
};
needs only:
while ($stmt1->fetch());
Here's a working example with some development:
<?php
ob_start();
session_start();
include_once 'dbtest.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$mysqli->autocommit(FALSE); //turn on transactions
$stmt1 = $mysqli->prepare("SELECT fbname,fbemail FROM users WHERE fbid = ?");
$stmt1->bind_param("s", $_SESSION['FBID']);
$stmt1->execute();
$stmt1->bind_result($fbname,$fbemail);
while ($stmt1->fetch());
$stmt2 = $mysqli->prepare("INSERT INTO test (name,email) VALUES (?, ?)");
$stmt2->bind_param("ss", $fbname, $fbemail);
$stmt2->execute();
$stmt2->close();
$stmt1->close();
$mysqli->autocommit(TRUE); //turn off transactions + commit queued queries
} catch(Exception $e) {
$mysqli->rollback(); //remove all queries from queue if error (undo)
error_log($e);
}
?>
Thank you anyway!!
Related
I want to update table with max three value and minimum with two values.How it would be possible to update table. I Get values from form, there are three fields for three students. Now all of them having same value when i update them in the database. Now i am trying this why. Dont know it works or not
See my page
$s1_name=$_POST['s1_name'];
$s2_name=$_POST['s2_name'];
$s3_name=$_POST['s3_name'];
$query="update students SET Name=:Name
WHERE ProjectID='$id'
";
try
{
$stmt = $conn->prepare( $query );
$stmt->bindParam(':Name', $s1_name);
$stmt->bindParam(':Name', $s2_name);
$stmt->bindParam(':Name', $s3_name);
$result = $stmt->execute();
$msg = "Record updated";
}
catch(PDOException $ex)
{
$msg = $ex -> getMessage();
}
}
It does not work this way. The way you are doing it will result in the query only updating it for $s3_name.
You will have to do your try/catch statement for each query:
<?php
$names = [$_POST['s1_name'], $_POST['s2_name'], $_POST['s3_name']];
$query = "update students SET Name=:Name WHERE ProjectID='$id'";
foreach ($names as $name) {
try
{
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name);
$result = $stmt->execute();
$msg = "Record updated";
}
catch(PDOException $ex)
{
$msg = $ex -> getMessage();
}
}
i want to insert into a table depending on the id of the session:
here the code in class.php:
public function activate($activation, $id,$change,$userID){
$stm1= $this->conn->prepare("INSERT INTO `log` (`date`,`change`) VALUES(CURRENT_TIMESTAMP(),'$change') WHERE `user_id` =$userID");
($stm1->execute());
$stmt = $this->conn->prepare("UPDATE `segments` SET `activation` = '$activation' WHERE `id` = '$id'")
or die($this->conn->error);
if ($stmt->execute()) {
$stmt->close();
$this->conn->close();
return TRUE;
}
}
at the top of the page i have this:
require './config.php';session_start();$userID = $_SESSION['user_id'];
and in action.php where the action go i have this:
$conn = new db_class();
$conn->activate($activation, $id,$change,$userID);
echo "Updated successfully.";
exit;
the first query insert into log is not working \ please help
This should be a comment but I don't have the rep yet...
Primarily, you don't do that type of insert with a WHERE clause. The insert will fail.
As an aside, that insert is open to sql injection. Bind your your parameters. Also, you should add error handling. If you had that, you would see the insert fails. Quick example (1 way...there are other ways...and I assumed $change is a string and $userId is an int...)
$sql = 'INSERT INTO log
SET `date` = CURRENT_TIMESTAMP(),
change = :change,
user_id = :user_id;';
$stmt = $this->conn->prepare( $sql );
$stmt->bindParam( ':change', $change, PDO::PARAM_STR );
$stmt->bindParam( ':user_id', $userID, PDO::PARAM_INT );
$result = $stmt->execute();
if (!$result) {
// failure -> get and handle the error
$error_array = $stmt->errorInfo();
} else {
// do something
}
The docs can help > pdo::execute, pdo::errorinfo
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.
Hello guys I have been trying to delete a file using php and I want it to delete the main post, reply's and like then update to the author -10 in his/her point.
Here is my code, using PDO:
<?php session_start();
if(isset($_POST['id'])){
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db_conn->prepare("DELETE FROM code WHERE cid= {$id}");
$stmt = $db_conn->prepare("DELETE FROM comment WHERE id = {$id}");
$stmt = $db_conn->prepare("DELETE FROM likes_map WHERE lid = {$id}");
$stmt = $db_conn->prepare("UPDATE users SET point -1 WHERE username = {$u}");
$stmt->bindParam(':id', $id);
$stmt->bindParam(':cid', $id);
$stmt->bindParam(':lid ', $id);
$stmt->bindParam(':u ', $_SESSION['username']);
$stmt->execute();
echo "deleted"
} catch(PDOException $e) {
echo "Error:" . $e->getMessage();
}
$db_conn = null;
}else{
echo "You are not allow to delete this";
}
?>
Your first problem is that you are preparing more than one query on the same statement handle and therefore loosing the link to that prepared statement when you prepare the next query.
You are also only executing the queries once and not once per statement!
Also your prepared sql statement do not have the parameters set with the correct syntax
It would also be a good idea to run this code inside a transaction, so if any update of the database fails you are not left with just bits of this process comepleted. This assumes the database is an INNODB database and not an MYISAM one, as transactions dont work on MYISAM
<?php
session_start();
if(!isset($_POST['id'])){
echo "You are not allow to delete this";
exit;
}
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// start a transaction
$db_conn->beginTransaction();
$d_code = $db_conn->prepare("DELETE FROM code WHERE cid= :id");
$d_code->bindParam(':id', $id);
$d_comment = $db_conn->prepare("DELETE FROM comment WHERE id = :id");
$d_comment->bindParam(':id', $id);
$d_like = $db_conn->prepare("DELETE FROM likes_map WHERE lid = :id");
$d_like->bindParam(':id ', $id);
$u_user = $db_conn->prepare("UPDATE users SET point -1 WHERE username = :u");
$u_user->bindParam(':u ', $_SESSION['username']);
$d_code->execute();
$d_comment->execute();
$d_like->execute();
$u_user->execute();
$db_conn->commit();
echo "deleted";
} catch(PDOException $e) {
$db_conn->rollBack();
echo "Error:" . $e->getMessage();
}
$db_conn = null;
?>
I am having quite some trouble and am unable to find the source of the problem but I cannot send a simple update to my sqlite3 database which simply times out and doesn't do anything. It said thirty seconds at first but then I changed it to 5 minutes and it still wouldn't do anything to query through a simple 1 rowed sqlite table.
if (isset($_POST['apply']))
{
try {
$bio = $_POST['bio'];
$file_db = new PDO('sqlite:Secure/data.sqlite');
// Set errormode to exceptions
//$file_db->exec("SET CHARACTER SET utf8");
$file_db->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
//
echo("$bio $name");
$sql = "UPDATE `users`
SET `profile` = :bio
WHERE `name` = :name
";
echo("2");
$statement = $file_db->prepare($sql);
echo("3");
$statement->bindValue(":bio", $bio);
echo("4");
$statement->bindValue(":name", $name);
echo("5");
$statement->execute();
echo("6");
$file_db = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
//$statement->bindValue(":profile", $profile);
//$statement->execute();
}
Remove the quotes from your bindValue() call:
$statement = $db->prepare($sql);
$statement->bindValue(':bio', $_POST['bio'], PDO::PARAM_STR);
$statement->bindValue(':name', $_POST['name'], PDO::PARAM_STR);
$statement->execute();
or
$statement = $db->prepare($sql);
$statement->execute(array(':bio' => $_POST['bio'],':name'=>$_POST['name']));
When doing updates, it is a good idea to check if it actually affected a row
if($statement->execute()){
echo 'success !';
if($statement->rowCount()>0){
echo 'record updated !';
}else{
echo 'no record updated !';
}
}else{
echo 'failed !';
}
It appears there was a variable being set in template.php called result, no idea why but I set this to null and all worked well...