fputcsv, multiple arrays into one row or column - output

I was trying to find answer but i was not successful, please help.
I'm trying to populate multiple rows from data.txt by preg_match to single row or column in data.csv. It needs to be in single array because I need only unique numbers. -> or any other option the get only unique numbers
I was not able to merge arrays to single array and populate it like one array to single row. I will be truly happy for any advice.
Here is my simplified code:
$filename = 'data.txt';
$fupids = array ();
$handle = fopen($filename, "r");
if (!$handle) exit;
while (($line = fgets($handle)) !== false) {
if (preg_match_all('/([0-9]{8})/',$line,$output)) {
$fupid = $output[0];
$file = fopen('data.csv', 'a+');
fputcsv($file, array_unique($output[0]));
}
}
fclose($file);
Here is my simplified data.txt :
10153231,10159512,10159512,10159512
10141703,10160541,10160541
10165815,10158007,10158007
current csv output :
10153231,10159512
10141703,10160541
10165815,10158007
desirable output is only one row or maybe better one column like this:
10153231,10159512,10141703,10160541,10165815,10158007
Thanks all for help.

Perhaps something like this (not tested): (idea: duplicate keys are overwritten with array_merge)
$filename = 'data.txt';
$fupids = [];
if ( false === $hin = fopen($filename, 'r') )
throw new Exception('unable to open input file');
if ( false === $hout = fopen('data.csv', 'a+') )
throw new Exception('unable to open output file');
while ( false !== $fields = fgetcsv($hin) ) {
$fupids = array_merge($fupids, array_flip($fields));
}
fclose($hin);
fwrite($hout, implode(',', array_keys($fupids)));
fclose($hout);

Related

Codeigniter + MySQL - Search containing string

I have column in table of database with value: PL TOFLEX NEGRO/PRETO
I search in my website: TOFLEX PRETO
I need output: PL TOFLEX NEGRO/PRETO
Can someone give me correct query to do this?
I try:
public function searchMaterial($nome)
{
$json = [];
$this->load->database();
if(!empty($this->input->get("q"))){
$this->db->like('nomeMaterial', $nome, 'both');
$query = $this->db->select('idMaterial as id,nomeMaterial as text')
->limit(50)
->get("material");
$json = $query->result();
}
echo json_encode($json);
}
but doesn't work.
You have to split your terms before querying your database.
I assume nomeMaterial is the name of your column.
Try this if you want your column contains BOTH terms :
$search = 'TOFLEX PRETO';
$terms = explode(' ',$search); //will return an array with two strings
foreach($terms as $term){
$this->db->like('nomeMaterial', $term);
}
Or try this if you want your columns contains at least one of the terms :
$search = 'TOFLEX PRETO';
$terms = explode(' ',$search); //will return an array with two strings
foreach($terms as $term){
$this->db->or_like('nomeMaterial', $term);
}

How to add to each query new value and key JSON MySQL read

I have one PHP script that reads from database and then generates JSON format string so that i can read on android device and show my covers and informations. The problem is how to add to each MySQL return index at end key name [SOURCE] = 'MYSOURCE4'?
Here is code that i im using:
while ($row = mysqli_fetch_assoc($qmovies)) {
$rows[] = $row;
$id = $row['id'];
switch(true) {
case $id > 4428:
$src = 'disk3.wuk';
break;
case $id > 2216:
$src = 'disk2.wuk';
break;
default:
$src = 'disk1.wuk';
break;
}
}
array_push($rows['0'], $src);
print json_encode($rows);
So i get this:
[{"id":"4457","title":"hahahah","source":"disk3.wuk"},{"id":"2000","title":"uuuuuu"}]
I need to get this:
[{"id":"4457","title":"hahahah","source":"disk3.wuk"},{"id":"2000","title":"uuuuuu","source":"disk2.wuk"}]
So how to add at end of MySQL read in while loop at each read end id array key and value source?
Thanks.

Add or update MySQL

