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"];
}
Related
This question already has answers here:
Running a loop that has a function inside it
(9 answers)
Closed 2 years ago.
I have the below code that I am trying to fix. In this code, I have created a class and that has a function testcal() in it. In that function, I connect to database, do a select query from a table. For the result set, I want to loop through and grab values of fields $field1,2,3. Using those fields I am creating another function to throw out the result.
<?php
class test
{
public function testcal()
{
set_error_handler(function($errno, $errstr){
error_reporting(0);
}, E_WARNING);
//database credentials
$host = "localhost";
$db_name = "mydb";
$username = "root";
$password = "";
//connect to database
$con = mysqli_connect($host,$username,$password,$db_name);
//Query to generate check-in variables from ffc_contrast
$sql = "SELECT * FROM mytable";
//Store result on $result variable
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result))
{
//assign values to each variable
$field1 = $row["field1"];
$field2 = $row["field2"];
$field3 = 0.5;
////////////////
//Calculations//
////////////////
function ratingcheck($field1,$field2){
if($field1 == 0 || $field2 == 0){
return 0;
} elseif ($field1 == 1) {
return 1;
} elseif ($field2 == 2) {
return 2;
}else{
return null;
}
}
}
}
}
$test = new test();
print $test->testcal();
?>
I am getting an error saying Cannot redeclare ratingcheck() (previously declared in ~/myfile.php:51) in ~/myfile.php on line 37 I have declared the method correctly and have called the parent method. Not sure why I am getting this error. Can someone help?
class test
{
public function testcal()
{
....all your code....
//Store result on $result variable
$result = mysqli_query($con, $sql);
$returnValues = [];//not sure what you want here really, as you're returning inside youe while loop
//so that will only do 1 iteration anyway, so i'm assuming you want to build an array or something
while($row = mysqli_fetch_assoc($result))
{
//assign values to each variable
$field1 = $row["field1"];
$field2 = $row["field2"];
$field3 = 0.5;
//store the result from the function
$returnValues[] = $this->ratingcheck($field1,$field2);
}
return $returnValues;
}
////////////////
//Calculations//
////////////////
//declare the function once as part of the class, now you can call it
//i've put private here as it's making an inernal calculation, make it public if you prefer
private function ratingcheck($field1,$field2){
if($field1 == 0 || $field2 == 0){
return 0;
} elseif ($field1 == 1) {
return 1;
} elseif ($field2 == 2) {
return 2;
}else{
return null;
}
}
}
$test = new test();
print $test->testcal();
You are recreating the function ratingcheck on every iteration of the while loop. You cannot redeclare functions.
You need to move the function outside the loop and then call it from inside the loop.
Hi I'm inserting data to database it's saving two time same data only username is saving two times I want save it only one time also I want save address
<?php
$users = array("username"=>"Kaleem", "adrress"=>"abc");
class dbase{
public function dbinsert($table,$users)
{
foreach ($users as $key => $value)
{
$sql = "INSERT INTO $table (`$key`) VALUES ('$value')";
$this->conn->query($sql);
if($this->conn->query($sql))
{
echo "Data inserted";
}
}
}
public function __construct ()
{
$this->conn = new mysqli('localhost','root','','dbase');
if($this->conn)
{
echo "Connected<br>";
}
}
}
$obj = new dbase;
$obj->dbinsert('users',$users);
?>
The problem is that you are calling the query function twice.
$this->conn->query($sql); // saves the first time
if($this->conn->query($sql)) // saves the second time
{
echo "Data inserted";
}
To avoid that the query is called twice you can save the result of the query into a variable and check it in the if.
Currently, you are saving each field of the users array in an own dataset because you are calling the query function on each field from your foreach loop.
Try this:
<?php
$users = array( // this array is for the users
array("username"=>"Kaleem", "adrress"=>"abc"), // this is one user
array("username"=>"Mickey Mouse", "adrress"=>"Test street"),
);
class dbase{
public function dbinsert($table,$users)
{
foreach ($users as $key => $value)
{
// Extract field names
$fields = implode("`, `", array_keys ( $users[$key] );
// Extract values
$values = implode("', '", array_values ( $users[$key] );
$sql = "INSERT INTO $table (`" . $fields . "`) VALUES ('". $values ."')";
// Check if query was succesfull
$success = $this->conn->query($sql);
if($success)
{
echo "Data inserted";
} else { // if no success display error message
echo "Error while saving";
}
}
}
public function __construct ()
{
$this->conn = new mysqli('localhost','root','','dbase');
if($this->conn)
{
echo "Connected<br>";
}
}
}
$obj = new dbase;
$obj->dbinsert('users',$users);
?>
you need name and address together as column name and corresponding values as field values in sql
public function dbinsert($table,$users)
{
$sqlKeys = [];
$sqlValues = [];
foreach ($users as $key => $value)
{
$sqlKeys[] = "'".$key."'";
$sqlValues[] = "'".$value."'";
}
$keys = array_implode(",",$sqlKeys);
$values = array_implode(",",$sqlValues);
$sql = "INSERT INTO $table ($keys) VALUES ($values)";
if($this->conn->query($sql))
{
echo "Data inserted";
}
}
that happen because you using foreach() for single array dimension,
$users = ["username"=>"Kaleem", "adrress"=>"abc"];
foreach($users as $key=>$value){
echo $value."\n";
}
this $success = $this->conn->query($sql); executed twice because array length is 0 and 1 , if you wanna use foreach you have to use multidimensional array like
$users = [
["username"=>"Kaleem", "adrress"=>"abc"]
];
foreach($users as $key=>$value){
$sql = "INSERT INTO $table (`username`, `adrress`) VALUES ('". $value['username'] ."', '". $value['adrress'] ."')";
$this->conn->query($sql);
}
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$username= $_SESSION['username'];
require "connection.php";
// GET THE DATA FROM POST IF IT EXISTS
$data = isset($_POST['data']) ? $_POST['data'] : false;
// IF IT IS A VALID ARRAY THEN PROCESS IT
if (is_array($data)) {
// LOOP THOUGH EACH SUBMITTED RECORD
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$updatestr = '';
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$updatestr .= "`{$fieldname}` = '{$value}',";
}
}
// REMOVE THE TRAILING ,
trim($updatestr, ',');
$updatestr = rtrim($updatestr, ',');
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$updatestr} WHERE id= '$id'";
// SEND IT TO THE DB
$result= mysqli_query($conn, $query);
}
echo "working";
}
else {
echo "not working";
}
?>
I have this code and it works perfectly, however I want to add
mysqli_real_escape_string But how can I do that to each variable since I don't know there exact information? I want it before it gets added to the query incase special characters were added
I also realized that my id never changes, it always stays one, whats the problem with that?
Granted I do not have access to PHP right now I believe this should work and get you on prepared statements.
<?php
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$update_fields = array();
$bind_params_types = ''
$bind_params_values = array();
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$update_fields[] = '{$fieldname} = ?';
$bind_params_types .= 's';
$bind_params_values[] = $value;
}
}
$update_fields = implode(',', $update_fields);
$bind_params_values = implode(',', $value);
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$update_fields} WHERE id= '$id'";
if($stmt = mysqli_prepare($conn, $query)){
$stmt->bind_param($bind_params_types,$bind_params_values);
$stmt->execute();
} else {
echo "failed";
}
}
}
I've done addon in your code before updation i've esacpe the string
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$username= $_SESSION['username'];
require "connection.php";
// GET THE DATA FROM POST IF IT EXISTS
$data = isset($_POST['data']) ? $_POST['data'] : false;
// IF IT IS A VALID ARRAY THEN PROCESS IT
if (is_array($data)) {
// LOOP THOUGH EACH SUBMITTED RECORD
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$updatestr = '';
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$updatestr .= "`{$fieldname}` = '{$value}',";
}
}
// REMOVE THE TRAILING ,
trim($updatestr, ',');
$updatestr = rtrim($updatestr, ',');
$updatestr = mysqli_real_escape_string($conn, $updatestr);
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$updatestr} WHERE id= '$id'";
// SEND IT TO THE DB
$result= mysqli_query($conn, $query);
}
echo "working";
}
else {
echo "not working";
}
?>
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();
?>
I need the $data to return from the database if the data was found from the database, but unfortunately, my code is not working to return the data.
I tried to enter non-exist data, it managed to return the error message but if the data exist, the page displays nothing.
May I know where did I go wrong in my if statement?
Below is my code that contain after the $data return the script will execute.
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$dob = implode('/', array($day,$month,$year));
if(isset($_POST['submit'])){
if(empty($_POST['day']) || empty($_POST['month']) || empty($_POST['year'])){
echo "You need to fill in each field.<br /><br />Click here to <b>fill in each field</b> again";
exit;
}
}
//Date that user keyin
$userDate = $dob;
$dateTime = DateTime::createFromFormat('d/m/Y', $userDate);
$myFormat = $dateTime->format('Y-m-d');
//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";
}
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
exit;
} else {
return $data=$userDate;
}
//Now we 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;
$zodiac = $row->zodiac;
//add all initial data into a matrix variable for easier access to them later
//To access rowone use $rows[0][0], rowtwo $rows[1][0] ect.
//The matrix is an array which contains multiple array. eg. 2-dimensional arrays
//To get all the variables with $r1X simply retrieve the first array of the matrix eg $rows[0]
$rows = array(array($r1),array($r2),array($r3),array());
}
//Similarities between row1 and row2 made me incorporate modulo value as an argument.
function incmod($a, $m){
return ($a % $m) + 1;
}
Thank you for your time
Get rid of the line:
return $data=$userDate;
because it's ending your script and also overwriting the $data variable.
Change:
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
Then change the line:
while ($row = $stmt->fetchObject()) {
to:
foreach ($data as $row) {