Related
This is my code I have to insert an array each value in the insert statement
if(isset($_POST['add'])){
$batch = $_POST['batch'];
$course = explode(':', $_POST['course']);
$cid = $course[0];
$rowCount = count($_POST['branch']);
$branch = implode(',', $_POST['branch']);
$semester = $_POST['sem'];
$day = $_POST['day'];
$hour = $_POST['hour'];
for($i=0;$i<$rowCount;$i++){
$description = $_POST['branch'][$i];
$sql. = "INSERT INTO batch (batch,bdescription,branch,course,semester,day,hour,user) VALUES ('$batch','$description',$i,'$cid','$semester','$day','$hour','$usnid');";
}
if($conn->query($sql)){
$_SESSION['success'] = 'batch added successfully';
}
else{
$_SESSION['error'] = $conn->error;
}
}
Please help thanks
You can't execute multiple queries with a single call to $conn->query().
Change your query so it's just a single INSERT statement with multiple lists of values after VALUES.
$sql = "INSERT INTO batch (batch,bdescription,branch,course,semester,day,hour,user) VALUES "
for($i=0;$i<$rowCount;$i++){
$description = $_POST['branch'][$i];
$sql. = "('$batch','$description',$i,'$cid','$semester','$day','$hour','$usnid'),";
}
$sql = substr($sql, 0, -1); // remove last comma
You should also use $conn->real_escape_string() to escape all the inputs, to protect against SQL injection (it would be even better to do that with a prepared statement, but it's difficult to make a prepared statement in mysqli with dynamic parameters).
Barmar is correct, you can't execute multiple SQL statements with query(). There's mysqli_multi_query(), but there's hardly ever a justification for using that. The former Engineering Director for MySQL once told me unequivocally, "there's no reason for multi-query to exist."
You should use parameters instead of copying $_POST variables directly into your SQL strings. It's not hard, in fact it makes code easier than fiddling with confusing quotes-within-quotes and mysqli_real_escape_string() and so on.
I wouldn't bother with trying to insert multiple tuples in a single INSERT statement. How many branches can possibly be in a single POST? A few dozen at most? Not enough to make it necessary to make the INSERT into a single statement. So just call execute() for a prepared INSERT, once for each row.
$sql = "INSERT INTO batch
SET batch=?, bdescription=?, branch=?, course=?, semester=?,
day=?, hour=?, user=?";
$stmt = $conn->prepare($sql) or die($conn->error);
$description = '';
$stmt->bind_param('ssssssss', $batch, $description, $i, $cid, $semester, $day, $hour, $usnid);
for($i=0;$i<$rowCount;$i++){
$description = $_POST['branch'][$i];
$stmt->execute() or die($stmt->error);
}
Read the manual for https://www.php.net/manual/en/mysqli-stmt.bind-param.php for more code examples.
This is how I Fixed My Code. I Used for loop
if(isset($_POST['addstd'])){
$rowCount = count($_POST['student']);
for($i=0;$i<$rowCount;$i++){
$stdid = $_POST['student'][$i];
$course = $_POST['course'][$i];
$batch = $_POST['batch'][$i];
$branch = $_POST['branch'][$i];
//insert students into attendance table
$sqlsel = "SELECT year,student_id, student_rollno,firstname,lastname, branch,active, nr FROM student WHERE student.student_id = '$stdid' AND student.branch = '$branch'";
$querysel = $conn->query($sqlsel) or die($conn->error);
$rowsel = $querysel->fetch_assoc();
if($rowsel !== null){
$year = $rowsel['year'];
$rollno = $rowsel['student_rollno'];
$active = $rowsel['active'];
$branch = $rowsel['branch'];
$name = $rowsel['firstname'].$rowsel['lastname'];
$sql = "INSERT IGNORE INTO class (year,regno, rollno,name, programme,coursecode,batch,user,active,count) VALUES ('$year','$stdid','$rollno','$name','$branch','$course','$batch','$usnid','$active','$i');";
if($conn->query($sql)){
$_SESSION['success'] = 'Students Added To Batch Successfully';
}
else{
$_SESSION['error'] = $conn->error;
}
}
else{
continue;
}
}
}
else{
$_SESSION['error'] = 'Fill up add form first';
}
I'm here trying to update my DB rows without deleting/creating new ones all the time. Currently, my DB creates new entries everytime I run this block of code. Instead of spamming my DB, I just want to change some of the values.
<?php
try {
$conn = new PDO("mysql:host=localhost;port=3306;dbname=dbname", Username, password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['mUsername']))
{
$mUsername = urldecode($_POST['mUsername']);
$mEvent = urldecode($_POST['mEvent']);
$mChat = urldecode($_POST['mChat']);
$mlongitude = urldecode($_POST['mlongitude']);
$mlatitude = urldecode($_POST['mlatitude']);
$sqlUPDATE = "UPDATE users
SET lastEvent=:lastEvent, lastChat=:lastChat,
lastLong=:lastLong, lastLatt=:lastLatt
WHERE name=:name";
$stmt = $conn->prepare($sqlUPDATE);
$stmt->bindParam(':lastEvent', $mEvent);
$stmt->bindParam(':lastChat', $mChat);
$stmt->bindParam(':lastLong', $mlongitude);
$stmt->bindParam(':lastLatt', $mlatitude);
$stmt->bindParam(':name', $mUsername);
$stmt->execute();
}
echo "successfully updated";
?>
My assumption is my final line, the $results area. I believe it's just treating this an a new entry instead of an update. How do I go about just replacing values? some values will not change, like the username, and sometimes longitude/latitude won't need to be changed. Would that have to be a separate query, should I split this in to two scripts? Or could I just enter a blank, null value? Or would that end up overwriting the ACTUAL last coordinates, leaving me with null values? Looking for any help or guides or tutorials. Thank you all in advance.
lots of syntax error in your code. It is simple to use bindParam
$sqlUPDATE = "UPDATE users
SET lastEvent=:lastEvent, lastChat=:lastChat,
lastLong=:lastLong, lastLatt=:lastLatt
WHERE name=:name";// you forget to close statement in your code
$stmt = $conn->prepare($sqlUPDATE);
$stmt->bindParam(':lastEvent', $mEvent);
$stmt->bindParam(':lastChat', $mChat);
$stmt->bindParam(':lastLong', $mlongitude);
$stmt->bindParam(':lastLatt', $mlatitude);
$stmt->bindParam(':name', $mUsername);
$stmt->execute();
read http://php.net/manual/en/pdostatement.bindparam.php
When using prepared statements, you should also make a habbit of following the set rules. Use named parameters. Try this:
if(isset($_POST['mUsername']))
{
$mUsername = urldecode($_POST['mUsername']);
$mEvent = urldecode($_POST['mEvent']);
$mChat = urldecode($_POST['mChat']);
$mlongitude = urldecode($_POST['mlongitude']);
$mlatitude = urldecode($_POST['mlatitude']);
$sqlUPDATE = "UPDATE users SET lastEvent= :lastEvent, lastChat= :lastChat, lastLong= :lastLong, lastLatt= :lastLatt WHERE name= :name";
$q = $conn->prepare($sqlUPDATE);
$results = $q->execute(array(':name'=>$mUsername, ':lastEvent'=>$mEvent, ':lastChat'=>$mChat, ':lastLong'=>$mlongitude, ':lastLatt'=>$mlatitude));
}
database.php: //database class file
public function multipleInsert($table,$attrArray,$valuesArray) {
$sql = "INSERT INTO ".$table."(";
$array =[];
$appendValues = "";
$valuesInArray = "";
foreach ($attrArray as $key => $value) {
$sql.="".$value.", ";
}
$sql = substr_replace($sql,") VALUES ",strlen($sql)-2);
foreach ($valuesArray as $valArr) {
$valuesInArray.= "(";
foreach ($valArr as $key => $value) {
array_push($array, $value);
$valuesInArray.="?,";
}
$appendValues.= substr_replace($valuesInArray,"),",strlen($valuesInArray)-1);
$valuesInArray = "";
}
$appendValues = substr_replace($appendValues,"",strlen($appendValues)-1);
$sql.=$appendValues;
//die($sql);
$result = $this->executeQueryPRE($sql,$array);
return $result;
}
private function executeQueryPRE($sql,$arr) {
try{
$executeSQL = $this->Connection->prepare($sql);
print_r($executeSQL);die();
$executeSQL->execute($arr);
if($executeSQL) {
if($this->Connection->lastInsertId())
return $this->Connection->lastInsertId();
else
return true;
}
else
return false;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
sample.php // sample file which utilizing multiple insert query
require_once("database.php");
$Database = new Database;
$arr = ["ct_name","ct_num","ct_status"];
$arr1 = [["x","1234567890",1],["y","1234567890",1],["z","1234567890",1],["a","1234567890",1]];
$Database->multipleInsert("contact",$arr,$arr1);
Using PDO prepare statement, I am trying develop a dynamic multiple insert query. when I try to execute it, the values are getting inserted into table twice. I have gone for print_r($executeSQL) and die() option before executing it showed me a proper multiple insertion query as below.
PDOStatement Object ( [queryString] => INSERT INTO contact(ct_name,
ct_num, ct_status) VALUES (?,?,?),(?,?,?),(?,?,?),(?,?,?) )
why is it inserting twice and what is the reason and how can I overcome with this problem ?
Not an answer to your actual question but maybe to the actual problem you want to solve:
I don't think this string concat stuff is worth any trouble.
Takes longer for the php script to execute, pollutes the MySQL query cache, is error prone.
Therefore unless you can point to a very,very specific problem I think it loses on all points against: Just prepare a statement and execute it multiple times.
<?php
/*
table must be a valid table identifier
columns must be an array of valid field identifiers
recordData is an array of records, each itself an array of corresponding values for the fields in $columns
recordData is the only parameter for which proper encoding is taken care of by this function
*/
function foo($table, $columns, $recordData) {
$query = sprintf('
INSERT INTO %s (%s) VALUES (%s)
',
$table,
join(',', $columns) /* put in the field ids like a,b,c,d */,
join(',', array_pad(array(), count($columns), '?')) /* put in a corresponding number of ? placeholders like ?,?,?,? */
);
// resulting query string looks like INSERT INTO tablename (a,b,c,d) VALUES (?,?,?,?)
// let the MySQL server prepare that query
$stmt = $yourPDOInstance->prepare($query);
// it might fail -> check if your error handling is in place here....
// now just iterate through the data array and use each record as the data source for the prepapred statement
// this will (more or less) only transmit the statement identifier (which the MySQL server returned as the result of pdo::prepare)
// and the actual payload data
// .... as long as $yourPDOInstance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); has been set somewhere prior to the prepare....
foreach( $recordData as $record ) {
$stmt->execute( $record );
// might fail, so again: check your error handling ....
}
}
$cols = ["ct_name","ct_num","ct_status"];
$data = [
["x","1234567890",1],
["y","1234567890",1],
["z","1234567890",1],
["a","1234567890",1],
];
foo("contact", $cols, $data);
(script is tested by php -l only; no warranty)
see also: http://docs.php.net/pdo.prepared-statements
As the title states: I am trying to update specific records in a MySQL data base using PDO and tokens to secure against any injection.
Here is my code:
Some arrays to help build the query:
$id = 1234
$values = array ('a','b','c',);
$variables = array ($A, $B, $C);
The query built via loop:
$sql = "UPDATE table1 SET ";
foreach($values as $value)
{
$sql .="$value = :$value, ";
}
$sql = rtrim($sql,', ');
$sql .=" WHERE id = '$id'";
Execution of query via PDO:
try
{
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare($sql);
foreach(array_combine($values, $variables) as $value=>$variable)
{
$stmt->bindParam(":$value", $variable);
}
$stmt->execute();
The result:
Every field in the specified record (matching $id) is set to the same value, which is always equal to the contents of the last variable listed in the array (in this example they would all contain the value held in $C)
echoing the SQL query shows it has been constructed correctly.
Any ideas? Thanks for your consideration
Extending from comment:
In your foreach loop, the $variable is a value, not a reference, so when you mysqli_stmt::execute(), you actually end up using the last $variable.
To avoid that, you'll have to use something like this:
$cache=array_combine($values,$variables);
foreach($cache as $value=>$variable)
{
$stmt->bindParam(":$value",$cache[$value]);
}
You have to make this way:
foreach(array_combine($values, $variables) as $value=>$variable)
{
$stmt->bindParam(":$value", $variable);
$stmt->execute();
}
Execute your query inside the for loop. Don't execute your query once the loop is done because it will only get the last value of your array. It will only execute once.
I'm trying to switch all my MySQL connections from the old mysql_query to PDOs. I'm trying to update multiple rows and columns of a MySQL table using different arrays and I'm receiving the following error:
[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(accnt, car, radio, misc) values ('admin', '300.00', '400.00', '10.00') WHERE ID' at line 1
From the following code:
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//$data = array_map(null,$account,$car_lease,$radio_lease,$misc_lease);
$A = count($lease_ID);
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH->prepare('UPDATE lease (accnt, car, radio, misc) values (:account, :car_lease, :radio_lease, :misc_lease) WHERE ID = :lease_ID');
$i = 0;
while($i < $A) {
$STH->bindParam(':account', $account[$i]);
$STH->bindParam(':car_lease', $car_lease[$i]);
$STH->bindParam(':radio_lease', $radio_lease[$i]);
$STH->bindParam(':misc_lease', $misc_lease[$i]);
$STH->bindParam(':lease_ID', $lease_ID[$i]);
$STH->execute();
$i++;
}
}
catch(PDOException $e) {
echo "I'm sorry, but there was an error updating the database.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
I believe this problem is arising from the way I'm calling the statement handle, but I'm not sure what part of my syntax is incorrect. Also, is this the best way of handling such situations? Or is there a better method to update multiple rows in a table?
You have confused the syntax between INSERT and UPDATE statements. Instead of a VALUES() list, you need a SET clause:
$STH = $DBH->prepare('
UPDATE lease
SET
accnt = :account,
car = :car_lease,
radio = :radio_lease,
misc = :misc_lease
WHERE ID = :lease_ID
');
Review the MySQL UPDATE syntax reference for the full specification to use with UPDATE statements.
I think this would be the simplest and easiest solution, if you can trust your keys and values:
$update = 'SET ';
$fields = array_keys($_POST);
$values = array_values($_POST);
foreach ($fields as $field) {
$update .= $field . '=?,';
}
$update = substr($update, 0, -1);
$db->query("update sub_projects ${update} where id=${_GET['id']}");
$db->execute($values);
Simple way to update multiple fields .but very important that inputs on your editing page must be in same order with your data base table.
hope its help
if (isset($_POST['pageSubmit'])) {
echo '<pre>';
print_r($_POST['page']);
echo '</pre>';
$fields = array('id','name','title','content','metaKey','metaDescr','metaTitle');//fields array
$fields = array_map(function($field){
return "`$field`";
},$fields);
$queryArray = array_combine($fields,$_POST['page']);//createng array for query
$countFields = count($queryArray);//getting count fields
$id = array_splice($queryArray , 0,-($countFields-1));//getting id of page
$insertArray = $queryArray;//getting new fields array without first key and value
function updatePage($db, array $fields, array $id){
$where = array_shift($id);
$sql = array();
foreach ($fields as $key => $value) {
$sql[] = "\n".$key."" ." = "."'".$value."'";
}
$sql = implode(",",$sql);
try {
$query = $db->prepare("UPDATE `pages` SET $sql WHERE `id` = $where ");
$query->execute();
} catch (Exception $e) {
echo $e->getMessage();
}
}
updatePage($db, $insertArray, $id);
}
better way is CASE, it is 3-4 time faster than preapared stmt