I am creating message delete script in PHP MYSQLI. I have added zero value to update column. my script is working but I want to add zero value with bind parameters.
Here is my source code
<?php
require_once "config.php";
if (isset($_GET['to_id'])) {
$id = $_GET['to_id'];
$session_id = $_SESSION['userid'];
}
$stmt = $con->prepare("UPDATE pm SET from_delete = '0' WHERE id = ? AND from_id = ?");
$stmt->bind_param("ss", $id, $session_id);
if ($stmt->execute()) {
echo"deleted successfully";
} else {
echo "Failed to delete<br/>";
}
?>
Just add another placeholder ? and bind value to it:
$stmt = $con->prepare("UPDATE pm SET from_delete = ? WHERE id = ? AND from_id = ?");
$zero = '0';
$stmt->bind_param("sss", $zero, $id, $session_id);
I am trying to insert a row in mysql table using the below php prepared statement, but the code always pass the statement and move to echo "failed". what is missing in the below code?
(My Database has extra columns but I didn't add it as I don't want to insert values inside (one of these columns are auto increment))
<?php
$ActivityDate = $_POST["ActivitytDate"];
$CoreSite = $_POST["CoreSite"];
$ActionAuditor = $_POST["ActionAuditor"];
$DCOSPOC = $_POST["DCOSPOC"];
if($stmt = $mysqli->prepare("Insert INTO DCO_Database (ActivityDate, CoreSite, ActionAuditor, DCOSPOC) Where (ActivityDate=? AND CoreSite=? AND ActionAuditor=? AND DCOSPOC=?)"))
{
$stmt->bind_param("ssss", $ActivityDate, $CoreSite, $ActionAuditor, $DCOSPOC);
$stmt->execute();
$stmt->close();
}
else{
echo ("Failed");
$mysqli->close();
}
?>
I have editied the code to use values instead, it is not echoing Failed but echoing success .. but still not adding values to database
<?php
$ActivityDate = $_POST["ActivitytDate"];
$CoreSite = $_POST["CoreSite"];
$ActionAuditor = $_POST["ActionAuditor"];
$DCOSPOC = $_POST["DCOSPOC"];
$AreaOwner = $_POST["AreaOwner"];
$ActionImplementer = $_POST["ActionImplementer"];
$ActionOwner = $_POST["ActionOwner"];
$MailSubject = $_POST["MailSubject"];
$ActionType = $_POST["ActionType"];
$RequestType = $_POST["RequestType"];
$RequestNumber = $_POST["RequestNumber"];
$OpenTime = $_POST["OpenTime"];
$CloseTime = $_POST["CloseTime"];
$ActionResult = $_POST["ActionResult"];
$Violation = $_POST["Violation"];
$ActionDetails = $_POST["ActionDetails"];
$Snags = $_POST["Snags"];
$SnagDesc = $_POST["SnagDesc"];
$Layout = $_POST["Layout"];
$LayoutDesc = $_POST["LayoutDesc"];
$CabinetLocation = $_POST["CabinetLocation"];
$Mapping = $_POST["Mapping"];
$MappingDesc = $_POST["MappingDesc"];
$Notes = $_POST["Notes"];
if($stmt = $mysqli->prepare("Insert INTO DCO_Database (ActivityDate, CoreSite, ActionAuditor, DCOSPOC, AreaOwner, ActionImplementer, ActionOwner, MailSubject, ActionType, RequestType, RequestNumber, OpenTime, CloseTime, ActionResult, Violation, ActionDetails, Snags, SnagDesc, Layout, LayoutDesc, CabinetLocation, Mapping, MappingDesc, Notes) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"))
{
$stmt->bind_param("ssssssssssssssssssssssss", $ActivityDate, $CoreSite, $ActionAuditor, $DCOSPOC, $AreaOwner, $ActionImplementer, $ActionOwner, $MailSubject, $ActionType, $RequestType, $RequestNumber, $OpenTime, $CloseTime, $ActionResult, $Violation, $ActionDetails, $Snags, $SnagDesc, $Layout, $LayoutDesc, $CabinetLocation, $Mapping, $MappingDesc, $Notes);
$stmt->execute();
$stmt->close();
}
else{
echo ("Failed");
$mysqli->close();
}
echo ("Successful");
?>
// think you should do as follows, insert statement only allows where clause when select statement is used,
<?php
$ActivityDate = $_POST["ActivitytDate"];
$CoreSite = $_POST["CoreSite"];
$ActionAuditor = $_POST["ActionAuditor"];
$DCOSPOC = $_POST["DCOSPOC"];
if($stmt = $mysqli->prepare("Insert INTO DCO_Database (ActivityDate, CoreSite, ActionAuditor, DCOSPOC) values (?,?,?,?)");
{
$stmt->bind_param("ssss", $ActivityDate, $CoreSite, $ActionAuditor, $DCOSPOC);
$stmt->execute();
$stmt->close();
}
else{
echo ("Failed");
$mysqli->close();
}
?>
use values insted of where
<?php
$ActivityDate = $_POST["ActivitytDate"];
$CoreSite = $_POST["CoreSite"];
$ActionAuditor = $_POST["ActionAuditor"];
$DCOSPOC = $_POST["DCOSPOC"];
if($stmt = $mysqli->prepare("Insert INTO DCO_Database (ActivityDate, CoreSite, ActionAuditor, DCOSPOC) values(?,?,?,?)"))
{
$stmt->bind_param("ssss", $ActivityDate, $CoreSite, $ActionAuditor, $DCOSPOC);
$stmt->execute();
$stmt->close();
}
else{
echo ("Failed");
$mysqli->close();
}
?>
You have to use
values
in your query. and remove
AND
from the query too. Please check the following code.
if($stmt = $mysqli->prepare("Insert INTO DCO_Database (ActivityDate, CoreSite, ActionAuditor, DCOSPOC) values (?,?,?,?)"))
{
$stmt->bind_param("ssss", $ActivityDate, $CoreSite, $ActionAuditor, $DCOSPOC);
$stmt->execute();
$stmt->close();
}
else{
echo ("Failed");
$mysqli->close();
}
Please note that where is used for update. so to insert use the query as follows:
INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...);
(Sorry for my English writing)
This is my coding for insert data
$insertChecklist = 'INSERT INTO checklists(`ADMIN_ID`, `COMPUTER_ID`) VALUES(?, ?);';
$stmtChecklist = $connection->prepare($insertChecklist);
$stmtChecklist->bind_param('ii', $_POST['ADMIN_ID'], $_POST['COMPUTER_ID']);
$isInsert = $stmtChecklist->execute();
$lastInsertId = mysqli_insert_id($connection);
$stmtChecklist->close();
$insertInstalledProgram = 'INSERT INTO checklist_programs(`CHECKLIST_ID`, `PROGRAM_ID`) VALUES(?, ?);';
$stmtProgramId = $connection->prepare($insertInstalledProgram);
$stmtProgramId->bind_param('ii', $lastInsertId, $programId);
foreach ($_POST['PROGRAM_ID'] as $program)
{
$programId = $program;
$stmtProgramId->execute();
}
$stmtProgramId->close();
$connection->close();
if ($isInsert) {
// echo($lastInsertId);
header('Location: OverViewCheckList.php');
exit(0);
}
And I need to change this Insert into to Update
I don't know how. Please help :(
Thank you.
It is not clear what you really want
maybe something like that:
$updateChecklist = 'UPDATE checklists SET `ADMIN_ID` = ?, `COMPUTER_ID` = ? WHERE id = ?';
$stmtChecklist = $connection->prepare($insertChecklist);
$stmtChecklist->bind_param('iii', $_POST['ADMIN_ID'], $_POST['COMPUTER_ID'], $_POST['ID']);
$res = $stmtChecklist->execute();
I insert data into a table called 'roster'. The first column (id_roster) is an id using mysql auto-increment.
I run a SELECT to find the id_roster
I use this id_roster to insert it into a table 'roster_par_membre' along with other data
if ($insert_stmt = $mysqli->prepare("INSERT INTO `roster`(`nom_roster`, `description_roster`, `id_organisation`, `created_by`, `creation_date`,`modified_by`) VALUES (?, ?, ?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssiisi', $roster_name, $description_roster, $organisation_id, $user_id, $creation_date, $user_id);
if (!$insert_stmt->execute()) {
$reponse = 'Sorry, a database error occurred; please try later';
} else {
// if INSERT OK -> create a new line in roster_membre table
//1. get the roster_id
$sql = "SELECT r.id_roster
FROM roster r
WHERE r.nom_roster = ?
LIMIT 1";
$stmt = $mysqli->prepare($sql);
if ($stmt) {
$stmt->bind_param('s', $roster_name);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($id_roster);
$stmt->fetch();
$level = 1;
//2. create a line with the roster_id and insert the membre as level 1
$insert_stmt = $mysqli->prepare("INSERT INTO `roster_par_membre`(`id_membre`, `id_roster`, `level`, `modified_by`) VALUES (?,?,?,?)");
$insert_stmt->bind_param('iiii', $user_id, $id_roster, $level, $user_id);
$insert_stmt->execute();
$reponse = 'success';
}
So far the code is working but it is not very nice.
Is there a way when we create a new line in a table to directly return a value (id with auto-increment) to be used in a sql query (to insert data into a second table)? or maybe to merge the two query (the two INSERT) in one statment?
short edit: it is an AJAX $response the return value (JSON)
Ok,solution:
//1. get the roster_id
$sql = "SELECT r.id_roster
FROM roster r
WHERE r.nom_roster = ?
LIMIT 1";
$stmt = $mysqli->prepare($sql);
if ($stmt) {
$stmt->bind_param('s', $roster_name);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($id_roster);
$stmt->fetch();
Just need to replace all this part by
$id_roster = $mysqli->insert_id;
nice and easy. THANKS to albanx
these are the functions I used for query on projects that I do not want to use any framework (just php):
/**
*
* Executes query methods
* #param string $query the query string
* #param array $vals array of values
* #param bool $show show the query
* #return int/array/false
*/
function q($query, $vals=array(), $show_query=false)
{
$conn = new mysqli(...)
$offset = 0;
foreach ($vals as $v)
{
$cv = $conn->real_escape_string($v);//escape the value for avoiding sql injection
$fv = ($v===NULL) ? 'NULL':"'".$cv."'"; //if value is null then insert NULL in db
$qpos = strpos($query, '?', $offset);//replace the ? with the valeue
$query = substr($query, 0, $qpos).$fv.substr($query, $qpos+1);
$offset = $qpos+strlen($cv)+1;
}
$result = $conn->query($query);
if($show || $result===false) echo $query."<br>";
$rows = array();
if($result===true)
{
return $conn->affected_rows;
}
else if($result===false)
{
return false;
}
else
{
while ($row = $result->fetch_array(MYSQLI_ASSOC) )
{
$rows[]=$row;
}
}
return $rows;
}
function lastid()
{
return $this->qval("SELECT LAST_INSERT_ID()");
}
Usage example:
q('INSERT INTO USER(name, email) VALUES(?,?)', array('admin','admin#admin.com'));
$id = lastid();
I'm trying to convert mysql_query over to prepared statements, but it's failing silently and I'm not sure where I'm going wrong. Here's my proc.php page for a form:
$db = new PDO('mysql:host=XXX;dbname=XXX;charset=utf8', 'XXX', 'XXX');
if ($_POST['submit']) {
$type = $_POST['type'];
$auth1_lname = trim($_POST['auth1_lname']);
$auth1_fname = trim($_POST['auth1_fname']);
$today = date("Y-m-d");
$stmt = $db->prepare("INSERT INTO table_base ( type , publ_date , auth1_lname , auth1_fname )
VALUES (:type, :today, :auth1_lname , :auth1_fname) ");
$stmt->bindParam(':type', $type);
$stmt->bindParam(':today', $today);
$stmt->bindParam(':auth1_lname', $auth1_lname);
$stmt->bindParam(':auth1_fname', $auth1_fname);
$stmt->execute();
$bid = $db->lastInsertId();
$subj_area = $_POST['subj_area'];
$subject = 'subj_area';
$subjs = '';
$stmt = $db->prepare("INSERT INTO table_meta (bid, key, value) VALUES (:bid, :key, :value)");
$stmt->bindParam(':bid', $bid);
$stmt->bindParam(':key', $subject);
$stmt->bindParam(':value', $subjs, PDO::PARAM_STR);
foreach($subj_area as $subjs) {
$stmt->execute();
}
$geo_area = $_POST['geo_area'];
$geograph = 'geo_area';
$geos = '';
$stmt = $db->prepare("INSERT INTO table_meta (bid, key, value) VALUES (:bid, :key, :value)");
$stmt->bindParam(':bid', $bid);
$stmt->bindParam(':key', $geograph);
$stmt->bindParam(':value', $geos, PDO::PARAM_STR);
foreach($geo_area as $geos) {
$stmt->execute();
}
}
I'm not sure I'm even doing this right.
I see comments elsewhere on SO that your PHP must be this tall to use PDO, but php.net's page on PDO doesn't list PHP requirements. Am I failing b/c my PHP5 host doesn't have the right drivers?
Is there a way to add a die(mysql_error()) so at least it wouldn't be a silent failure?