mysqli results not filling in values - php

I've been trying to create an array from a mysqli query that creates a new class 'Book'. When I run this code, it returns the correct number of rows that I have in my database, but it won't display any of the values in the rows. Definitely a newb to a lot of this stuff, any help is really appreciated! Here's the code I'm running. If I just put in a pre-populated array, the code all works great. My problem is getting the values from the database into this array.
$db = new db();
$conn = $db->connect();
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
$thearray = array();
while($array_ar = mysqli_fetch_array($result)){
$thearray[] = array(
$array_ar['username'] => new Book($array_ar['username'], $array_ar['first_name'], $array_ar['last_name']),
);
}
echo 'Rows found: ' . mysqli_num_rows($result);
return $thearray;
Ok, so I var_dump($thearray); and it gives me a multidimensional array, which is why it's returning empty values. I think I need it to return an associative array? Here's what it var_dump($thearray); returns:
array(4) {
[0]=> array(1) {
["joshua"]=> object(Book)#6 (3) {
["title"]=> string(6) "joshua" ["author"]=> string(6) "Joshua" ["description"]=> string(9) "Lundquist"
}
}
[1]=> array(1) {
["matthew"]=> object(Book)#7 (3) {
["title"]=> string(7) "matthew" ["author"]=> string(4) "Matt" ["description"]=> string(3) "Alm"
}
}
[2]=> array(1) {
["roger"]=> object(Book)#8 (3) {
["title"]=> string(5) "roger" ["author"]=> string(5) "Roger" ["description"]=> string(9) "Lundquist"
}
}
[3]=> array(1) {
["norm"]=> object(Book)#9 (3) {
["title"]=> string(4) "norm" ["author"]=> string(4) "Norm" ["description"]=> string(5) "Shupe"
}
}
}
Next I thought I would take a look at what the var_dump(); for my hard-coded array looks like, and it output this (this one works):
array(3) {
["Jungle Book"]=> object(Book)#3 (3) {
["title"]=> string(11) "Jungle Book" ["author"]=> string(10) "R. Kipling" ["description"]=> string(15) "A classic book."
}
["Moonwalker"]=> object(Book)#4 (3) {
["title"]=> string(10) "Moonwalker" ["author"]=> string(9) "J. Walker" ["description"]=> string(7) "another"
}
["PHP for Dummies"]=> object(Book)#5 (3) {
["title"]=> string(15) "PHP for Dummies" ["author"]=> string(14) "Some Smart Guy" ["description"]=> string(18) "and the final one."
}
}
It makes sense to me what's happening, but I'm not sure how to fix my code. Thank you for the help!

Don't Panic's answer got me looking in the right direction. I needed to create an associative array, not a multidimensional array. At first I was accidentally creating the multidimensional array by setting $thearray equal to "array();". By removing that, it filled in the values correctly. Thanks again for the help!
$db = new db();
$conn = $db->connect();
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
$thearray = array();
while($array_ar = mysqli_fetch_array($result)){
$title = $array_ar['username'];
$author = $array_ar['username'];
$description = $array_ar['username'];
$thearray[] = $title = new Book($title, $author, $description);
}
var_dump($thearray);
echo 'Rows found: ' . mysqli_num_rows($result);
return $thearray;

I think this is the problem.
$thearray[] = array(
$array_ar['username'] => new Book(
$array_ar['username'], $array_ar['first_name'], $array_ar['last_name']),
);
It looks like the differences between what you're getting and what you want is 1) You're wrapping the input to $thearray in an extra array() layer, and 2) You won't get string keys like you have in your hard-coded array if you just add the items using [].
Try it like this instead:
// use the username as a key, since that is what it looks like you're using as the 'title'
$thearray[$array_ar['username']] = new Book(
$array_ar['username'], $array_ar['first_name'], $array_ar['last_name']);

Related

PHP influxdb - get measurement name in result

