How to insert arrays into mysql using php - php

I am scraping data and then turning the data into arrays that output as follows:
array(8) {
[0]=> array(8) {
[1]=> string(1) "1"
[2]=> string(8) "Henricho"
[3]=> string(10) "Bruintjies"
[4]=> string(2) "23"
[5]=> string(3) "Agn"
[6]=> string(6) "10.17A"
[7]=> string(4) "-0.2"
[8]=> string(1) "8" }
[1]=> array(8) {
[1]=> string(1) "2"
[2]=> string(5) "Akani"
[3]=> string(7) "Simbine"
[4]=> string(2) "23"
[5]=> string(3) "Agn"
[6]=> string(6) "10.21A"
[7]=> string(4) "-0.2"
[8]=> string(1) "7" }
It is displayed by using var_dump($results);
Is there a simple way to input the data into a sql table using $results?

You need to you something like:
foreach ($results as $value){
$allValues = implode('", "', $value);
//the above line will give us something like ("1", "Henricho"....etc)
$query ='Insert into(col1, col2, col3, col4, col5, col6, col7, col8)
Values("'.$allValues.'")';
//You can now execute your query
echo $query."<BR />";
}
Check Demo Here

The data you used var_dump on to give the above result in my guess would be:
$result = array(
array("1","Henricho","Bruintjies","23","Agn","10.17A","-0.2","8"),
array("2","Akani" , "Simbine" ,"23" ,"Agn", "10.21A","-0.2","7" )
);
lets assume the fields you want to insert data to are id, firstname, lastname, age, anotherfield,anotherfield,anotherfield,anotherfield
foreach ($result AS $innerArray){
// In above $result, each $innerArray is an indexed array
$sqlQuery = 'INSERT INTO `tablename` (`id`, `firstname`, `lastname`, `age`, `anotherfield`, `anotherfield`, `anotherfield`, `anotherfield`) VALUES('.implode(",", $innerArray).')';
// You can now execute your sql query depending on the mysql adapter you are using.
}

Related

Trying to reorganize this PHP array so it's values are toghether by id and easily accesible later

First of all, I couldn't think of any better title, sorry if you find it inapropiate.
I have this function which task is to bring data from 2 databases, modify some of that data, and upload everything to an external API.
The first database accounting has
subscriber_id | amount | zone_id
stored in the table named cdr
The second db billing has stored inside the table billing_zones these values:
zone_id | zone_name
Everything I've done works fine, but the resulting array is not what I expected/wanted.
This is my code:
try {
$conn = new PDO('mysql:host=host;dbname=accounting','user','password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
echo "ERROR: " . $e->getMessage();
}
$destinationId = 0;
$stmt = $conn->prepare('SELECT a.`zone`, b.`source_external_subscriber_id`, SUM(b.`source_customer_cost`) AS total
FROM `billing`.billing_zones a INNER JOIN cdr b
ON a.`id` = b.`source_customer_billing_zone_id`
WHERE destination_account_id = :destinationId
GROUP BY b.`source_external_subscriber_id`, a.`zone`');
$stmt->execute(array('destinationId' => $destinationId));
foreach ($stmt as $row) {
$data[] = $row;
}
for ($i=0; $i < sizeof($data); $i++) {
$sanitizedData[$i] = array(
0 => $data[$i][0],
1 => $data[$i][1],
2 => $data[$i][2]
);
}
/*ATTEMPT TO MAKE THE ARRAY I WANTED - DIDN'T WORK*/
for ($i=0; $i < sizeof($data); $i++) {
while ($sanitizedData[$i] == $sanitizedData[$i-1][1]) {
$newArray[] = array_merge($sanitizedData[$i], $sanitizedData[$i-1]);
}
}
var_dump($sanitizedData);
The result of the code above my ATTEMPT comment is a big array, I will show you a piece of it so you can understand better what I want to do:
[1047]=>
array(3) {
[0]=>
string(27) "Llamadas Moviles nacionales"
[1]=>
string(9) "V30048086"
[2]=>
string(10) "460.440000"
}
[1048]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 902 Nivel 1"
[1]=>
string(9) "V30048086"
[2]=>
string(9) "87.301236"
}
[1049]=>
array(3) {
[0]=>
string(25) "Llamadas Fijos nacionales"
[1]=>
string(9) "W24154073"
[2]=>
string(9) "64.340367"
}
[1050]=>
array(3) {
[0]=>
string(27) "Llamadas Moviles nacionales"
[1]=>
string(9) "W24154073"
[2]=>
string(10) "116.480000"
}
[1051]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 901 Nivel 1"
[1]=>
string(9) "W24154073"
[2]=>
string(9) "62.559759"
}
To clarify:
array[n][0] is the aforementioned zone_name
array[n][1] is the subscriber_id - The id defining the customer
array[n][2] is the SUM() of the amount for that id in that zone.
So the result is that for every id, there are several arrays for each zone.
What I want to do is to group those in a unique array like:
[1051]=>
array(3) {
[0]=>
string(9) "W24154073"
[1]=>
string(28) "Llamadas Premium 901 Nivel 1"
[2]=>
string(9) "62.559759"
[3]=>
string(28) "Llamadas Moviles nacionales"
[4]=>
string(9) "116.480000"
[5]=>
string(28) "Llamadas Fijos nacionales"
[6]=>
string(9) "64.340367"
.
.
.
If there were more
}
As #Misorude pointed out in the comments, maybe using the subscriber_id as key for the main array would be a better solution:
["W24154073"]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 901 Nivel 1"
[1]=>
string(9) "62.559759"
[2]=>
string(28) "Llamadas Moviles nacionales"
[3]=>
string(9) "116.480000"
[4]=>
string(28) "Llamadas Fijos nacionales"
[5]=>
string(9) "64.340367"
.
.
.
If there were more
}
This way, I could later access the array and fetch the info customer by customer, not having in mind how many zones they are in.
I don't know if this is all necessary or if I don't even need any of this to begin with, but I could not think about any way to do it. Maybe I have overthinked this a lot.
If you know how to turn the array I get into the array I want it would be great, but if there is another solution to pass the data easier than this, then please, bring me the light I need.
Thank you for the help, have a great weekend!
After a bit of discussion and clarifying the requirement, this boiled down to inserting two data fields from each record into an array, grouped under an ID value from a third field.
This can be a achieved in quite a simple fashion, like this:
$data = [];
foreach ($stmt as $row) {
// $row[1] is the subscriber_id
$data[$row[1]][] = $row[0]; // $row[0] is zone_name
$data[$row[1]][] = $row[2]; // $row[2] is the sum amount
}
var_dump($data);
The “trick” here is to let PHP take care of the grouping, basically, by providing the grouping id as array key on the first level, $data[$row[1]], and then simply appending new items under that on the second level, using [] = … syntax.

