It keeps updating all of the rows as the samething - php

<?php
$method = strtoupper($_SERVER["REQUEST_METHOD"]);
if($method === "POST") {
$edittask = [
"TName"=>$_POST["TName"],
"description"=>$_POST["description"],
"status"=>$_POST["status"],
"duedate"=>$_POST["duedate"],
"userassign"=>$_POST["userassign"],
];
// use prepared statement to protect against SQL Injection
$sql ="UPDATE task_list SET task_name=:TName,description=:description,status=:status,due_date=:duedate,user_assign=:userassign WHERE id=:uid";
$statement = $DB->prepare($sql);
try {
// execute statement
$statement->execute($edittask);
header("location: /task/tasks");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
?>

You need to add the parameters(bind) to the query object.
Please see the bindParam method.
$sql ="UPDATE task_list SET task_name=:TName,description=:description,status=:status,due_date=:duedate,user_assign=:userassign WHERE id=:uid";
$statement = $DB->prepare($sql);
$statement->bindParam(':uid',$userId);
BindParam Documentation

Related

Multiple MySQLi prepared UPDATE statement in a SELECT

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!!

MYSQL Error Get Prepared Statement

How do I get the prepared statement of the mysqli_stmt-object?
If there is an error while executing the mysql-statement I want to return the statement.
$id = "89c483c8";
$query = "SELECT * FROM database WHERE id = ?";
if (!($stmt = $database->prepare($query) { ... }
else {
$stmt->bind_param("s", $id);
if (!$stmt->execute())
return $stmt->get_statement; //doesn't exist
}
"$stmt->get_statement" of course doesn't work. So how do I get the full query? In this example:
"SELECT * FROM database WHERE id = 89c483c8"
This is the best way to catch sql errors :
try {
$res = $mysqli_instance->query($query);
}catch (mysqli_sql_exception $e) {
print "Error Code <br>".$e->getCode();
print "Error Message <br>".$e->getMessage();
print "Strack Trace <br>".nl2br($e->getTraceAsString());
}
Or the simplest way :
echo $stmt->error
http://php.net/manual/en/mysqli.error.php

PHP PDO Statement inserting Null value to Db table

PHP PDO Statement inserting Null value to Db table
MY CODE:-
function pdate_product_desc_preview($fieldvalues, $company_digms1, $company_digms2, $company_digms3)
{
$query = "INSERT INTO eco_product_descTemp(`blockdigms1`, `blockdigms2`, `blockdigms3`) values(:company_digms1,:company_digms2,:company_digms3)";
try {
$stmt = $this->conn->prepare($query);
$stmt->bindValue(":company_digms1", $company_digms1);
echo $company_digms2;
$stmt->bindValue(":company_digms2", $company_digms2);
echo $company_digms3;
$stmt->bindValue(":company_digms3", $company_digms3);
$stmt->execute();
var_dump($stmt->errorInfo());
$productid = $this->conn->lastInsertId();
return $productid;
} catch (PDOException $e) {
$e->getMessage();
}
}
When i am executing, it only insert null value with auto increment id.
Thanks in advance.
function pdate_product_desc_preview($fieldvalues, $company_digms1, $company_digms2, $company_digms3)
{
$query = "INSERT INTO eco_product_descTemp (`blockdigms1`, `blockdigms2`, `blockdigms3`) values(:company_digms1,:company_digms2,:company_digms3)";
try {
$stmt = $this->conn->prepare($query);
$stmt->bindParam(":company_digms1", $company_digms1);
echo $company_digms2;
$stmt->bindParam(":company_digms2", $company_digms2);
echo $company_digms3;
$stmt->bindParam(":company_digms3", $company_digms3);
$stmt->execute();
var_dump($stmt->errorInfo());
$productid = $this->conn->lastInsertId();
return $productid;
} catch (PDOException $e) {
$e->getMessage();
}
}
Try this one.
Just replacing bindValue with bindParam
You can check prepared-statements.php here.
I've left $fieldvalues in but i dont see what it is doing..
Here's my take on it:
function pdate_product_desc_preview($fieldvalues, $company_digms1, $company_digms2, $company_digms3)
{
if (!empty($company_digms1) && !empty($company_digms2) && !empty($company_digms3))
{
$stmt = $this->conn->prepare("INSERT INTO `eco_product_descTemp` (`blockdigims1`, `blockdigims2`, `blockdigims3`) VALUES (?,?,?)");
$stmt->execute([$company_digms1, $company_digms2, $company_digms3]);
echo 'Inserted!';
} else {
echo 'make sure all fields have been filled in!';
}
}
So on the condition that if none of the fields are empty (NULL) then run the query. If one is empty (NULL) then run the make sure statement.

How to avoid duplicating a lot of php prepare 12+ times

try {$db=mysqli_connect( etc )
catch {
retry on time out
handle errors
}
try { if (!($errors = $db->prepare("insert into errors (`insert`,`error`) values(?,?);
print "\n*********prepare Error:" . $db->error;
}
}
catch { repeat above}
try {$errors->bind_param("ss",$sqlLoad,$errormsg); }
catch {repeat above)
....
try {$error->execute()} catch {repeat above error handling}
Now repeat all of that 10-40 times for different SQL queries on different fields.
That is a lot of duplicated code. Make my code hard to read, and if someone wants to add more sql queries they are forced to reduplicate large blocks of code.
I was thinking something like this but ran into a stumbling block with bind.
$sql[0]=array("name","select ? from <tablename>","s");
$sql[1]=array("name","select ?,? from <tablename>","ss");
$sql[2]=array("name","select ?,?,? from <tablename>","sss");
$sql[3]=array("name","select ?,?,?,? from <tablename>","ssss");
for(i=0;i<=3,i++){
try (
$preQuery[$sql[i][0]=$db->prepare($sql[i][1]);}
catch {}
try {$preQuery[$sql[i][0]]->bind_param($sql[i][2],????);} //Here is the trouble how do I define unique variables
catch { }
}
Here is some real code
It is a work in progress
foreach ($fieldspath as $field)
{
$filepath=$_SERVER[$field];
$result=$queryfile->execute();
$getres = $queryfile->get_result();
$numRows = -1;
$numRows = $getres->num_rows;
if ($numRows <>0)
{
$qryField = $getres->fetch_assoc();
$_SERVER[$field]=$qryField["id"];
$fileCount=$qryField["count"];
$fileRating=$qryField["rating"];
mysqli_query($db, "update Files set count=count+1 where `id` ='" . $qryField["id"] . "';");
continue;
}
else
{
$output = $insertFile->execute();
$result = $queryip->execute();
$getres = $queryip->get_result();
$qryField = $getres->fetch_assoc();
$_SERVER[$field]=$qryField["id"];
}
}
Notice: How I can re-execute a query just by:
$result=$queryfile->execute();
The query doesn't have to be re-stated, nor do the parameters. Everything is automatic. The actual queries are all listed at the top of the program, and I never have to see them, or restate them ever again. Also I don't need to cram my parameters into array before I can use them.
<?php
$pipeName = '/var/run/mysql/mysql.sock';
$username = 'user';
$password = 'password';
$db = new PDO('mysql:unix_socket='.$pipeName.";dbname=dbase", $username, $password);
$sql["errors"]="insert into errors (`insert`,`error`) values(:insert,:error);";
$sql["events"]="insert into event (`message`) values(?);";
$sql["queryip"]="select id,count,rating FROM ip where address=? limit 1;";
$sql["queryUsrAgent"]="select id,count,rating FROM http_user_agent where agent=? limit 1;";
$sql["insUsrAgent"]="insert into http_user_agent (`agent`) values (?);";
$sql["insertIP"]="insert into ip (`address`) values (?);";
$sql["insertReqURI"]="insert into request (`REQUEST_URI`) values (?);";
$sql["queryReqURI"]="select * FROM request where REQUEST_URI=? LIMIT 1;";
$sql["queryfile"]="select id,count,rating FROM Files where path=? limit 1;";
$sql["insertFile"]="insert into Files (`path`) values (?);";
$sql["cntIp"]="update ip set count=count+1 where `address` = :ip";
$sql["cntFiles"]="update Files set count=count+1 where `id` = :id;";
$sql["cntAgent"]="update http_user_agent set count=count+1 where `agent` = :agent;";
$sql["reqRequest"]="select * FROM request where REQUEST_URI= :requesturi LIMIT 1;";
$sql["cntRequest"]="update request set count=count+1 where `REQUEST_URI` = :requesturi;";
$ready=doPrepare($db,$sql);
$ready["errors"]->execute(array("insert"=>"stuff","error" =>"stuff"));
pdoRun($ready,"errors",array("iniisert"=>"iiiii","error" =>"yyyyyggg"));
function doPrepare($db, $enmass) {
foreach ($enmass as $key => $sql) {
try {
$stmt[$key] = $db->prepare($sql);
} catch (PDOException $e) {
print "\nStuff";
trigger_error($e);
return false;
}
}
return $stmt;
}
function pdoRun($ready,$query,$vals) {
try {
$ready[$query]->execute($vals);
} catch (PDOException $e) {
print "\nExecution fail";
}
}
// $stmt->execute(array_values($column_values));
?>
Making prepared queries like you are doing doesn't work like you seem to think it does. The parameter placeholders can only substitute for literal values. You can't use them for column names or table names or anything else.
You also can't prepare a query like "select ? from" because it names no table. It's not a syntactically complete query.
The better practice is to code a "helper function" that does the prepare and execute for you. You can reduce repetitive code that way.
By the way, I find PDO is much easier than Mysqli when coding a helper function like this, because you don't have to use the bind_param() with variable arguments. In PDO, you just pass an array of arguments to execute().
function doInsert($db, $sql, $params) {
try {
$stmt = $db->prepare($sql);
$stmt->execute($params);
} catch (PDOException $e) {
trigger_error($e);
return false;
}
return true;
}
Now call it this way:
$sql = "insert into errors (`insert`, `error`) values(?, ?)";
$success = doInsert($db, $sql, [$sqlLoad, $errormsg]);
You might even like the function to format your INSERT statement for you:
function doInsert($db, $table, $column_values) {
$placeholders = array_fill(1, count($column_values), '?');
$columns = implode(',', array_keys($column_values));
$sql = "INSERT INTO `$table` ($columns) VALUES ($placeholders)";
try {
$stmt = $db->prepare($sql);
$stmt->execute(array_values($column_values));
} catch (PDOException $e) {
trigger_error($e);
return false;
}
return true;
}
Then call it like this:
$success = doInsert($db, "errors", ["insert"=>$sqlLoad, "error"=>$errormsg]);
You'll have to do something to apply back-ticks to the column names too.

How to delete and update using php

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

Categories