I'm getting very stuck on something that should be very easy. I am trying to parse a .BLM file using a PHP class from http://kodegeek.wordpress.com/2010/02/20/rightmove-data-parsing-php-class/
The Class works perfectly and outputs an array like this: -
Array ( [0] => Array ( [AGENT_REF] => _70 [ADDRESS_1] => 123 Main Street [POSTCODE1] => CF12 [POSTCODE2] => 4HY [FEATURE1] => Ideal Location [FEATURE2] => Only £250 per room [FEATURE3] => Three Double Bedrooms ) [2] => Array ( [AGENT_REF] => _83 [ADDRESS_1] => 45 Harriet Street [POSTCODE1] => CF24 [POSTCODE2] => 4BU [FEATURE1] => Modern [FEATURE2] => Laminate Flooring ) )
Once the array is created I want to immediately insert the array into a SQL table. Ideally this would grab the Field titles eg. [AGENT_REF] [ADDRESS_1] and create columns and insert the data as a new row per array ([0] => Array [2] => Array) etc.
I have tried something like this and a multitude of other variation and I cant seem to get it to work.
function mysql_insert_array($table, $rmdata) {
foreach ($rmdata as $field=>$value) {
$fields[] = '`' . $field . '`';
$values[] = "'" . $value . "'";
}
$field_list = join(',', $fields);
$value_list = join(', ', $values);
$query = "INSERT INTO testarray (" . $field_list . ") VALUES (" . $value_list . ")";
<?php
$rmdata = ARRAY();
$rmdata[0]['field1'] = 1;
$rmdata[0]['field2'] = 'two';
$rmdata[0]['field3'] = 3;
$rmdata[0]['field4'] = NULL;
$rmdata[0]['field5'] = 'five';
$rmdata[1] = $rmdata[2] = $rmdata[3] = $rmdata[0];
foreach ($rmdata AS $key => $dummy) {
$fields = ARRAY();
$values = ARRAY();
foreach ($rmdata[$key] as $field=>$value) {
if (!isset($value)) {
//$value='';
// or
//if($field=='field4') { $value=4; }
// or $values[] = "NULL";
}
if (isset($value)) {
$fields[] = $field;
$values[] = "'".$value."'";
}
}
// if (count($fields) > 0)
echo 'key: '.$key.'<br />';
$sql_fields = implode(',', $fields);
$sql_values = implode(',', $values);
print_r($sql_fields); echo '<br />';
print_r($sql_values); echo '<hr />';
}
?>
You must create table with the field list before insert.
If you dont have table created, you can use :
$sql = "CREATE TABLE if not exists TABLENAME (
id tinyint(4) unsigned NOT NULL auto_increment,
AGENT_REF varchar(80) NOT NULL,
ADDRESS_1 varchar(255),
POSTCODE1 varchar(6),
POSTCODE2 varchar(6),
FEATURE1 varchar(255),
FEATURE2 varchar(255),
FEATURE3 varchar(255),
PRIMARY KEY (id)
)";
mysql_query($sql,$link);
and after your function.
$rmdata = ARRAY();
$rmdata['field1'] = 1;
$rmdata['field2'] = 'two';
$rmdata['field3'] = 3;
$rmdata['field4'] = NULL;
$rmdata['field5'] = 'five';
$fields = ARRAY();
$values = ARRAY();
foreach ($rmdata as $field=>$value) {
if (!isset($value)) {
//$value='';
// or
//if($field=='field4') { $value=4; }
// or $values[] = "NULL";
}
if (isset($value)) {
$fields[] = $field;
$values[] = "'".$value."'";
}
}
// if (count($fields) > 0)
$sql_fields = implode(',', $fields);
$sql_values = implode(',', $values);
Related
I want to populate a html table from the results of a SQL query, the fields included will vary depending on choices the user makes so I want to autmatically set the headings etc based on what is in the results of the query. I found the array_to_table function on the website https://inkplant.com/code/array-to-table and it does what I want except the data is duplicated:-
Expected result
Formation Play
A SW
S DL
Actual Result
Formation 0 Play 1
A A SW SW
S S DL DL
I think it may be be to do with the type of array I'm creating but I'm unsure how to alter the code to generate my expected result. I'm not sure if I should create the array in a different way or whether (or how) I should change the function to work with the type of array I have.
#SQL for creating example table
CREATE TABLE `example` ( `id` INT NOT NULL AUTO_INCREMENT , `form` VARCHAR(10) NOT NULL , `playcall` VARCHAR(10) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;
#Sample data
INSERT INTO `example` (`id`, `form`, `playcall`) VALUES (NULL, 'A', 'SW'), (NULL, 'S', 'DL');
#mycode
$sql = "SELECT `form` as 'Formation',`playcall` as 'Playcall' FROM `example` ORDER BY `form` DESC";
$res = execute_db($sql3 $conn);
$caption = "Example table";
echo array_to_table($res,$caption);
#function
function array_to_table($data,$caption,$args=false) {
if (!is_array($args)) { $args = array(); }
foreach (array('class','column_widths','custom_headers','format_functions','nowrap_head','nowrap_body','capitalize_headers') as $key) {
if (array_key_exists($key,$args)) { $$key = $args[$key]; } else { $$key = false; }
}
if ($class) { $class = ' class="'.$class.'"'; } else { $class = ''; }
if (!is_array($column_widths)) { $column_widths = array(); }
//get rid of headers row, if it exists (headers should exist as keys)
if (array_key_exists('headers',$data)) { unset($data['headers']); }
$t="<table style='width:40%' class='w3-table w3-striped w3-bordered'>";
$t .= $caption;
$i = 0;
foreach ($data as $row) {
$i++;
//display headers
if ($i == 1) {
foreach ($row as $key => $value) {
if (array_key_exists($key,$column_widths)) { $style = ' style="width:'.$column_widths[$key].'px;"'; } else { $style = ''; }
$t .= '<col'.$style.' />';
}
$t .= '<thead><tr>';
foreach ($row as $key => $value) {
if (is_array($custom_headers) && array_key_exists($key,$custom_headers) && ($custom_headers[$key])) { $header = $custom_headers[$key]; }
elseif ($capitalize_headers) { $header = ucwords($key); }
else { $header = $key; }
if ($nowrap_head) { $nowrap = ' nowrap'; } else { $nowrap = ''; }
$t .= '<td'.$nowrap.'>'.$header.'</td>';
}
$t .= '</tr></thead>';
}
//display values
if ($i == 1) { $t .= '<tbody>'; }
$t .= '<tr>';
foreach ($row as $key => $value) {
if (is_array($format_functions) && array_key_exists($key,$format_functions) && ($format_functions[$key])) {
$function = $format_functions[$key];
if (!function_exists($function)) { custom_die('Data format function does not exist: '.htmlspecialchars($function)); }
$value = $function($value);
}
if ($nowrap_body) { $nowrap = ' nowrap'; } else { $nowrap = ''; }
$t .= '<td'.$nowrap.'>'.$value.'</td>';
}
$t .= '</tr>';
}
$t .= '</tbody>';
$t .= '</table>';
return $t;
}
EDIT: Based on the tip from https://stackoverflow.com/users/13851118/dhnwebpro I dumped the array to see what it contained:-
Array
(
[0] => Array
(
[Formation] => A
[0] => A
[Playcall] => SW
[1] => Sw
)
[1] => Array
(
[Formation] => S
[0] => S
[Playcall] => DL
[1] => DL
)
)
EDIT2: I changed the format of the query and got it working:-
$res3 = $conn->query($sql3)->fetchAll(PDO::FETCH_ASSOC);
Fetch both was indeed the default and I was able to override that with the above statement.
As #dhnwebpro said PDO was defaulting to PDO::FETCH_BOTH so I overrode it by changing the execution to:-
$res3 = $conn->query($sql3)->fetchAll(PDO::FETCH_ASSOC);
I am trying to read json data and insert it into mysql,
But all the columns seems to match with the values.
Where am i wrong in the below query:
gmrjson.json:
{
"rtVisitInfoOpObjV1":{
"version":"1",
"visitorId":"vis1",
"dwellTime":"0",
"poiId":"poi1",
"srId":"sr1",
"zoneId":"zone1",
"poiProximityConfidence":"0",
"zoneProximityConfidence":"0",
"poiPresenceConfidence":"15",
"zonePresenceConfidence":"0",
"normalizedTime":"1489574975000"
}
}
sample.php:
<?php
//First: read data
$fo=fopen("gmrjson.json","r");
$fr=fread($fo,filesize("gmrjson.json"));
$array=json_decode($fr,true);
//Second: create $values
$rows = array();
foreach ($array['rtVisitInfoOpObjV1'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows); //echo '<pre>';print_r($values);die;
//Save to DB
$hostname = 'localhost';
$username = 'root';
$password = '';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
echo 'Connected to database<br />';
echo "INSERT INTO gmr(version,visitorId,dwellTime,poiId,srId,zoneId,poiProximityConfidence,zoneProximityConfidence,poiPresenceConfidence,zonePresenceConfidence,normalizedTime) VALUES " . $values;
$count = $dbh->exec("INSERT INTO gmr(version,visitorId,dwellTime,poiId,srId,zoneId,poiProximityConfidence,zoneProximityConfidence,poiPresenceConfidence,zonePresenceConfidence,normalizedTime) VALUES " . $values) or die(print_r($dbh->errorInfo(), true));
echo $count; die;
$dbh = null;
echo 'Success<br />';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Below is the description of mysql table
UPDATE- Debugging generated query:
Array
(
[rtVisitInfoOpObjV1] => Array
(
[version] => 1
[visitorId] => vis1
[dwellTime] => 0
[poiId] => poi1
[srId] => sr1
[zoneId] => zone1
[poiProximityConfidence] => 0
[zoneProximityConfidence] => 0
[poiPresenceConfidence] => 15
[zonePresenceConfidence] => 0
[normalizedTime] => 1489574975000
)
)
Connected to database
INSERT INTO gmr(version,visitorId,dwellTime,poiId,srId,zoneId,poiProximityConfidence,zoneProximityConfidence,poiPresenceConfidence,zonePresenceConfidence,normalizedTime) VALUES ('version', '1'),('visitorId', 'vis1'),('dwellTime', '0'),('poiId', 'poi1'),('srId', 'sr1'),('zoneId', 'zone1'),('poiProximityConfidence', '0'),('zoneProximityConfidence', '0'),('poiPresenceConfidence', '15'),('zonePresenceConfidence', '0'),('normalizedTime', '1489574975000')Array
(
[0] => 21S01
[1] => 1136
[2] => Column count doesn't match value count at row 1
)
As you can see your SQL is wrong:
INSERT INTO gmr(version,visitorId,dwellTime,poiId,srId,zoneId,poiProximityConfidence,zoneProximityConfidence,poiPresenceConfidence,zonePresenceConfidence,normalizedTime) VALUES ('version', '1'),('visitorId', 'vis1'),('dwellTime', '0'),('poiId', 'poi1'),('srId', 'sr1'),('zoneId', 'zone1'),('poiProximityConfidence', '0'),('zoneProximityConfidence', '0'),('poiPresenceConfidence', '15'),('zonePresenceConfidence', '0'),('normalizedTime', '1489574975000') ...
it must be:
INSERT INTO gmr(version,visitorId,dwellTime,poiId,srId,zoneId,poiProximityConfidence,zoneProximityConfidence,poiPresenceConfidence,zonePresenceConfidence,normalizedTime) VALUES (1, 'vis1', '0','poi1','sr1' ...)
And you should remove the single quotes arround the numeric values
Your query is actually giving a pair of values instead of single values
instead of doing this:
foreach ($array['rtVisitInfoOpObjV1'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows); //echo '<pre>';print_r($values);die;
do this
foreach ($array['rtVisitInfoOpObjV1'] as $key => $value)
array_push($rows, $value);
$values = implode(",", $rows); //echo '<pre>';print_r($values);die;
Ok here's a function with a nested foreach and i want to check if a key value pair needs to be deleted or updated/inserted. But this one doesn't work, maybe you can see where i go wrong
function insertUserShoppingMetaData($params) {
global $wpdb;
$shopping_meta_table = 'wp_shopping_metavalues';
$wp_user_id = $params['wp_user_id'];
$checkKeyValues = $wpdb->get_results("SELECT meta_shopping_key FROM $shopping_meta_table WHERE wp_user_id = '$wp_user_id'");
//print_r($checkKeyValues);
foreach ($params as $key => $val) {
foreach($checkKeyValues as $check){
//UPDATE OF INSERT
if (($check->meta_shopping_key == $key) AND ($key != "wp_user_id")) {
if (is_array($val)) {
$val = json_encode($val);
}
$shopping_meta_values = array(
'wp_user_id' => $wp_user_id,
'meta_shopping_key' => $key,
'meta_shopping_value' => $val
);
$shopping_meta_where = array('meta_shopping_key' => $key, 'wp_user_id' => $wp_user_id);
$result = $wpdb->get_results("SELECT * FROM $shopping_meta_table WHERE meta_shopping_key = '" . $key . "' AND wp_user_id = '$wp_user_id'");
if (count($result) > 0) {//KEY ALREADY EXISTS FOR USER
$return = $wpdb->update($shopping_meta_table, array('meta_shopping_key' => $key, 'meta_shopping_value' => $val), $shopping_meta_where) . '<br/>';
} else {//KEY IS NEW
$return = $wpdb->insert($shopping_meta_table, $shopping_meta_values) . '<br/>';
}
}//.end $key
else {
//KEY IS NOT SELECTED ANYMORE SO DELETE key value pair row
$qdel = $wpdb->delete($shopping_meta_table,array('wp_user_id'=>$id));
$return = 'Deleted: '.$qdel;
}//.end else {
}//.end foreach checkKeyValue
}//.end each
echo 'Test return: ' . $return;
}
This is my function
$dataArray = array();
$results = mysqli_query($mysqli, ("SELECT CONCAT ('US-', medicare_provider_charge_inpatient_drg100_fy2011.`Provider State`) AS `Provider State`,
sum(ROUND(medicare_provider_charge_inpatient_drg100_fy2011.`Total Discharges`, 2)) AS `Total Discharges`
FROM medicare_provider_charge_inpatient_drg100_fy2011
WHERE medicare_provider_charge_inpatient_drg100_fy2011.`Provider Name` LIKE '%" . $hospital_name . "'
GROUP BY CONCAT ('US-', medicare_provider_charge_inpatient_drg100_fy2011.`Provider State`)"));
while ($row = mysqli_fetch_assoc($results)) {
$dataArray[] = $row;
}
I want to display data in following format
[Provider State, Total Discharges],
[US-AL,2051],
[US-TN,6982]
the dump of $dataArray gives me
Array
(
[0] => Array
(
[Provider State] => US-AL
[Total Discharges] => 2051.00
)
[1] => Array
(
[Provider State] => US-TN
[Total Discharges] => 6982.00
)
)
while ($row = mysqli_fetch_assoc($results)) {
$dataArray[] = $row["Provider State"]. "," .$row["Total Discharges"];
}
That should make your data into a single-dimensional-array.
You just need to work with the data to display the way you want. Print first the column names and then the data. I made this example to work for any number of fields:
// Print the first row with column names
$firstRow = array_keys(reset($dataArray));
$output = array();
foreach($firstRow as $val) {
$output[] = $val;
}
echo '['.implode(',',$output).']'."\n";
// Print all the data
foreach($dataArray as $row) {
$output = array();
foreach($row as $col) {
$output[] = $col;
}
echo '['.implode(',',$output).']'."\n";
}
If you need such structure of array, use this (but it is strange):
$newStructure = array();
$newStructure[] = "Provider State, Total Discharges";
while ($row = mysqli_fetch_assoc($results)) {
$newStructure[] = $row['Provider State'] . ',' . $row['Total Discharges'];
}
If you want to just display data, use this:
echo "Provider State, Total Discharges";
while ($row = mysqli_fetch_assoc($results)) {
echo = $row['Provider State'] . ',' . $row['Total Discharges'];
}
I am trying to put together a function that does the following:
retrieve a JSON encoded string from a form
decode the string to a php array
loop through the generated php array to get the values for each part of the array so that I can update a MySql table
Here is my function code so far:
public function saveTestimonials() {
$existing_testimonials_update = $this->post('data');
$update_array = json_decode($existing_testimonials_update);
foreach ($update_array as $key => $testimonials) {
foreach($testimonials as $key => $value) {
//echo "$key = $value\n";
}
}
$db = Loader::db();
$sql = "UPDATE testimonials SET name=var, content=var WHERE id=var";
$db->query($sql);
$this->redirect('/dashboard/testimonials/');
}
Here is the array stored in the $update_array variable:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Mr. John Doe, Manager, ABC Ltd
[content] => my content 1.
)
[1] => stdClass Object
(
[id] => 2
[name] => Mr. Joe Smith, Manager, ABC Industries
[content] => my content 2.
)
[2] => stdClass Object
(
[id] => 3
[name] => Mr. Mike Smith, Manager, ABC Industries
[content] => my content 3.
)
[3] => stdClass Object
(
[id] => 4
[name] => Ms. Jane Doe, Manager, ABCD Ltd
[content] => my content 4.
)
)
I have got steps 1 and 2 working fine, however I am stuck on step 3.
I still learning PHP and struggle with syntax at times.
I have tried to work this one out on my own and have spent several hours on it, but just can't seem to figure this one out.
Any assistance is very much appreciated.
foreach ($update_array as $key => $testimonials) {
$name = mysql_real_escape_string($testimonials->name);
$content = mysql_real_escape_string($testimonials->content);
$id = intval($testimonials->id);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
}
I'm using something like this. Might be a help to you!
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$array = array_intersect_key( $_POST, array_flip($fieldnames) );
}
}
foreach ($array as $key => $value) {
$value = mysql_real_escape_string($value);
$value = "'$value'";
$updates[] = "$key = $value";
}
$implodeArray = implode(', ', $updates);
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);
mysql_query($sql);
if ($carry == 'yes') {
redirect($carryUrl.'?id='.$_REQUEST['id'].'&'.$table);
} else { echo "Done!"; }
}
These are objects you're dealing with inside of the update_array, so you should be able to access them like this:
$update_array = json_decode($existing_testimonials_update);
foreach ($update_array as $key => $testimonials) {
$testimonials = (array) $testimonials;
foreach($testimonials as $key => $value) {
//echo "$key = $value\n";
}
}
Or, more simply, you can use the arrow operator ($testimonials->name) to access the variables.
You are getting an object from json_decode(). If you pass true as second argument to json_decode() you get an associative array.
http://php.net/manual/de/function.json-decode.php
try something like this
$db = Loader::db();
foreach ($update_array as $key => $testimonials) {
foreach($testimonials as $testimonial) {
// escape data to avoid sql injection
$id = mysql_escape_string($testimonial->id);
$name = mysql_escape_string($testimonial->name);
$content = mysql_escape_string($testimonial->content);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id='$id'";
$db->query($sql);
// TODO check for database error here
}
}
function update($table_name, $myarray, $my_wheres) {
$sql = "Update`".$table_name.
"` SET ";
$i = 0;
foreach($myarray as $key => $value) {
$sql.= $key." = '".$value."'";
if ($i < count($myarray) - 1) {
$sql.= " , ";
}
$i++;
}
if (count($my_wheres) > 0) {
$sql.= " WHERE ";
$i = 0;
foreach($my_wheres as $key => $value) {
$sql.= $key.
" = ".$value;
if ($i < count($my_wheres) - 1) {
$sql.= " AND ";
}
$i++;
}
}
return mysqli_query($sql);
}
Hope, this code can help you. Not try one by one update i think. Think performance.