I don't know how to proceed to do the following thing on my specific table.
Let's say I have the following table param, with 3 columns tck, label, value . tck is my primary key.
The data are coming once everyday. I would like to update the value of the existing tck, and if the data sent contain a new tck, I would like to add it to the table...
I hope I'm clear enough... Thank you for your help.
The code I'm using is the following one :
<?php try {
$bdd = new PDO('mysql:host='.$_ENV['localhost'].';dbname=eip_tasks','root'); } catch(Exception $e) {
die('Erreur : '.$e->getMessage()); }
$data = $_POST['field1'];
$phpArray = json_decode($data, true); foreach ($phpArray as $u) {
//$req = $bdd->prepare('INSERT INTO param (tck, label, value) VALUES(:tck, :label, :value)');
$req = $bdd->prepare('UPDATE param SET value=:value WHERE tck=:tck');
$req->execute(array(
':tck'=>$u['tck'],
':value'=>$u['value']
)); } ?>
Here is the code I'm using now :
<?php
try
{
$bdd = new PDO('mysql:host='.$_ENV['localhost'].';dbname=eip_tasks','root');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$data = $_POST['field1'];
$phpArray = json_decode($data, true);
$sourceTck = array();
foreach ($phpArray as $u) {array_push($sourceTck, $u['tck']);
$req = $bdd->prepare("INSERT INTO param (tck, label, value) VALUES (:tck, :label, :value) ON DUPLICATE KEY UPDATE value=:value");
$req->execute(
array(
':tck'=>$u['tck'],
':label'=>$u['label'],
':value'=>$u['value']
)
);
}
if(count($sourceTck) > 0){
$sourceTckClause = implode("," , $sourceTck);
$req = $bdd->prepare("DELETE FROM param WHERE tck NOT IN ($sourceTckClause)");
$req->execute();
}
?>
Use ON DUPLICATE KEY syntax to update the row instead of insert (if tck was exist):
$req = $bdd->prepare("
INSERT INTO param (tck, label, value)
VALUES
(:tck, :label, :value)
ON DUPLICATE KEY UPDATE value=:value
");
Update: Also don't forget to bind :label. As your comment, To delete a data which would be in the table and not in the source, You should push source tck values to an array and then run a delete query where NOT IN your array:
$sourceTck = array();
foreach ($phpArray as $u) {
array_push($sourceTck, $u['tck']);
$req = $bdd->prepare("
INSERT INTO param (tck, label, value)
VALUES
(:tck, :label, :value)
ON DUPLICATE KEY UPDATE value=:value
");
$req->execute(
array(':tck'=>$u['tck'], ':label'=>$u['label'], ':value'=>$u['value'])
);
}
I found this answer useful to prepare and bind tck values, But for small solution, you can convert array values to int to prevent sql injection in this case:
if(count($sourceTck) > 0){
$sourceTckClause = implode("," , array_map('intval', $sourceTck));
$bdd->query("DELETE FROM param WHERE tck NOT IN ($sourceTckClause)");
}
What you want to do is called an upsert or merge. MySQL does support it.
INSERT INTO param VALUES (:tck, :label, :value)
ON DUPLICATE KEY UPDATE value = :value
-- change :label as well? , label = :label

PHP PDO succinct mySQL SELECT object

Using PDO I have built a succinct object for retrieving rows from a database as a PHP object with the first column value being the name and the second column value being the desired value.
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
I now want to apply it to a function with 2 parameters, the first containing the table and the second containing any where clauses to then produce the same result.
function select($table,$condition){
$sql = "SELECT * FROM `$table`";
if($condition){
$sql .= " WHERE $condition";
}
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
}
The idea that this could be called something like this:
<?php select("options","class = 'apples'");?>
and then be used on page in the same format as the first method.
<?php echo $option['green'];?>
Giving me the value of the column named value that is in the same row as the value called 'green' in the column named field.
The problem of course is that the function will not return the foreach data like that. That is that this bit:
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
cannot return data like that.
Is there a way to make it?
Well, this:
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
Can easily become this:
$sql = "SELECT * FROM `site`";
$site = array();
foreach( $sodb->query($sql) as $row )
{
$site[] = $row;
}
print_r($site);
// or, where 0 is the index you want, etc.
echo $site[0]['name'];
So, you should be able to get a map of all of your columns into the multidimensional array $site.
Also, don't forget to sanitize your inputs before you dump them right into that query. One of the benefits of PDO is using placeholders to protect yourself from malicious users.

Retrieving widget data with MySQL query in WordPress

I've built up multiple dynamic sidebars for front page item manipulation. Each sidebar contains a Text widget, and I want to retrieve each widget's content (according to widget ID) from wp_options.
Basically, the structure is dbName -> wp_options -> option_id #92 contains the following:
a:9:{i:2;a:0:{}i:3;a:3:
{s:5:"title";s:0:"";s:4:"text";s:2:"mainItem";s:6:"filter";b:0;}i:4;a:3:
{s:5:"title";s:0:"";s:4:"text";s:9:"leftThree";s:6:"filter";b:0;}i:5;a:3:
{s:5:"title";s:0:"";s:4:"text";s:10:"rightThree";s:6:"filter";b:0;}i:6;a:3:
{s:5:"title";s:0:"";s:4:"text";s:8:"rightTwo";s:6:"filter";b:0;}i:7;a:3:
{s:5:"title";s:0:"";s:4:"text";s:8:"rightOne";s:6:"filter";b:0;}i:8;a:3:
{s:5:"title";s:0:"";s:4:"text";s:7:"leftOne";s:6:"filter";b:0;}i:9;a:3:
{s:5:"title";s:0:"";s:4:"text";s:7:"leftTwo";s:6:"filter";b:0;}
s:12:"_multiwidget";i:1;}
[Actually all on one line.]
I want to retrieve the following strings:
mainItem
leftOne/leftTwo/leftThree
rightOne/rightTwo/rightThree
What's the syntax for such a query? And how can I add it to the PHP template?
You can pull all of the information about a type of widget from the database like so:
$text_widgets = get_option( 'widget_text' );
There's no need to use mySQL to get this. This will return an array of all the stored widgets of the type 'text'. Then you can loop through this array and do stuff with the internal properties of each like so:
foreach ( $text_widgets as $widget ) {
extract( $widget );
// now you have variables: $mainItem, $leftOne, $leftTwo, etc.
// do something with variables
}
Or, if you already know the ID's of the widgets you want to interact with, you can access the properties like this:
$mainItem = $text_widgets[17]['mainItem'];
Try below code snippet. It return the array of all widgets stored data.
// 1. Initialize variables
$data = '';
$all_stored_widgets = array();
// 2. Get all widgets using - `$GLOBALS['wp_widget_factory']`
$all_widgets = $GLOBALS['wp_widget_factory'];
foreach ($all_widgets->widgets as $w => $value) {
$widget_data = get_option( 'widget_' . $value->id_base );
foreach ($widget_data as $k => $v) {
if( is_numeric( $k ) ) {
$data['id'] = "{$value->id_base}-{$k}";
$data['options'] = $v;
$all_widgets_css[$value->id_base][] = $data;
}
}
}
// 3. Output:
echo '<pre>';
print_r( $all_stored_widgets );
echo '</pre>';
Output: