I'm new with PHP. I'v been struggling with this task for hours now. Earlier I used json_encode to get data from MYSQL to a JSON file. Now i try to revese and add the same data from JSON file to a new MYSQL database. I have a problem with converting the array to string before passing it to MYSQL database tho. The database works and I was able to add "players" there by inserting manual values instead of the $values from array. My code looks like this:
<?php
//open connection to mysql db
$con = mysqli_connect("localhost","root","","scoreboard2") or die("Error " . mysqli_error($con));
$scorefile = file_get_contents('scores.json');
$Score = json_decode($scorefile, true);
echo '<pre>' . print_r($Score, true) . '</pre>';
foreach ($Score as $field => $value) {
// Use $field and $value here
print_r($field . '=>' . $value . '<br/>', true);
//mysqli_query($con, "INSERT INTO scores (name, score, time) VALUES ($value->name, $value->score, $value->time)");
}
//mysqli_close($con);
?>
the JSON file looks like this:
[
{"id":"22",
"name":"Jack",
"score":"2142",
"time":"196:13",
"ts":"2016-02-23 15:36:23",
"date":"2016-02-23"},
{"id":"23",
"name":"Bob",
"score":"7026",
"time":"35:54",
"ts":"2016-02-23 15:40:33"}
]
etc.. and the "error" is this:
Notice: Array to string conversion in F:\XAMPP\htdocs\JSON_MySQL\decode.php on line 13
The error
Notice: Array to string conversion in
F:\XAMPP\htdocs\JSON_MySQL\decode.php on line 13
is produced by the line
print_r($field . '=>' . $value . '<br/>', true);
(which actually is the 13th line)
where you try to convert $value which is an array (your second score object) to a string in order to concatenate it with the rest of the string
note that if you replace the error-producing line by
echo '<pre>' .$field . '=>' . print_r($value, true) . '</pre>'.'<br/>';
you get the
0=>Array
(
[id] => 22
[name] => Jack
[score] => 2142
[time] => 196:13
[ts] => 2016-02-23 15:36:23
[date] => 2016-02-23
)
1=>Array
(
[id] => 23
[name] => Bob
[score] => 7026
[time] => 35:54
[ts] => 2016-02-23 15:40:33
)
that you might originally expect
Your issue is that you are converting the data in your .json file to an array by using parameter 2 of json_decode() as true.
This is converting your objects to arrays and therefore the syntax you use in this line is wrong
mysqli_query($con, "INSERT INTO scores
(name, score, time)
VALUES ($value->name, $value->score, $value->time)");
because you are using object notation.
So change this line from
$Score = json_decode($scorefile, true);
To
$Score = json_decode($scorefile);
SO
?php
$con = mysqli_connect("localhost","root","","scoreboard2") or die("Error " . mysqli_error($con));
$scorefile = file_get_contents('scores.json');
$Score = json_decode($scorefile);
foreach ($Score as $object) {
mysqli_query($con, "INSERT INTO scores
(name, score, time)
VALUES ('{$object->name}', '{$object->score}', '{$object->time}')");
}
mysqli_close($con);
?>
Also note I quoted the values with single quotes and also wrapped the object properties in {} which is required when using object or array notation inside a double quoted literal.
Related
Using EasyRdf, I want to fetch query result. I used below code in codeigniter:
$this->load->library('rdf');
EasyRdf_Namespace::set('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns');
EasyRdf_Namespace::set('srt', 'http://persuratan-semweb.dev/ontologies/surat.owl');
$sparql = new EasyRdf_Sparql_Client('http://localhost:3030/surat_single/sparql');
$query = "SELECT * WHERE { "
. "?surat rdf:type srt:Surat . "
. "?surat srt:sifat_surat ?sifat_surat . "
. "?surat srt:nomor_surat ?nomor_surat . }";
$result = $sparql->query($query);
echo "jumlah data: " . $result->numRows() . "<br>";
echo "<br>";
foreach ($result as $row) {
echo $row->sifat_surat . " " .$row->sifat_surat . " " . $row->nomor_surat ."<br>";
}
print_r($result);
The output I got are:
jumlah data: 0
EasyRdf_Sparql_Result Object (
[type:EasyRdf_Sparql_Result:private] => bindings
[boolean:EasyRdf_Sparql_Result:private] =>
[ordered:EasyRdf_Sparql_Result:private] =>
[distinct:EasyRdf_Sparql_Result:private] =>
[fields:EasyRdf_Sparql_Result:private] => Array (
[0] => surat
[1] => sifat_surat
[2] => nomor_surat
)
[storage:ArrayIterator:private] => Array ( )
)
I also try Joshua's solution given here, but got similar output. I also try my query in Fuseki endpoint (I'm using Fuseki triplestore) and got this result. I'm completely beginer in semantic web.
I don't know whether it's the answer or not, but these namespaces don't look right to me:
EasyRdf_Namespace::set('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns');
EasyRdf_Namespace::set('srt', 'http://persuratan-semweb.dev/ontologies/surat.owl');
The rdf namespace should have a # at the end, and you should probably have one for your OWL file, too:
EasyRdf_Namespace::set('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
EasyRdf_Namespace::set('srt', 'http://persuratan-semweb.dev/ontologies/surat.owl#');
But that said, there's no reason you can't try a simpler query first. Why not just run
SELECT ?s ?p ?o { ?s ?p ?o }
to be sure that you can get results, and what the data is.
I'm trying to save with foreach
here is what i get from my form
Array
(
[mulai] => 2016-08-28
[akhir] => 2016-08-31
[keterangan] => remarks
[nip] => Array
(
[0] => 1004384
[1] => 1602744
[2] => 1501039
)
)
and then here is my saving query.
$jumlahrange = $this->db->query("SELECT DATEDIFF(day,'".$mulai."','".$akhir."') AS diff")->row();
$totaldata = count($nip);
$skrg = $this->db->query("SELECT GETDATE() tgl")->row();
for($x = 0;$x<=$totaldata;$x++)
{
for($y=0;$y<$jumlahrange->diff;$y++){
$this->db->query("INSERT INTO attendance
(Nip,AttendanceDate,InTime,OutTime,AttendanceCode,RosterCode,LocationCode,Remarks,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy)
values(
'".$nip[$x]."',DATEADD(DAY,".$y.",'".$mulai."'),'','','P3','','','".$keterangan."','".$skrg->tgl."','$niplogin','','')
");
}
}
i have no problem with my save but i have empty field like this in my table. In row 10,11,12 . That row should not exist right?.
I using SqlServer 2008 and Codeigniter . I know i can use insert_batch, but i want use this way.
in your line for($x = 0;$x<=$totaldata;$x++) i'm pretty sure you wanted to write < instead of <=
To overcome these kind of issues you can use foreach loop instead
foreach($resourcedata as $value){
//your code goes here and you will get all array elements sequentially in **$value** variable
}
This one is right at your fingertips. $nip[$x] is null. Error log or dump and die on the first loop $nip[$x] and see what it returns. If it is in fact not null, then it might be a data type problem (string vs int).
I'm trying to convert an array (key/value) to be an SQL statement.
I'm using MYSQLi like such:
if(!$result = $mysqli->query($sql)){throw new Exception("SQL Failed ".__file__." on line ".__line__.":\n".$sql);}
I have an array like such:
Array
(
[database] => Array
(
[cms_network] => Array
(
[network_id] => 61
[network_name] =>
[network_server_mac_address] => 00:1b:eb:21:38:f4
[network_description] => network
[network_thermostat_reporting_rate] => 5
[network_server_reporting_rate] => 5
[network_data_poll_rate] => 5
[network_created_by] => 38
[network_modified_by] => 1
[network_network_id] => 8012
[network_language] => en
[network_hotel_id] => 68
[network_channel] => 0
[network_deleted] => 0
[network_reported_network_id] => 8012
[network_rooms] => 4
)
)
)
How can I convert [cms_network] to look like this:
$sql = "UPDATE cms_network set network_id='61', network_name='',
network_server_mac_address = '00:1b:eb:21:38:f4', .... WHERE network_id='61'"
I'm more interested in knowing how to concatenate the key=>value pair of the array to be key='value' in my select statement.
Thanks for the help!
If you use the VALUES syntax, you could do it in one fell swoop.
mysql_query("
UPDATE MyTable
( . implode(',', array_keys($array['database']['cms_network'])) . ")
VALUES ('" . implode("','", $array['database']['cms_network']) . "')
");
This, of course, assumes that the data is already escaped.
EDIT: Tidier version that's easier to read and maintain:
$fields = implode(',', array_keys($array['database']['cms_network']));
$values = implode("','", $array['database']['cms_network']);
mysql_query("UPDATE MyTable ($fields) VALUES ('$values')");
I suggest you populate an array with formatted key/value pairs, then implode them at the end. This is an easy way to add the required , between each key/value:
$fields = array();
foreach($array['database']['cms_network'] as $key => $value) {
// add formatted key/value pair to fields array
// e.g. format: network_id = '26'
$fields[] = $key . " = '" . $value . "'";
}
$fields = implode(', ', $fields);
// build your query
$query = "UPDATE cms_network SET " . $fields . " WHERE network_id = " . $array['database']['cms_network']['network_id'] . " LIMIT 1";
// process it...
This will (SQL wise) be inserting every value as a string, which is obviously incorrect with integer columns etc. It should still work anyway, but if not you'll need to put in a conditional statement for whether to wrap the value in quotes or not, like this:
foreach(...) {
if(is_numeric($value))
$fields[] = $key . ' = ' . $value;
else
$fields[] = $key . " = '$value'";
}
Although this should probably relate to your database column type rather than the PHP variable type. Up to you, they should work fine with quotes around integers.
This should work.
$update_query = "UPDATE `cms_network` SET ";
$count = 0;
foreach($array['database']['cms_network'] as $key => $value) {
if ($count != 0) {
$update_query = $update_query.",".$key."=".$value;
} else {
$update_query = $update_query.$key."=".$value;
}
$count++;
}
$update_query = $update_query." WHERE ".cms_network."=".$array['database']['cms_network'];
mysql_query($update_query);
Hello i have a JSon array like this
Array
(
[NTAy] => ALFA ROMEO
[NTA0] => AUDI
[NTEx] => BMW
[NjAy] => CHEVROLET
[NTEz] => CHRYSLER
[NTE0] => CITROËN
[NjAz] => DACIA
[NjQ5] => DAEWOO
[NTE3] => DAIHATSU
)
and I have to insert it in a database row by row, I used
foreach ($mata as $marca_id => $marca_name){
$line = $line. "','" . $marca_id . "','". $marca_name . "','". $marca_name;
}
$line = substr($line, 0, strlen($line)-1);
$values[$i] = $line;
++$i;
$values =implode ( $values);
echo $values;
echo "<br />";
but at the mysql insert
$data = mysql_query(" INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug)
VALUES " .$values)
I get an error and can't get it to work. Can someone help me please?
foreach ($mata as $marca_id => $marca_name) {
$id = intval($marca_id);
$name = mysql_real_escape_string($marca_name);
$values = "$id, '$name', '$name'";
mysql_query("INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug) VALUES ($values)");
}
Why not use prepared statements? Especially if you're taking user generated data and entering it into your database.
That and it looks like you're final SQL query will look like this
INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug)
VALUES 'NTAy','ALFA ROMEO','ALFA ROMEO','NTA0','AUDI','AUDI' etc
You would have to break this up into multiple queries
I've recently started working with PHP and SQLite and I'm having problems with PHP arrays (I think). This is the code I use:
<?php
$dbo = new SQLiteDatabase("rsc/db.sqlite");
$test = $dbo->arrayQuery("DROP TABLE users;");
$test = $dbo->arrayQuery("CREATE TABLE \"users\"(name text, avatar text);");
$test = $dbo->arrayQuery("INSERT INTO users(name, avatar) VALUES('zad0xsis', 'http://zad0xsis.net/');");
// get number of rows changed
$changes = $dbo->changes();
echo "<br />Rows changed: $changes<br />";
// Get and show inputted data
$tableArray = $dbo->arrayQuery("SELECT * FROM users;");
echo "Table Contents\n";
echo "<pre>\n";
print_r($tableArray);
echo "\n</pre>";
?>
And when showing the data (print_r($tableArray);) I get this array:
Array
(
[0] => Array
(
[0] => zad0xsis
[name] => zad0xsis
[1] => http://zad0xsis.net/
[avatar] => http://zad0xsis.net/
)
)
I don't know why the values are duplicated, like [0] and [name], but it shows the data. Now, when I try to do print_r($tableArray["name"]); I should get the value, but it doesn't prints anything :( What I'm doing wrong? Thanks!
it helps you to select both
$tableArray[0]
or
$tableArray['name'];
it's fine.
to your problem: You'll have to
print_r($tableArray[0]['name'])
or
print_r($tableArray[0][0])