I've spent hours looking at this and just don't see the mistake.
6 columns, 6 ?'s, 6 array elements.
The insert works fine the update is the problem!
Btw. is this a good way to deal with insert on duplicate update?
$userId = 13;
foreach($tableKey as $table=>$value){
foreach($value as $key=>$val){
$array_of_parameters[$key] = $val;
$fields[] = sprintf("%s=?", $key);
}
$field_list = join(', ', $fields);
try{
$update = "UPDATE `$table` SET $field_list WHERE id=$userId";
$stmt = $db->prepare($update);
echo $stmt->debugDumpParams();
$stmt->execute($array_of_parameters);// here's where I get error!
if($stmt->rowCount() == 0){
$insert = "INSERT INTO `$table` (".implode(',', array_keys($value)).") VALUES (:".implode(',:', array_keys($value)).")";
$stmt = $db->prepare($insert);
echo $stmt->debugDumpParams();
$stmt->execute($array_of_parameters);
}
}
}
Here's the debug and $array_of_parameters
array
'user' => string 'somebody' (length=3)
'first' => string 'some' (length=7)
'last' => string 'body' (length=4)
'zoneId' => string 'zone' (length=4)
'email' => string 'tst#me.net' (length=21)
'head' => string '1' (length=1)
SQL: [80] UPDATE `user` SET user=?, first=?, last=?, zoneId=?, email=?, head=? WHERE id=13 Params: 0
And of course the error
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Try calling array_values on $array_of_parameters before executing the statement.
For unnamed parameters, execute probably expects numeric (default) keys in your parameters array. Populate $array_of_parameters in order without keys, then try it.
Related
$query = 'SELECT name FROM users';
$stmt = $db->prepare($query);
$stmt->execute();
works well. Now I change my code just a bit
$query = 'SELECT RIGHT(name, 2) FROM users';
$stmt = $db->prepare($query); // returns false
$stmt->execute(); // throws an error
Does not work. var_dump($db->errorInfo()) outputs this
array (size=3)
0 => string 'HY000' (length=5)
1 => int 17
2 => string 'near "(": syntax error' (length=22)
What's the problem? name is a varchar string and it is longer than 2 symbols and never null.
So I have been doing my research and no method seems to parse my file correctly. I have tried these two codes, my data is being inserted into sql however it is inserted 3 times with the first insertion being fine while the other 2 are blank. Here is my JSON file and code:
JSON:
[
{
"Comments": {
"Manufacturer": "--E",
"Model": "----- ----- ----",
"BIOSFamily": "---",
"BIOSDate": --/--/---8",
"SerialNumber": "---------"
}
},
{
"#ComputerSystem.v1-----------ystem": {
"/redfish/v1/Systems/1/": {
"AssetTag": " ",
"Bios": {
"#odata.id": "/redfish/v1/systems/1/bios/"
},
"BiosVersion": "U----------------)",
"Boot": {
"BootSourceOverrideMode": "-----y",
"BootSourceOverrideTarget": "None",
"BootSourceOverrideEnabled": "Disabled",
"BootSo-----------arget#Redfish.AllowableValues": [
"None",
"Cd",
"Hdd",
"Usb",
"Utilities",
"Diags",
"BiosSetup",
"Pxe",
"UefiShell"
]
Code:
<?php
$connect = mysqli_connect("reserve1",
"root", "","server_31");
$filename = "-----.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO servers (Model,
Manufacturer, BIOSFamily,
BIOSDate,
SerialNumber) VALUES
('".$row["Comments"]["Model"]."' ,
'".$row["Comments"]
["Manufacturer"]."',
'".$row["Comments"]
["BIOSFamily"]."','".$row["Comments"]
["BIOSDate"]."','".$row["Comments"]
["SerialNumber"]."')";
mysqli_query($connect, $sql);
}
echo "Data in";
?>
ERROR:" Notice: Undefined index: Comments "
other forloops i have tried are:
foreach($data as $Comments)
{
$sql =" INSERT INTO
'servers'('Manufacturer','Model',
'BIOSFamily','BIOSDate',
'SerialNumber'), VALUES('{$Comments-
>Manufacturer}', '{$Comments-
>Model}',
'{$Comments->BiosFamily}',
'{$Comments->BiosDate}',
'{$Comments-
>SerialNumber}')";
}
ERROR:" Notice: Trying to get property of non-object in"
To reiterate: the first method does get my info onto sql but does so 3 times with the last 2 entries being blank. The second method does not insert anything into my table.
EDIT:
so i tried vardump, using the file itself all i got was NULL, copy and pasting the contents and labeling it $json= ' content ' in the script i get..
C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:16:
array (size=1)
0 =>
object(stdClass)[1]
public 'Comments' =>
object(stdClass)[2]
public 'Manufacturer' => string 'HPE' (length=3)
public 'Model' => string '-------------' (length=20)
public 'BIOSFamily' => string '---' (length=3)
public 'BIOSDate' => string '--/--/----' (length=10)
public 'SerialNumber' => string '-------' (length=10)
C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:17:
array (size=1)
0 =>
array (size=1)
'Comments' =>
array (size=5)
'Manufacturer' => string '---' (length=3)
'Model' => string '------ ----------' (length=20)
'BIOSFamily' => string '---' (length=3)
'BIOSDate' => string '--/--/----' (length=10)
'SerialNumber' => string '-------' (length=10)
Simply index in your foreach loop the first item since $array object maintains Comments only in first position. See 0 index from var_dump output:
array (
0 =>
array (
'Comments' =>
array (
'Manufacturer' => '--E',
'Model' => '----- ----- ----',
'BIOSFamily' => '---',
'BIOSDate' => ' --/--/-- - 8 ',
'SerialNumber' => '---------',
),
),
1 =>
array (
'#ComputerSystem.v1-----------ystem' =>
...
Therefore, iterate through the Comments array and use parameterization for readability:
$connect = new mysqli($servername, $username, $password, $dbname);
// PREPARED STATEMENT
$sql = "INSERT INTO servers (Model, Manufacturer, BIOSFamily, BIOSDate, SerialNumber)
VALUES(?, ?, ?, ?, ?)";
// INDEX FIRST ITEM AT 0
foreach($array[0] as $row) {
$stmt = $connect->prepare($sql);
// BIND PARAMETERS (NO COMMENTS INDEX)
$stmt->bind_param("sssss", $row["Model"],
$row["Manufacturer"],
$row["BIOSFamily"],
$row["BIOSDate"],
$row["SerialNumber"]);
// EXECUTE STATEMENT
$result = $stmt->execute();
}
I want to post a multidimensional array into Mysql.
The code I have to know.
if (isset($_POST['husers[]'])) {
$query = $db->prepare("UPDATE `users` SET highlighted_users = ( ? ) WHERE user_id = '" . $userId . "'");
$query->bindParam(1, $_POST['husers[]']);
$query->execute();
}
The data I have:
array (size=4)
'text' => string 'bla' (length=3)
'another text' => &string '' (length=0)
'husers' =>
array (size=5)
0 => string '100486' (length=6)
1 => string '13474' (length=5)
2 => string '179339' (length=6)
3 => string '184729' (length=6)
4 => string '150593' (length=6)
The function serialize will do the trick for you.
if (isset($_POST['husers'])) {
$query = $db->prepare("UPDATE `users` SET highlighted_users = ( ? ) WHERE user_id = '" . $userId . "'");
$query->bindParam(1, serialize($_POST['husers']));
$query->execute();
}
When you are pulling it out of the database you'll need to use the function unserialize to get it to a normal array.
You can use json_encode function of php. By this you can stora data as string. When retrieving it from database, by json_decodefunction yu can make it array again.
if (isset($_POST['husers'])) {
$query = $db->prepare("UPDATE `users` SET highlighted_users = ( ? ) WHERE
user_id = '" . $userId . "'");
$query->bindParam(1, json_eoncode($_POST['husers']));
$query->execute();
}
If you want to store the data as a simple comma-separate string:
if(isset($_POST['husers'])){ // changed $_POST key reference
$husers_csv=implode(',',$_POST['husers']);
$stmt=$db->prepare("UPDATE `users` SET highlighted_users=? WHERE user_id=?"); // removed (), added another placeholder
$stmt->bindParam(1,$husers_csv);
$stmt->bindParam(2,$user_id);
$status=$stmt->execute();
}
You can json_encode this data, then store it as a json string. When you pull the data back out simple json_decode() to get your array back.
if (isset($_POST['husers'])) {
$query = $db->prepare("UPDATE `users` SET highlighted_users = ( ? ) WHERE user_id = '" . $userId . "'");
$query->bindParam(1, json_encode($_POST['husers']));
$query->execute();
}
Can't figure out why this code isn't working:
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute([$SQL_values]);
And these are dumps of the two strings being inserted into those statements:
$SQL_update = UPDATE laptops SET asset_tag = :asset_tag WHERE id = :id
$SQL_values = 'asset_tag' => 5544, 'id' => 23
You missed : in your code:-
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute([':asset_tag' => 5544, ':id' => 23]);
So actually what you have to do is:-
$SQL_values =[':asset_tag' => 5544, ':id' => 23]; // create array like this
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute($SQL_values); // pass that array
Or
$SQL_values =['asset_tag' => 5544, 'id' => 23]; // create array like this
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute($SQL_values); // pass that array
Note:- execute won't accept a string, it must be an array.
I'm having trouble with inserting the values from this array. Here example:
$arr = json_decode($_POST['dynfields'], true);
//{"dynfields":{"dynfields[0][DescRepair]":"Desc repair","dynfields[0][NestParts]":"Parts","dynfields[0][EdPrice]":"10","dynfields[0][DateRepair]":"2015-07-20","dynfields[1][DescRepair]":"Desc repair","dynfields[1][NestParts]":"Parts","dynfields[1][EdPrice]":"5","dynfields[1][DateRepair]":"2015-07-20"}}
foreach ($arr as $key => $fieldArray ) {
foreach($fieldArray as $k => $v) {
echo $k . " - " . $v . "<br>"; // result: dynfields[0][DescRepair] - Desc repair
dynfields[0] [NestParts] - Parts
dynfields[0][EdPrice] - 10
dynfields[0][DateRepair] - 2015-07-20
dynfields[1][DescRepair] - Desc repair
dynfields[1][NestParts] - Parts
dynfields[1][EdPrice] - 5
dynfields[1][DateRepair] - 2015-07-20
}
//$query = mysqli_query($mysqli, "INSERT INTO repair (DescRepair, NestParts, EdPrice, DateRepair) VALUES ('?', '?', '?', '?')") or die(mysqli_error($mysqli));
}
This is my code, but I don't know how to insert the value in db. Can you give me any suggestions. Thanks.
I did not understand very well your code, but at first your json is bad, on post, this is an example of right json:
{
"dynfields": [
{
"DescRepair": "Desc repair",
"NestParts": "Parts",
"EdPrice": "10",
"DateRepair": "2015-07-20"
},
{
"DescRepair": "Desc repair",
"NestParts": "Parts",
"EdPrice": "5",
"DateRepair": "2015-07-20"
}
]
}
Then you can make a foreach with the dynfields data:
$myvar = json_decode($json,true);
$data = $myvar['dynfields'];
foreach(array_keys($data) as $index){
var_dump($data[$index]);
}
then you will get something like this (var_dump):
array (size=4)
'DescRepair' => string 'Desc repair' (length=11)
'NestParts' => string 'Parts' (length=5)
'EdPrice' => string '10' (length=2)
'DateRepair' => string '2015-07-20' (length=10)
array (size=4)
'DescRepair' => string 'Desc repair' (length=11)
'NestParts' => string 'Parts' (length=5)
'EdPrice' => string '5' (length=1)
'DateRepair' => string '2015-07-20' (length=10)
$query = mysqli_query($mysqli, "INSERT INTO repair (DescRepair, NestParts, EdPrice, DateRepair) VALUES ('?', '?', '?', '?')") or die(mysqli_error($mysqli))
relace each ? with {$arr['xxxxx']} Where xxxxx are your array keys
make sure to well-escape the variables to prevent SQL Injection
Hint: you can use PDO or prepared statements