I need to get some data out of my influxdb database.
My current query is:
SELECT value FROM first,second,third WHERE location = 'somewhere' ORDER BY time DESC LIMIT 1
With this result:
array(3) {
[0]=>
array(2) {
["time"]=>
string(30) "2020-02-06T12:44:49.461551353Z"
["value"]=>
float(8.7572979625)
}
[1]=>
array(2) {
["time"]=>
string(29) "2020-02-06T12:44:48.70683539Z"
["value"]=>
float(22.5172978864)
}
[2]=>
array(2) {
["time"]=>
string(30) "2020-02-06T12:44:48.711272393Z"
["value"]=>
float(43.0572978868)
}
}
To process this information i have to use a while loop of some sort, i am unsure since i cannot find an
example of this online anywhere related to this type of data.
But to make the loop useful i need to know what the measurement name is, if i dont have that the result is quite unusable.
I would require this to be:
array(3) {
[0]=>
array(2) {
["time"]=>
string(30) "2020-02-06T12:44:49.461551353Z"
["measurement"]=>
string(5) "first"
["value"]=>
float(8.7572979625)
}
[1]=>
array(2) {
["time"]=>
string(29) "2020-02-06T12:44:48.70683539Z"
["measurement"]=>
string(6) "second"
["value"]=>
float(22.5172978864)
}
[2]=>
array(2) {
["time"]=>
string(30) "2020-02-06T12:44:48.711272393Z"
["measurement"]=>
string(5) "third"
["value"]=>
float(43.0572978868)
}
}
How can i achieve this and process the results correctly?
This solved my issue:
<?php
include "vendor/autoload.php";
$columns = array('first', 'second', 'third');
$cstrings = implode(",",$columns);
$database = InfluxDB\Client::fromDSN(sprintf('influxdb://xxx:xxx#%s:%s/%s', 'localhost', 8086, 'xxxx'));
$client = $database->getClient();
$result = $database->query("SELECT value FROM $cstrings WHERE location = 'xxx' ORDER BY time DESC LIMIT 1");
foreach ($columns as $column) {
$points = $result->getPoints($column);
print($column." ".$points[0]['value']."\n");
}

Change the key of first arrays in three dimensional array in PHP

The following code gives the array below, however I need it formatted differently (stated after the array), so it will work for a javascript function I've already written.
$sql = "SELECT towhich, duedate, amount FROM sales WHERE email = '$email' ORDER BY duedate ASC";
$result = mysqli_query($conn, $sql);
$dbarray = array();
while($row = mysqli_fetch_assoc($result)) {
$dbarray[] = $row;
}
$graph = array();
$cnt = 0;
foreach($dbarray as $key => $values){
$orderdate = explode('-', $values['duedate']);
$month = $orderdate[1];
$graph[$month][$cnt] = array (
0 => $values['amount'],
1 => $values['towhich']
);
$cnt ++;
}
//Now it's grouped by date
Array output:
array(5)
{
["02"]=> array(2)
{
[0]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
[1]=> array(2) { [0]=> string(2) "30" [1]=> string(9) "the co op" }
}
["03"]=> array(1)
{
[2]=> array(2) { [0]=> string(2) "50" [1]=> string(9) "the co op" }
}
["04"]=> array(1)
{
[3]=> array(2) {[0]=> string(2) "40" [1]=> string(9) "the co op" }
}
["05"]=> array(2)
{
[4]=> array(2) {[0]=> string(2) "10" [1]=> string(9) "the co op" }
[5]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
}
["06"]=> array(1)
{
[6]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
}
}
The key index value for array should not be, for example, ['02'], but, being the first in the containing array, [0], like normal; and '03' should be [1].
I've looked around a lot, indeed it helped with what bit of code I've produced, however all answers seem to deal with changing the key value further inside the large array. I'm new with multidimensional arrays, btw. Thanks in advance.
In case you're wondering why I've done it like so, so far, it's because each first array should correspond to a different month; that's why I've ordered by date and all that.
If I got you right, you can use: array_values :
$graph = array_values($graph);
so "02" will be 0, "03" will be 1 , ... etc.
$key in your foreach will be the relative record number that the row occurs in the query.
$graph = array();
$cnt = 0;
foreach($dbarray as $key => $values){
$orderdate = explode('-', $values['duedate']);
$month = $orderdate[1];
$graph[$month][$cnt] = array (
$graph[$key] = array (
$month,
$values['amount'],
$values['towhich']
);
$cnt ++;
}

Spliting Single Column Query values to different php variables

need some help with splitting mysql single column query array into different php variables here.
example:
here's the query, it's pretty simple to be honest.
but, i'm running out of ideas right now.
$string = "select Description from tblQuestion
where Employeeid = '$param'"
$query = $this->db->query($string);
$result = return $query->result_array();
btw, i am using Codeigniter and i tried to var_dump and the results are like this.
array(9) { [0]=> array(1) { ["Description"]=> string(5) "tidak" } [1]=> array(1) { ["Description"]=> string(5) "tidak" } [2]=> array(1) { ["Description"]=> string(5) "tidak" } [3]=> array(1) { ["Description"]=> string(5) "tidak" } [4]=> array(1) { ["Description"]=> string(5) "tidak" } [5]=> array(1) { ["Description"]=> string(5) "tidak" } [6]=> array(1) { ["Description"]=> string(5) "tidak" } [7]=> array(1) { ["Description"]=> string(5) "tidak" } [8]=> array(1) { ["Description"]=> string(5) "tidak" } }
i tried to use json_encode and the result is
[{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"}]
the question is.
how do i convert this stack of arrays into different variables like this?
$var0 = "tidak";
$var1 = "tidak";
$var2 = "tidak";
$var3 = "tidak";
and on and on....
thanks in advance.
cheers!
Put the results in a foreach loop and assign the values to a dynamic variable...
sample code like,
foreach($results as $key=>$val){
$str = 'var'.$key;
$$str = $val['Description'];
}
echo $var0;

SQLite3 returns both indexed and associative array

I have a SQLite query in PHP:
$database = new SQLite3("database.db");
$statement = $database->prepare("SELECT * FROM table");
$result = $statement->execute();
$table = array();
while ($row = $result->fetchArray()) {
array_push($table, $row);
}
var_dump($table);
and it outputs
array(2) {
[0]=> array(4) {
[0]=> int(1)
["event"]=> int(1)
[1]=> string(2) "A1"
["code"]=> string(2) "A1"
}
[1]=> array(4) {
[0]=> int(5)
["event"]=> int(5)
[1]=> string(2) "A2"
["code"]=> string(2) "A2"
}
}
Which is the correct data, but it's outputting all of the information twice: one with an index attached, and one with the column name. Is there any way to pick one or the other? This program needs to be very memory efficient as it will be expanded to having thousands of rows.
This will give you a regular mysql-style assoc array output,
$db = new SQLite3('dbs');
$result = $db->query("SELECT * FROM table");
$assoc_array = array();
while ($dbs_row = $result->fetchArray(SQLITE3_ASSOC)) {
$assoc_array[] = $dbs_row;
}
SQLite's fetchArray function can take a mode parameter. You can use SQLITE3_ASSOC, SQLITE3_NUM, or SQLITE3_BOTH for the desired effect. I guess I should've looked at the documentation before I posted :)

Return an array from a function

I am using the PHP Simple HTML DOM Parser to scrape some results from a page.
At the moment I am having a problem with the function as it is not returning the array "$result".
Any help would be greatly appreciated :)
The result of the array:
array(1) { [0]=> array(6) { ["itemid"]=> string(6) "123456" ["title"]=> string(21) "XXX Prod1" ["unit"]=> string(6) "500ml " ["price"]=> string(4) "2.59" } [1]=> array(6) { ["itemid"]=> string(6) "123457" ["title"]=> string(27) "XXX Prod2" ["unit"]=> string(6) "500ml " ["price"]=> string(5) "10.49" }
Code in question:
function parseItems($html) {
foreach($html->find('div.product-stamp-inner') as $content) { //Finds each individual product on page and extracts its details and stores it into its own array
$detail['itemid'] = filter_var($content->find('a.product-title-link', 0)->href, FILTER_SANITIZE_NUMBER_FLOAT);
$detail['title'] = $content->find('span.title', 0)->plaintext;
$detail['unit'] = $content->find('span.unit-size', 0)->plaintext;
$detail['price'] = filter_var($content->find('span.price', 0)->plaintext, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
$result[] = $detail; //Puts all individual product arrays into one large array
}
//var_dump($result); --Testing purposes
return $result;
}
I guess what you have a piece of code like so
parseItems($html);
When it should be the following because it is returning a variable and needs a variable to hold its returning result
$retval = parseItems($html);

Categories