PHP array to mysql BD... missing array fields - php

Need your help.
I need to update the array data in the mysql table. my problem is that there are some array values which dont have "photo" coloum (check 4th field in the array) because of that my query is failing with error "Column count doesn't match value count at row 1"
below is what im trying.
$dept = $job->user();
$sql = array();
foreach( $dept as $row ) {
$sql[] = '('.$row['dob'].', "'.($row['name']).'", "'.($row['role']).'"
"'.$row['email'].'", "'.($row['photo']).'" )';
}
mysql_query('INSERT INTO cast (dob, name, role, email, photo) VALUES '.implode(',', $sql)) or die(mysql_error());
Array Data
array
0 =>
array
'dob' => string '01121978'
'name' => string 'Ram Avtar'
'role' => string 'Inspector'
'email' => string 'ramavtar#gmail.com'
'photo' => string ' '
1 =>
array
'dob' => string '15021978'
'name' => string 'Suresh Babu'
'role' => string 'Constable'
'email' => string 'ssbh1#mail.yahoo.com'
'photo' => string ' '
2 =>
array
'dob' => string '11111965'
'name' => string 'Dean'
'role' => string 'Inspector'
'email' => string 'ddepth#live.in'
'photo' => string ' '
3 =>
array
'dob' => string '10061979'
'name' => string 'Rohit Shette'
'role' => string 'Sergeant'
'email' => string ' '
'photo' => string ' '
4 =>
array
'dob' => string '15081979'
'name' => string 'Ian'
'role' => string 'warden'
'email' => string ' '
table structure
CREATE TABLE user(
id INT(5) NOT NULL AUTO_INCREMENT,
dob TEXT NOT NULL,
name TEXT NOT NULL,
role TEXT DEFAULT NULL,
email TEXT DEFAULT NULL,
photo TEXT DEFAULT NULL
)
ENGINE = INNODB
CHARACTER SET latin1
COLLATE latin1_swedish_ci;

The actual problem is that you missed a comma.
Change:
echo $sql[] = '('.$row['dob'].', "'.($row['name']).'", "'.($row['role']).'"
"'.$row['email'].'", "'.($row['photo']).'" )';
To:
$sql[] = "('{$row['dob']}', '{$row['name']}', '{$row['role']}',
'{$row['email']}', '{$row['photo']}')"; // ^^^ Here is the missing comma
The missing values will not cause a problem, they will just cause an empty string to be inserted, because the string is quoted. However, you may wish to test to make sure the key exists in the array array before you try to use it, to avoid any nasty E_NOTICEs.
Also, make sure you properly escape your data before you use it in a query - you don't want a visit from Bobby Tables...

First - if that's your real code I think you're missing a comma after $row['role']. Also - why not check if array key exists?
Try something like (not tested, just to give you an idea)
$dept = $job->user();
$sql = array();
foreach( $dept as $row ) {
echo $sql[] = '('
. (array_key_exists('dob', $row) ? $row['dob'] : 'null') . ', "'
. (array_key_exists('name', $row) ? $row['name'] : 'null') . '", "'
. (array_key_exists('role', $row) ? $row['role'] : 'null') . '", "'
. (array_key_exists('email', $row) ? $row['email'] : 'null') . '", "'
. (array_key_exists('photo', $row) ? $row['photo'] : 'null') . '" )';
}
mysql_query('INSERT INTO cast (dob, name, role, email, photo) VALUES '.implode(',', $sql)) or die(mysql_error());

Related

Parse JSON file in PHP and insert into SQL ----

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();
}

Post multidimensional array in Mysql

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();
}

PHP MySQL Insert 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

Codeigniter Database Insert - Not Working With Array