PHP mysql session array

I have a little question.
I have few stored values in session Array. These values are ID's of products.
After that i want to display products from my database, but this is not working propertly for me.
Can someone help me a little? :) (I am still learning :) )
<?php
include 'includes/dbconnect.php';
$orderid = $_SESSION['order'];
foreach ($orderid as $value) {
$sql="SELECT * FROM product WHERE productID LIKE '%$value%'";
$result=$conn->query($sql);
while($row=$result->fetch_assoc()){
echo '<tr>';
echo '<td>'.$row["tag"].'</td>';
echo '<td>'.$row["price"].',- Kč</td>';
echo '<td><img src="images/'.$row["tag"].'.jpg" width=70"></td>';
echo '<td>1</td>' ;
echo '<td>X</td>';
}
}
?>
var_dump($orderid); shows:
array(1) {
["order"]=> array(10) {
[0]=> string(2) "44"
[1]=> string(2) "46"
[2]=> string(2) "44"
[3]=> string(2) "54"
[4]=> string(1) "1"
[5]=> string(2) "44"
[6]=> string(1) "1"
[7]=> string(2) "44"
[8]=> string(2) "47"
[9]=> string(2) "74"
}
}
Just for the purposes of SO, I'll make my comment as an answer:
In the $sql query instead of using LIKE '%$value%'"; use this: LIKE '". $value ."'";
This ensures that we actually get the value of the variable.

Export a array of objects in a table with PHP in codeigniter

I have this array of objects that is looking like this:
Done: array(2) {
[0]=>
object(stdClass)#107 (19) {
["id"]=>
string(1) "6"
["apartament"]=>
string(1) "1"
["nume"]=>
string(5) "SURCA"
["persoane"]=>
string(1) "2"
["mp"]=>
string(4) "37.7"
["retim"]=>
string(5) "19.19"
["incalzire"]=>
string(5) "74.74"
["apacaldamc"]=>
string(1) "3"
["apacaldalei"]=>
string(5) "47.48"
["apacaldadif"]=>
string(4) "3.72"
["aparecemc"]=>
string(1) "8"
["aparecelei"]=>
string(5) "54.73"
["aparecedif"]=>
NULL
["curent"]=>
string(3) "345"
["gaz"]=>
string(3) "2.5"
["administrator"]=>
string(5) "17.01"
["cheltuieliadministrare"]=>
string(4) "2.05"
["acoperis"]=>
string(4) "62.5"
["timp"]=>
string(19) "2017-04-28 10:04:28"
}
[1]=>
object(stdClass)#108 (19) {
["id"]=>
string(1) "7"
["apartament"]=>
string(1) "2"
["nume"]=>
string(8) "ENACHIUC"
["persoane"]=>
string(1) "1"
["mp"]=>
string(5) "37.07"
["retim"]=>
string(3) "9.6"
["incalzire"]=>
string(4) "73.5"
["apacaldamc"]=>
string(1) "3"
["apacaldalei"]=>
string(5) "15.83"
["apacaldadif"]=>
string(4) "3.72"
["aparecemc"]=>
string(1) "2"
["aparecelei"]=>
string(5) "13.68"
["aparecedif"]=>
string(1) "0"
["curent"]=>
string(4) "0.66"
["gaz"]=>
string(4) "1.25"
["administrator"]=>
string(5) "17.01"
["cheltuieliadministrare"]=>
string(4) "2.05"
["acoperis"]=>
string(4) "62.5"
["timp"]=>
string(19) "2017-04-28 10:11:25"
}
}
I get this from a standard query:
$sql ="SELECT * FROM consum WHERE timp BETWEEN '".$fromDate."' AND '".$toDate."'";
$query = $this->db->query($sql);
$databaseOject = $query->result();
I was trying to do something like this:
if ($databaseOject->num_rows > 0) {
echo "<table><tr><th>id</th><th>apartament</th><th>nume</th><th>apartament</th><th>persoane</th><th>mp</th><th>retim</th><th>incalzire</th><th>apacaldamc</th><th>apacaldalei</th><th>apacaldadif</th><th>aparecemc</th><th>aparecelei</th><th>aparecedif</th><th>curent</th><th>gaz</th><th>administrator</th><th>cheltuieliadministrare</th><th>acoperis</th><th>timp</th></tr>";
// output data of each row
while($row = $databaseOject->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["apartament"]."</td><td>".$row["nume"]."</td><td>".$row["persoane"]."</td><td>".$row["mp"]."</td><td>".$row["retim"]."</td><td>".$row["incalzire"]."</td><td>".$row["apacaldamc"]."</td><td>".$row["apacaldalei"]."</td><td>".$row["apacaldadif"]."</td><td>".$row["aparecemc"]."</td><td>".$row["aparecelei"]."</td><td>".$row["aparecedif"]."</td><td>".$row["curent"]."</td><td>".$row["gaz"]."</td><td>".$row["administrator"]."</td><td>".$row["cheltuieliadministrare"]."</td><td>".$row["acoperis"]."</td><td>".$row["timp"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
But I get:
Trying to get property of non-object
Indeed $databaseOject is not a object, it's a array of object, probably that's why I get that error, but how I can make the table in my case - array of objects ? Thank you so much for your time!
The result of $query->result() is an array of StdObjects, you can loop through them using a simple foreach loop.
To access their properties, as they are stdObjects and not array, you need to replace $row['id'] with $row->id, or replace result() with result_array()
I strongly advise you to read the doc on the subject here.
Very simple, you should understand that result helper function for num_rows() should be implemented before the query result() like below:
$sql ="SELECT * FROM consum WHERE timp BETWEEN '".$fromDate."' AND '".$toDate."'";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
$databaseObject = $query->result();
}
So you can check either the result was existed or not before fetch it.
For your references:
https://www.codeigniter.com/userguide3/database/results.html
Hope it helps!

PHP Create Query from array, can't pick out both indexes in foreach statement

I am trying to create a query from a form that passes ID and Details fields, the post array looks like this:
array(2) {
["ID"]=> array(9)
{
[0]=> string(3) "10a"
[1]=> string(3) "10b"
[2]=> string(3) "10c"
[3]=> string(3) "10d"
[4]=> string(3) "10e"
[5]=> string(3) "10f"
}
["Details"]=> array(9)
{
[0]=> string(19) "This is textfield 1"
[1]=> string(17) "This is textfield 2"
[2]=> string(0) ""
[3]=> string(0) ""
[4]=> string(0) ""
[5]=> string(0) ""
}
}
The ID is hardcoded into the page and always passed, the details can be filled out by the user as needed.
if ($_POST['OthProb']['Details'] != '') {
// Catch issue text and assign to variable
foreach ( $_POST['OthProb']['Details'] as $key => $value) {
$id = $_POST['OthProb']['ID']->$key;
$dets = $value;
// Focus on fields with values and join the array values together in a query string
if ($dets != ''){
$string = "INSERT into $table (AccountID, OtherID, ID, Details) VALUES ($_POST[AccountID], $_POST[OtherID], '".$id.", '".$dets."')";
$sql = $DBH->prepare($string);
// $sql->execute();
// var_dump ($id);
}
}
}
creates the following
"INSERT into tbl_problems (AccountID, OtherID, ID, Details) VALUES (80, 80, '10f, 'This is Title issue')"
The 'Details' are outputting correctly, but its cycling all the way through the ID's to the last one, is that because I'm nesting a foreach? What would be the best way to structure the loop?
Try to replace this line:
$id = $_POST['OthProb']['ID']->$key;
by
$id = $_POST['OthProb']['ID'][$key];

Mysql query grouping results in php / moodle

I have a mysql query:
SELECT
mdl_user_info_data.data,
mdl_user.firstname,
mdl_user.lastname,
mdl_grade_grades.itemid,
mdl_grade_items.itemname,
mdl_course.cpd,
mdl_grade_grades.timecreated AS DATE
FROM mdl_user
INNER JOIN mdl_grade_grades ON mdl_user.id = mdl_grade_grades.userid
INNER JOIN mdl_grade_items ON mdl_grade_grades.itemid = mdl_grade_items.courseid
INNER JOIN mdl_course ON mdl_grade_items.courseid = mdl_course.id
INNER JOIN mdl_user_info_data ON mdl_user.id = mdl_user_info_data.userid
WHERE mdl_grade_grades.timecreated >= '1370091991'
AND mdl_grade_grades.timecreated <= '1370524243'
AND mdl_user_info_data.fieldid = 1
The query executes correctly and in phpmyadmin, it shows correctly. there are 4 records.
some of these records have the same usernames eg:
09118514 Elazabi Gillyman 108 Career Management1 1370508988
09118514 Elzaabi Gillyman 108 Career Management2 1370508988
03228812 Magria Martinia 171 NULL 4 1370294859
03228812 Magria Martinia 171 Making Budgeting 1370294859
But when I try and use this in php, there are only 2 records:
09118514 Elazabi Gillyman 108 Career Management2 1370508988
03228812 Magria Martinia 171 Making Budgeting 1370294859
I assume that somehow the records with the same id's are being grouped, but I need to see all the results. What am I doing wrong?
Here is the exact query:
$sql = "SELECT
mdl_user_info_data.data,
mdl_user.firstname,
mdl_user.lastname,
mdl_grade_grades.itemid,
mdl_grade_items.itemname,
mdl_course.cpd,
mdl_grade_grades.timecreated AS DATE
FROM mdl_user
INNER JOIN mdl_grade_grades ON mdl_user.id = mdl_grade_grades.userid
INNER JOIN mdl_grade_items ON mdl_grade_grades.itemid = mdl_grade_items.courseid
INNER JOIN mdl_course ON mdl_grade_items.courseid = mdl_course.id
INNER JOIN mdl_user_info_data ON mdl_user.id = mdl_user_info_data.userid
WHERE mdl_grade_grades.timecreated >= '1370091991'
AND mdl_grade_grades.timecreated <= '1370524243'
AND mdl_user_info_data.fieldid = 1";
$users = $DB->get_records_sql($sql);
var_dump($users);
the var_dump fives this result (please note, I had edited out some fields for readability):
array(5) {
[20038617]=> object(stdClass)#387 (7) { ["data"]=> string(8) "20038617" ["firstname"]=> string(9) "Bhekumuzi" ["lastname"]=> string(7) "Shongwe" ["itemid"]=> string(2) "72" ["itemname"]=> string(21) "Delegating Assessment" ["cpd"]=> string(4) "2.00" ["date"]=> string(10) "1370518594" }
["03429262"]=> object(stdClass)#388 (7) { ["data"]=> string(8) "03429262" ["firstname"]=> string(7) "Shirlee" ["lastname"]=> string(5) "Levey" ["itemid"]=> string(3) "100" ["itemname"]=> string(27) "The IFRS Agenda part 2 quiz" ["cpd"]=> string(4) "0.25" ["date"]=> string(10) "1370431311" }
[10001873]=> object(stdClass)#386 (7) { ["data"]=> string(8) "10001873" ["firstname"]=> string(6) "Bertha" ["lastname"]=> string(11) "Muchineripi" ["itemid"]=> string(3) "103" ["itemname"]=> string(45) "State of the nation analysis 2012 part 3 quiz" ["cpd"]=> string(4) "0.25" ["date"]=> string(10) "1370255012" }
["09118514"]=> object(stdClass)#385 (7) { ["data"]=> string(8) "09118514" ["firstname"]=> string(6) "Elzabi" ["lastname"]=> string(7) "Gillman" ["itemid"]=> string(3) "108" ["itemname"]=> string(17) "Career Management" ["cpd"]=> string(4) "2.00" ["date"]=> string(10) "1370508988" }
["03228812"]=> object(stdClass)#383 (7) { ["data"]=> string(8) "03228812" ["firstname"]=> string(5) "Maria" ["lastname"]=> string(6) "Martin" ["itemid"]=> string(3) "172" ["itemname"]=> string(90) "Managerial Megatrends and Financial Control Quiz - pass the quiz for automatic CPD logging" ["cpd"]=> string(1) "4" ["date"]=> string(10) "1370297204" } }
The moodle documentation at http://docs.moodle.org/dev/Data_manipulation_API#Getting_an_hashed_array_of_records says that the API call you're using (get_records_sql) retrieves a hashed array of records indexed by the first column of your query. The documentation says
The array is indexed by the first column of the fields returned by the
query. Thus to assure consistent data, it appears to be best practice
to ensure that your query include an "id column" as the first field.
"Appears to be best practice?" Heh heh. That's a model of understatement.
So, you're getting one item in your hashed array for each distinct value of mdl_user_info_data.data in the result of your query. The moodle get_records_sql method is functioning as it was designed.
Moodle also offers a recordset API. This is what you want. http://docs.moodle.org/dev/Data_manipulation_API#Using_Recordsets
Try something like this.
$recordset = $DB->get_recordset_sql($sql);
foreach ($recordset as $user) {
// Do whatever you want with this user's record
}
$recordset ->close(); // Don't forget to close the recordset!

Categories