How to insert data in SQLite table using php? - php

I am working on a php code as shown below which scans the directory ($src_dir) and list all mp4 files.
$src_dir = ('\\\ABCD-ST-001\Audio_Test\podcast\incoming_folder');
$mp4_files = preg_grep('~\.(mp4)$~', scandir($src_dir));
print_r(array_values($mp4_files)); // LineA
Here is the O/P obtained from Line#A:
Array ( [0] => 36031P.mp4 [1] => hello.mp4 )
I am getting two values at Index 0 and Index 1. The 1st is 36031P.mp4 and 2nd is hello.mp4
After that I have wrote a script which insert data in table Podcast_Export.
$db->exec("INSERT INTO Podcast_Export ('House#', 'Status') VALUES ('array_values($mp4_files)', 'Go')"); /* have to place this question on SO*/
On running the above script, I am getting the following data inside the table which is not I want.
array_values(Array) Go
array_values(Array) Go
Problem Statement:
I am wondering what changes I should make in the script above so that it inserts the following data inside the table:
36031 Go
hello Go

You are inserting a string value 'array_values($mp4_files)' , you just need to remove quotes around this value. something like:
$db->exec("INSERT INTO Podcast_Export ('House#', 'Status') VALUES (array_values($mp4_files), 'Go')");
But, if you delete the quotes around array_values then it will insert following array as a string Array ( [0] => 36031P.mp4 [1] => hello.mp4 )
so, its better to use loop here with $mp4_files array and insert your data.
Side Note:
I suggest you to use different name for House# column something like house_no.

Related

PHP stdObject to array that can be used in Google Charts [duplicate]

This question already has an answer here:
Google Table Chart from php created Json
(1 answer)
Closed last year.
I would like to use google charts to visualize some data.
I know from documentation that in order to use google charts the data must be in the following form:
[["C1","C2","C3],[C1V1,C2V1,C3V1],[C1V2,C2V2,C3V3]]
Where c1-c3 are columns one to three and the same of v1-v3 for values.
I currently have data from a query in php in the following form:
Array ( [0] => stdClass Object ( [C1] => C1V1 [C2] => C2V1 [C3] => C3V3 ))
I am getting my data using a simple sql query in laravel:
$live = DB::connection('azure')->select("SELECT C1,C2 FROM tableName");
How can I convert from my data form to the one from the top so that I can use google charts.
I am using PHP so I would like to be able to convert it in that language.
Any help is greatly appreciated!
To format the data in source array $arr to fit your needs, you could use:
<?php
$i=0;
$newArr[0] = array_keys($arr[0]);
foreach($arr as $record) {
$i++;
foreach($record as $col => $val) {
$newArr[$i][] = $val;
}
}
working demo
You need to create the first inner array using the indexes returned from the DB. So if your database query returns an associative array you can use the array_keys function to get an array of all the keys, add that as the first entry in the your main array, then loop through your data returned from the database and add each row as a new entry in your main array.

mysql data insertion line by line

asking for insert multiple lines in one mysql column (with something like line break like show didn't mean inserting data in multiple rows have multiple variables contain different urls like
$var_one = "http://example.com";
$var_two = "http://example.org";
$var_two = "http://example.net";
want to store these values in one mysql column ever value should be in new line refer image describe better
asking for insert multiple lines in one mysql column (with something like line break like didn't mean inserting data in multiple rows
If you trying in php, then you can serialize the data and store as single column in DB.
While retriving data, we can unserialize and get the data as array. Find below example.
<?php
$var = array();
$var[0] = "http://example.com";
$var[1] = "http://example.org";
$var = array("1","2","3");
print_r($var); // Array ( [0] => http://example.com [1] => http://example.org )
$b=serialize($var);
echo $b; // a:2:{i:0;s:18:"http://example.com";i:1;s:18:"http://example.org";}
$c=unserialize($b);
print_r($c); // Array ( [0] => http://example.com [1] => http://example.org )

PHP -- Convert a csv file into a named multidimensional array

I am a bit new to PHP, and I am having some trouble converting a csv file into a multidimensional array, where each dimension has a name. I need to two distinct named array so that I can use them in a preg_replace statement like the below:
$expand_abbrev=preg_replace($contracted_form , $expanded_form , $sentence);
the file content are as follows:
contracted_form,expanded_form
'/a./','in dates ante'
'/abbrev./','abbreviation of'
'/Abbrev./','abbreviations'
'/Abd./','Aberdeen'
'/Aberd./','Aberdeen'
'/Aberdeensh./','Aberdeenshire'
This is so far what I have come up with, but it does not achieve the desired output.
$abbrev_list=file_get_contents('files/abbreviations.text');
$test=str_getcsv($abbrev_list, ",");
$expand_abbrev=preg_replace($contracted_form, $expanded_form, $sentence);
Can anyone help me out with this please ? I have been trying so many times but so far no success.
---- Please allow me to make a clarification, because it seems I might have mislead you. I would like to process a csv file which has two two values per line contracted_form and expanded_form. These two values per line are separated by a comma.
I am not sure how best to approach it, I was thinking perhaps splitting the each line into two arrays like for example each contracted_form is stored in the contracted_from array and each expanded_form is stored in the expanded_form array.
So that preg_replace can replace any instance of contracted_from, encountered in a sentence with its corresponding expanded_form. So for example the following sentence:
Hi sir, I live in a flat in Abd.
So preg_replace(Adb. , Aberdeen, Hi sir, I live in a flat in Abd.) would result in the below.
Hi sir, I live in a flat in Aberdeen.
So from what I understood you want to put each line of the csv into a multi dimensional array, if I understood you wrong please correct me.
Also bare in mind the algorithm below does not take into csv headers into account.
// The Multidimensional Array
$array = array();
$handle = fopen("file.csv", "r");
// If csv if empty, this will not run
while((($data = fgetcsv($handle, null, ',')) !== false)) {
// The "magic" happen here.
temp = array();
$temp["contrated_form"] = $data[0];
$temp["expanded_form"] = $data[1];
array_push($array, $temp);
}
For example if your csv file had the following:
data1,data2
data3,data4
data5,data6
The result of the above algorithm would be:
Array (
[0] => Array (
[contrated_form] => data1
[expanded_form] => data2
)
[1] => Array (
[contrated_form] => data3
[expanded_form] => data4
)
[2] => Array (
[contrated_form] => data5
[expanded_form] => data6
)
)
Tips:
str_getcsv does not know that the first row of your csv file contains your column names.
str_getcsv does not need "," in the statement str_getcsv($abbrev_list, ",") because , is default separator.
Statement $expand_abbrev=... has no idea what you're arguments mean.
You must write a foreach to create array $contracted_form using $test.
You must write a foreach to create array $expanded_form using $test.

Extraing data from json array and separate according to type

So I am currently trying to extract information from a json array using json_decode($result,true). The background here is that there is another php script getting information from a database and it is sending the data to me as json_encoded result.
using print_r($json) i get the following
Array
(
[result] => 1
[message] => Query Successful
[data] => Query Output
[0] => Array
(
//Several values
[test] => test
[Example] => catcatcat
[choice2] => B
)
[1] => Array
[test]=> test
//etc....
I understand we can use a simple for loop to get some stuff to display or in this case I used
for($i=0;$i<=count($json); $i++){
echo $json[$i]['test'];
//etc etc
}
and that will display the value. But what I cant figure out is how to send that to my HTML page as an output as a list.
I am trying to get it to display as following
Test catcatcat B
Test etc etc
--This may be a separate question but for me to learn I want to know if it's possible to actually break down the array and send to html as radio input and turn it into a value to choose from.
Your JSON result is a mixture of 1st level elements and sub-arrays, so you'll need to filter those.
Use a foreach loop like this to output radio buttons:
foreach($json as $current) {
if(!is_array($current))
continue; // skip top level properties that aren't sub arrays
echo '<input type="radio" name="yourradio" value="' . $current['choice2'] . '"> ' . $current['test'] . ' ' . $current['Example'];
}
The value of the radio button and the labels are up to you, but that's the general idea.

PHP SQLite JSON Data Duplication

I have the following PHP code:
$testMessage = "TESTMESSAGE";
$db = new SQLite3('messages.sq3');
$db->exec('CREATE TABLE messages(id INTEGER PRIMARY KEY, message CHAR(255));');
$db->exec("INSERT INTO messages (message) VALUES ('$testMessage');");
$results = $db->query('SELECT * FROM messages ORDER BY id DESC LIMIT 5');
while ($row = $results->fetchArray()) {
print_r($row);
}
The resulting print_r:
Array ( [0] => 1 [id] => 1 [1] => TESTMESSAGE [message] => TESTMESSAGE )
Why is this data duplicated? Is this just the way the array is presented or are there really two copies of TESTMESSAGE string? Inspecting the sqlite file, I only see one actually stored there. I am trying to serialize the output via JSON and this duplication is carrying through to the serialization.
The default is to have the data with both numeric and string keys, merged in the same array.
You need to use $results->fetchArray(SQLITE3_NUM) or $results->fetchArray(SQLITE3_ASSOC) to get numeric and string keys respectively. The default is SQLITE3_BOTH, which I've always hated.
Both $row[1] and $row['message'] will give you the same data. This is because on technique uses the numerical index of the column and the other uses the name. They are both included in the column so that you can use either way to access them. It does not indicate any sort of duplication in the database itself.
Here you can see the documentation and how to tell PHP which version you want. By default it gives you both: http://php.net/manual/en/sqlite3result.fetcharray.php

Categories