I'm trying to insert some data into a database via codeigniter but am getting some strange errors. Does anyone know the cause:
My insert array ($datainsert) is the following when printed:
Array ( [online_name] => Discount Store
[online_nameKey] => d
[storeGroup_ID] =>
[CJ_ID] => 123456
[online_tag] => Health and Medical
[online_businessType] => 0
[online_businessTypeSub] => 0
[online_homepage] => http://www.discountstore.com
[store_ChainID] =>
[savingsdotcom_ID] => 0 )
Trying to print the insert I use:
echo $DB1->_insert('stores_online', $datainsert);
Which results in:
INSERT INTO stores_online (Discount Store, d, , 123456, Health and Medical, 0, 0, http://www.discountstore.com, , 0) VALUES ()
I can't figure out why its not using the array keys for the first () and the values correctly.
Try this code
$datainsert=Array ( [online_name] => Discount Store,
[online_nameKey] => d,
[storeGroup_ID] => something,
[CJ_ID] => 123456 ,
[online_tag] => Health and Medical ,
[online_businessType] => 0 ,
[online_businessTypeSub] => 0 ,
[online_homepage] => http://www.discountstore.com ,
[store_ChainID] => ,
[savingsdotcom_ID] => 0
) ;
$this->db->insert('stores_online', $datainsert);
Use
$this->db->insert('stores_online', $datainsert);
instead of
echo $DB1->_insert('stores_online', $datainsert);
I know the question is over a year, but I had the same issue and I solve it by creating the query manually this way:
public function add($data)
{
$query = 'INSERT INTO myTable (';
// (Column1, Column2, Column3,
foreach($data as $key => $column)
$query .= $key . ',';
// Removes the last comma
// Column3, == Column3) VALUES(
$query .= rtrim($query, ',') . ') VALUES(';
// Value1, Value2, Value3,
foreach($data as $key => $column)
$query .= "'" . $column . "',";
// Removes the last comma and closes the query
$query .= rtrim($query, ',') . ')';
// Result: INSERT INTO (Column1, Column2, Column3) VALUES ('VALUE1', 'VALUE2', 'VALUE3')
return $query;
}
This needs to be done:
echo $DB1->_insert('stores_online', array_keys($datainsert), $datainsert);
P.S. This works for CI 2.X and I have not tested it for other version of CI.

MySQL returns null values for certain rows

I am having a problem with MySQL and PHP. I'm trying to create something that gets values from a database, encode it in JSON and then print it. I have that down, but there's something that is keeping from one certain row in the database from displaying. It always returns NULL except for the id value I set. Here's my code, am I doing something wrong?
$srv = mysql_query("SELECT * FROM `players` WHERE `name` LIKE '%" . mysql_real_escape_string($_GET['q']) . "%'");
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $playerarray['id'], 'name' => $playerarray['name'], 'server' => $playerarray['server']);
echo(json_encode($playerInfo));
}
If you want to take a look at it, it's hosted here. The funny thing is, this page uses the exact same code, but doesn't return null. Any ideas?
Edit:
Here's what is in $playerInfo (when I use geekygamer14)
array (size=3)
'id' => null
'name' => null
'server' => null
It seems that whatever rows that have verified set to 1 (integer), it gives NULL.
You're using variable $record in your loop, though this doesn't show in your generated array. Instead you're using a variable named $playerarray. I assume the code should be:
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $record['id'], 'name' => $record['name'], 'server' => $record['server']);
echo(json_encode($playerInfo));
}
Note: Consider using an alternative to mysql-functions, for example mysqli. Mysql-functions are deprecated.
Change this
$srv = mysql_query("SELECT * FROM `players` WHERE `name` LIKE '%" . mysql_real_escape_string($_GET['q']) . "%'");
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $playerarray['id'], 'name' => $playerarray['name'], 'server' => $playerarray['server']);
echo(json_encode($playerInfo));
}
to this
$srv = mysql_query("SELECT * FROM `players` WHERE `name` LIKE '%" . mysql_real_escape_string($_GET['q']) . "%'");
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $record['id'], 'name' => $record['name'], 'server' => $record['server']);
echo(json_encode($playerInfo));
}
Your variables name $playerarray['id'] is wrong this is write $record['id']. Your data is in $record because of loop so you should use $record instead of $playerarray.

Categories