PHP Update statement not working because of the number of parameters - php
I have some php code for an app that I built. I have an sql statement that updates on duplicate key that is not working. It seems to have something to do with the number of parameters in the update part of the call. Please let me know if you have an idea on what the problem might be.
<?php
//database connection variables
$hostname = "";
$username = "";
$password = "";
$dbName = "";
//files to capture json
$incomingJson = 'json.txt';
// initialize the string with a blank value
$string = "";
function insertNewRowIntoStatistics($db,
$rowName,
$charactersName,
$highscoreFeet,
$charactersFitnessLevel,
$worstJump,
$totalTrainingTime,
$startingDate) {
$sqlInsertNewRow = <<<'EOT'
INSERT INTO Statistics(
charactersName,
highscoreFeet,
charactersFitnessLevel,
worstJump,
totalTrainingTime,
startingDate
) VALUES ( ?, ?, ?, ?, ?, ? )
ON DUPLICATE KEY UPDATE
highscoreFeet = VALUES(highscoreFeet),
charactersFitnessLevel = VALUES(charactersFitnessLevel),
worstJump = VALUES(worstJump),
totalTrainingTime = VALUES(totalTrainingTime)
EOT;
$stmt1 = $db->prepare($sqlInsertNewRow);
$stmt1->bind_param("siiiis",
$charactersName,
$highscoreFeet,
$charactersFitnessLevel,
$worstJump,
$totalTrainingTime,
$startingDate);
$stmt1->execute();
$stmt1->bind_result($result);
$stmt1->fetch();
$stmt1->close();
if(!$result){
trigger_error("Error inserting into Statistics, $result", E_USER_ERROR);
}
}
//Create function for deleting rows that have been in queuedRows for more then 5 minutes.
function deleteExpiredRowsInQueuedRows($db) {
$sqlDeleteQueuedRow = "DELETE FROM queuedRows WHERE timeOfCreation < ?";
$stmt4 = $db->prepare($sqlDeleteQueuedRow);
$stmt4->bind_param($stmt4, 'i', DateAdd(mi, -5, GetDate()));
$stmt4->execute();
$stmt4->bind_result($result);
$stmt4->fetch();
$stmt4->close();
// catch any errors
if(!$result){
trigger_error("Error deleting from queuedRows, $result", E_USER_ERROR);
}
}
//Create function for inserting rows that have been searched for into queued rows.
function insertRowInQueuedRows($db, $charactersName) {
$sqlInsertRowInQueuedRows = "Insert INTO queuedRows(charactersName, highscoreFeet, charactersFitnessLevel, worstJump, totalTrainingTime, startingDate, timeOfCreation) SELECT (charactersName, highscoreFeet, charactersFitnessLevel, worstJump, totalTrainingTime, startingDate, timeOfCreation) FROM Statistics where charactersName = ?";
$stmt3 = $db->prepare($sqlInsertRowInQueuedRows);
$stmt3->bind_param(1, $charactersName);
$stmt3->execute();
$stmt3->bind_result($result);
$stmt3->fetch();
$stmt3->close();
if(!$result){
trigger_error("Error inserting into queuedRows, $result", E_USER_ERROR);
}
}
function handleLineOfData( $db,
$rowName,
$charactersName,
$highscoreFeet,
$charactersFitnessLevel,
$worstJump,
$totalTrainingTime,
$startingDate ) {
if($startingDate != "1/1/1") {
//Insert or update a row in main table, Statistics.
insertNewRowIntoStatistics($db,
$rowName,
$charactersName,
$highscoreFeet,
$charactersFitnessLevel,
$worstJump,
$totalTrainingTime,
$startingDate);
} else {
//Search for the character name instead of adding it/delete expired rows.
insertRowInQueuedRows($db, $charactersName);
deleteExpiredRowsInQueuedRows($db);
}
}
//Connecting to your database
$mysqli = new mysqli($hostname, $username, $password, $dbName);
//If error occurs connection to database
if (mysqli_connect_error()) { trigger_error("Cannot connect", E_USER_ERROR); exit; }
//var_dump($_SERVER);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
var_dump( $_POST );
//capture incoming data
error_reporting(E_ALL);
ini_set('display_errors', 1);
//$sig = $_POST["sig"];
if( isset($_POST['params']) ) {
$jsondata = $_POST["params"];
//Captures sent json to figure out what to send back
//file_put_contents($incomingJson,$jsondata);
//converts JSON to an array
$array = json_decode($jsondata, TRUE);
//formats the array to view it easier
$results = print_r($array,true);
//file_put_contents($fullArray, $results);
//gets the total number of objects in the array
$arrlength = count($array['Children']['1']['Properties']);
//loop through array node and get row values
for ($i=0; $i < $arrlength; $i++) {
// get row value
$value = $array['Children']['1']['Properties'][$i]['Value']."\n";
// convert delimited string to an array
$arrayPieces = explode("|", $value);
$rowName = $arrayPieces[0];
$charactersName = $arrayPieces[1];
$highscoreFeet = $arrayPieces[2];
$charactersFitnessLevel = $arrayPieces[3];
$worstJump = $arrayPieces[4];
$totalTrainingTime = $arrayPieces[5];
$startingDate = $arrayPieces[6];
handleLineOfData( $mysqli, $rowName, $charactersName,
$highscoreFeet, $charactersFitnessLevel,
$worstJump, $totalTrainingTime, $startingDate );
}
}
// report http success even if data wasn't found
//Tells application of success
echo '{"Status":"Success"}';
} // end of POST
// start GET data
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
//var_dump( $_GET );
// initialize the JSON body variable
$jsonBody="";
//get table contents
$query = mysqli_query($mysqli, "SELECT * FROM queuedRows");
//construct an array to hold the data pulled down from mySQL
$rows = array();
// loop through the table and drop the data into the array
while($row = mysqli_fetch_assoc($query)) {
$rows[] = $row;
}
// get the number of rows in the array for the JSON return
$arrlength = count($rows);
// set while loop index
$i = 0;
//loop through array node and get row values
while ($i < $arrlength ) {
// tables we are capturing
$charactersName = $rows[$i]['charactersName'];
$highscoreFeet =$rows[$i]['highscoreFeet'];
$charactersFitnessLevel = $rows[$i]['charactersFitnessLevel'];
$worstJump = $rows[$i]['worstJump'];
$totalTrainingTime = $rows[$i]['totalTrainingTime'];
$startingDate = $rows[$i]['startingDate'];
// table row numbers. index starts at 0, increment it by 1 to get valid row numbers.
$tableRow = $i+1;
// construct the JSON return from data
$jsonString ='{"Name":"'.$tableRow.'","Value":"|'.$charactersName.'|'.$highscoreFeet.'|'.$charactersFitnessLevel.'|'.$worstJump.'|'.$totalTrainingTime.'|'.$startingDate.'|"},';
// append the JSON return with the new data
$jsonBody=$jsonBody.$jsonString;
// increase index and loop again if not at end of array.
$i++;
}
// construct the JSON response to send table back to app
// this is the header of the JSON return.
$jsonHeadher='{"Properties":[],"Name":"id946381_headers","Children":[{"Properties":[{"Name":"rowCount","Value":'.$arrlength.'},{"Name":"columnCount","Value":6},{"Name":"0-1-name","Value":"charactersName"},{"Name":"0-1-type","Value":1},{"Name":"0-2-name","Value":"highscoreFeet"},{"Name":"0-2-type","Value":2},{"Name":"0-3-name","Value":"charactersFitnessLevel"},{"Name":"0-3-type","Value":2},{"Name":"0-4-name","Value":"worstJump"},{"Name":"0-4-type","Value":2},{"Name":"0-5-name","Value":"totalTrainingTime"},{"Name":"0-5-type","Value":2},{"Name":"0-6-name","Value":"startingDate"},{"Name":"0-6-type","Value":1}],"Name":"id946381_headers","Children":[]},{"Properties":[';
// this is the footer of the JSON return.
$jsonFooter='],"Name":"id946381","Children":[]}]}';
// removes an extra comma that the loop above leaves behind
$jsonBody=rtrim($jsonBody, ",");
// constructing the full JSON return
$returnedJson=$jsonHeadher.$jsonBody.$jsonFooter;
// write the JSON data so the app can read it.
echo $returnedJson;
} // end of get
//Close out mysql
$mysqli->close();
?>
Related
all retrieve data from ms accesss database in php
Data retrieve from the ms access database 2007 in php using odbc driver. ALL data retrieve using query but its get only one record retrieve other data is not retrieve. below query three records but its retrieved only one data. which problem below code in php?how get all data using query from this code what's changes it? <?PHP include 'Connection2.php'; $sql = "select FYearID,Description,FromDate,ToDate from mstFinancialyear"; $stmt = odbc_exec($conn, $sql); //print_r($stmt); $rs = odbc_exec($conn, "SELECT Count(*) AS counter from mstFinancialyear"); //print_r($stmt); $arr = odbc_fetch_array($rs); $arr1 = $arr['counter']; $result = array(); //print_r($arr); if (!empty($stmt)) { // check for empty result if ($arr1 > 0) { // print_r($stmt); $stmt1 = odbc_fetch_array($stmt); $year = array(); $year['FYearID'] = $stmt1['FYearID']; $year['Description'] = $stmt1['Description']; $year['FromDate'] = $stmt1['FromDate']; $year['ToDate'] = $stmt1['ToDate']; // success $result["success"] = 1; // user node $result["year"] = array(); array_push($result["year"], $year); echo json_encode($result); //return true; } else { // no product found $result["success"] = 0; $result["message"] = "No product found"; echo json_encode($result); } odbc_close($conn); //Close the connnection first } ?>
You return only a single record in the JSON data because you do not iterate through the recordset. Initially I misread that you had called odbc_fetch_array twice on the same recordset but upon closer inspection see that one query is imply used, as far as I can tell, to see if there are any records likely to be returned from the main query. The re-written code below has not been tested - I have no means to do so - and has a single query only but does attempt to iterate through the loop. I included the count as a sub-query in the main query if for some reason the number of records was required somehow - I don't think that it is however. <?php include 'Connection2.php'; $result=array(); $sql = "select ( select count(*) from `mstFinancialyear` ) as `counter`, `FYearID`, `Description`, `FromDate`, `ToDate` from `mstFinancialyear`"; $stmt = odbc_exec( $conn, $sql ); $rows = odbc_num_rows( $conn ); /* odbc_num_rows() after a SELECT will return -1 with many drivers!! */ /* assume success as `odbc_num_rows` cannot be relied upon */ if( !empty( $stmt ) ) { $result["success"] = $rows > 0 ? 1 : 0; $result["year"] = array(); /* loop through the recordset, add new record to `$result` for each row/year */ while( $row=odbc_fetch_array( $stmt ) ){ $year = array(); $year['FYearID'] = $row['FYearID']; $year['Description'] = $row['Description']; $year['FromDate'] = $row['FromDate']; $year['ToDate'] = $row['ToDate']; $result["year"][] = $year; } odbc_close( $conn ); } $json=json_encode( $result ); echo $json; ?>
Stored array data into string with comma(,)
[!]problem: whenever I get the data from frontend and try to insert into database...the data are inserted as a single alphabet in elective cell...but what I really needed that the whole data to be inserted in the elective cell with separated by comma(,) <?php include_once '../../config/db_connection.php'; include_once '../../config/functions.php'; include "autho.php"; include('../db_mysqli.php'); if (isset($_POST['submit'])) { $username1 = $_POST['username']; $username1 = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $username1); $rollno = $_POST['register_no']; $rollno = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $rollno); $subjectcode = implode(',', $_POST['subject']); ; date_default_timezone_set("Asia/Kolkata"); $today = date('g:ia \o\n l jS F Y'); $rollnos = array_map('strlen', $rollno); $rollnos = min($rollnos); if ($rollnos < 6) { $error = 'Roll Number is too short.'; } else { } if (!isset($error)) { for ($i = 0; $i < count($rollno); $i++) { $sql = "UPDATE students SET elective='$subjectcode[$i]' WHERE register_number='$rollno[$i]'"; $result = mysqli_query($conn, $sql); if ($result) { header('Location:./?edu_camp=elective_student_update&success'); } else { header('Location:./?edu_camp=elective_student_update&fail'); } } } else { //echo "Sorry! something Wrong."; } } ?>
As the comments mentioned, you can implode your array into a string an insert it (docs). Also, you're using MySQLi, but not using bound parameters which you REALLY should be using (docs). // Concatenate all values together $commaSeparatedList = implode(',',$subjectcode); // Prepare your statement $stmt = $mysqli->prepare("UPDATE students SET elective=? WHERE register_number=?"); // Bind the relevant parameters (not sure what the where clause should be here) $stmt->bind_param('si', $commaSeparatedList, $i); // Check if rows were affected if ($mysqli->affected_rows > 0) { // Success, rows were changed } // Execute and close the statement object $stmt->execute(); $stmt->close();
How to set object property to null in Mysql
I am uploading a list of Objects to MySQL. Some of the objects do not contain the same number of variables. For example Objectt1 { property1 property 2 } Objectt2 { property1 property2 property3 } Objectt3 { property1 } My problem is that Object3 in mysql is being given a property2 and property3 instead of NULL. the value is being taken from the Object2. How can I make object 3's propery2 and property3 null? The php code is as follows: (I think I understand why it does this, because the variable is isset already in a previous run of the loop. But I don't know how to fix it.) <?php error_reporting(E_ALL); ini_set('display_errors', 1); if($_SERVER["REQUEST_METHOD"] == "POST") { require 'connection.php'; uploadstart(); } function uploadstart() { global $connect; $json = $_POST["objectlist"]; //Remove Slashes if (get_magic_quotes_gpc()){ $json = stripslashes($json); } $createworkoutquery = $connect->prepare("INSERT INTO objectTable (id, prop1, prop2, prop3) VALUES (?, ?, ?, ?)"); $createworkoutquery->bind_param("ssss", $ID, $prop1, $prop2, $prop3) ; //convert json object to php associative array $data = json_decode($json, true); //Util arrays to create response JSON $a=array(); $b=array(); // loop through the array foreach ($data as $row) { // get the list details $ID = $row["id"]; $prop1 = $row["prop1"]; if (isset($row["prpop2"])) { $prop2 = $row["prop2"]; } if (isset($row["prop3"])) { $prop3 = $row["prop3"]; } // execute insert query $result = $createworkoutquery->execute(); //if insert successful.. plug yes and woid else plug no if($result){ $b["id"] = $ID; $b["status"] = 'yes'; array_push($a,$b); } else { $b["id"] = $ID; $b["status"] = 'no'; array_push($a,$b); } } echo json_encode($a); //close connection mysqli_close($connect); } ?>
Assign null to the missing properties on each iteration so the previous value doesn't get bound to the query: foreach($data as $row){ $ID = $row['id']; $prop1 = isset($row['prop1'])? $row['prop1']: null; $prop2 = isset($row['prop2'])? $row['prop2']: null; $prop3 = isset($row['prop3'])? $row['prop3']: null; $result = $createworkoutquery->execute(); ... }
One thing I noticed is a mispelling prpop2 if (isset($row["prpop2"])) { $prop2 = $row["prop2"]; }
How to return error message if there is no data in the database?
I wanted the logic is if there is data in the database then query the data. Or else if there is no data then it will show an error message. Here is my code: $stmt = $db->prepare($query); $stmt->execute(array('date' => $myFormat)); $data = $stmt->fetchAll(); if ( !$data ) { echo 'No data found in database!'; } else { return $data = $query; } Before this code, if the code that query from database: //Query string and put it in a variable. if(isset($_POST['dob_chi'])){ $query = "SELECT * FROM $table_n WHERE dob_chi = :date"; } else { $query = "SELECT * FROM $table_n WHERE dob_eng = :date"; } I tried input a non data to execute the code but somehow it didn't show error and straight process to the scripting area. The script below: //create a while loop for every entry in our DB where the date is match. while ($row = $stmt->fetchObject()) { $r1 = $row->rowone; $r2 = $row->rowtwo; $r3 = $row->rowthree; $englishdate = $row->dob_eng; $chinesedate = $row->dob_chi; //add all initial data into the matrix variable for easier access to them later $rows[0] $rows = array( array($r1), array($r2), array($r3), array() ); } //incoporate modulo value as an argument. function incmod($a, $m) { return ($a % $m) + 1; } //Population each row, with $populationCount number of elements, where each element is added with incmod(X, $mod) function populateRow($rowId, $populationCount, $mod) { //function to access the global variable. global $rows; $row = $rows[$rowId]; while (sizeof($row) < $populationCount) { $rowInd = sizeof($row) - 1; $m = incmod($row[$rowInd], $mod); array_push($row, $m); } //set the row back into the global variable. $rows[$rowId] = $row; }
$stmt = $db->prepare($query); $stmt->execute(array('date' => $myFormat)); $data = $stmt->fetchAll(); if ( !$data ) { echo 'No data found in database!'; }
Mysqli with unknown bind_results
Ok, I thought I had this, but I can't see why it's not working... I have a SELECT with a variable table, hence my columns (bind_result) is going to be variable. I need to adjust for any number of columns coming back, and fetch as an associated array, since there will be multiple rows coming back: // Get table data $mysqli = new mysqli('host','login','passwd','db'); if ($mysqli->connect_errno()) { $errors .= "<br>Cannot connect: ".$mysqli->connect_error()); } $stmt = $mysqli->prepare("SELECT * FROM ?"); $stmt->bind_param('s', $table); $stmt->execute(); // Get bind result columns $fields = array(); // Loop through columns, build bind results for ($i=0; $i < count($columns); $i++) { $fields[$i] = ${'col'.$i}; } // Bind Results call_user_func_array(array($stmt,'bind_result'),$fields); // Fetch Results $i = 0; while ($stmt->fetch()) { $results[$i] = array(); foreach($fields as $k => $v) $results[$i][$k] = $v; $i++; } // close statement $stmt->close(); Any thoughts are greatly appreciated ^_^ EDIT: New code: $mysqli = new mysqli('host','login','passwd','db'); if ($mysqli->connect_errno)) { $errors .= "<br>Cannot connect: ".$mysqli->connect_error()); } $stmt = "SELECT * FROM ".$table; if ($query = $mysqli->query($stmt)) { $results = array(); while ($result = $query->fetch_assoc()) { $results[] = $result; } $query->free(); } $mysqli->close();
You can not bind the table name. Bind_param accept the column name and its datatype. To use the table name dynamically use the below code: $stmt = $mysqli->prepare("SELECT * FROM ".$table);