Placing database data in multidimensional array - php

For my webshop, I have 1 database with 3 relevant tables.
In order to display the data, I was advised to place the data out of these databases in 3 two dimensional arrays so that I could visualize what I was doing.
However, my only successful attempt of placing the data in the array resulted in the code overwriting itself, only showing the last data in the table.
Can anyone give me some suggestions on how to set up my array in a way that its automatically filled?
<?php
//Create the Multiarrays. 2D, one per table.
// Create connection
$conn = new mysqli(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Open the database
$sql = "SELECT * FROM productwindow";
$result = $conn->query($sql);
//Multiarray locatie 1. When the array starts here, the browser chokes.
if ($result->num_rows > 0) {
//multiarray locatie 2. When the array starts here, the browser also chokes.
while($row = $result->fetch_assoc()) {
$product = array( //multiarray locatie 3. The problem is that the array seems to overwrite itself.
array( //I want PHP to repeat this bit of code for every product in my database, so that I can use it later on.
"ID" => $row["ID"],
"Name" => $row["Productname"],
"Price" => $row["Pricetag"],
"Supply" => $row["Productsupply"],
"Tags" => $row["Tags"],
"Materials" => $row["Materials"],
),
);
}
//Multiarray locatie 2 end woul be placed here
} else {
echo "0 results found. Please check database connection.";
}
//Multiarray locatie 1 end woul be placed here.
$conn->close();
//
echo "<br/>";
$searchby = "Pluimstaart";//The keyword that I used in earlier concepts to filter on specific products. I now need a for loop to procedurally run through the multiarray.
$array_subjected_to_search = $product;
$key = array_search($searchby, array_column($array_subjected_to_search, "Name")); //If it cannot be done via a foreloop, I would need an alternative to "array_search" to show the contents of my array.
var_dump($array_subjected_to_search[$key]);//Used to see if I actually fill my array with data. It only shows the latest data.
//From here on out I build the website like follows;
echo "<br/>product data: " . $product[$key["Supply"]] . ".";
?>
Thank you very much for your feedback!

The $product variable is being overwritten on each loop because you are making it equal a brand new array each time:
$product = array(...
Instead you should be appending elements to the end of an array, using either array_push, or this shorthand:
$product[] = [
"ID" => $row["ID"],
"Name" => $row["Productname"],
"Price" => $row["Pricetag"],
"Supply" => $row["Productsupply"],
"Tags" => $row["Tags"],
"Materials" => $row["Materials"]
];

Try to replace your code of if else code by this code and try
$product[]=array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$product[]["ID"]=$row["ID"];
$product[]["Name"]=$row["Productname"];
$product[]["Price"]=$row["Price"];
$product[]["Supply"]=$row["Supply"];
$product[]["Tags"]=$row["Tags"];
$product[]["Materials"]=$row["Materials"];
}
} else {
echo "0 results found. Please check database connection.";
}

I am not sure if this is what you meant...
$i = 0;
$product = array();
while($row = $result->fetch_assoc()) {
$product[$i] = array(
"ID" => $row["ID"],
"Name" => $row["Productname"],
"Price" => $row["Pricetag"],
"Supply" => $row["Productsupply"],
"Tags" => $row["Tags"],
"Materials" => $row["Materials"],
);
$i++;
}

Related

PHP 'Count' displaying multiple '1's and not a total value

I am calling data from an SQL database in PHP, and I want to be able to count the number of specific values I am pulling from the database, I can pull a specific value, and get say 20 values, when I try to get the 'Count' of these values, it'll display 20 '1's so "11111111111111111111" rather than "20".
I have tried printing it, and entering it into a table, and neither produce the result I want.
My code below:
date_default_timezone_set('Europe/London');
$conn = new mysqli("xxx.xxx.xxx","title","password","title");
if (!$con){
{exit("Connection Failed: " . $con);}
//Connecting to the (DB) Database
}
<?php
if (isset($_POST['submit'])){
?>
<table>
<tr><td><strong>Count</strong></td></tr>
<?php
$start=$_POST['start'];
$end=$_POST['end'];
$sql="SELECT Data.Items ".
//Selecting the required data from the table
$sql="FROM Data ";
//Selecting FROM the Table(s) required
$reports = $con->query($sql);
while ($report = $reports->fetch_object()){
$result = count ($report->Items);
echo count ($result);
echo "<tr><td>".$report->Items."</td></tr>";
}
?>
Its because you are using the count function inside a loop as you fetch each row. Each row has got 1 item(which is not even an array). You have to use
echo $reports->num_rows;
before the while loop instead.
You need to take an array with values and count how much time each value is there in database:
You can do this by using array_count_values()
$items = [];
while ($report = $reports->fetch_object()){
$items[] = $report->Items;
}
if (! empty($items)) {
$numOccurances = array_count_values($items);
foreach ($numOccurances as $val => $count) {
echo "<tr><td>" . $count . " times </td><td> => ".$val."</td></tr>";
}
}
Sample Output:
4 times => item 1
2 times => item 2
1 times => item 3
1 times => item 5
2 times => item 6

Multi-dimensional array to JSON

I am trying to print my data and encode it into JSON. I'm extracting the data from my MySQL database for a quiz. The data that I am trying to extract 1 question, 1 category and 4 options to make a set of quiz. I think I nearly got it how to make it work but I failed to find out how. This was the result check in this link.
Paste the JSON to this link so that you can easily format it. From that JSON data, I want to output like this for each question:
"What is the approximate number of islands that comprise the Philippines?",
"Philippine Geography",
[
{
"quiz_choice_id":"5",
"choice":"7000",
"is_correct_choice":"1"
},
{
"quiz_choice_id":"6",
"choice":"6000",
"is_correct_choice":"0"
},
{
"quiz_choice_id":"7",
"choice":"8000",
"is_correct_choice":"0"
},
{
"quiz_choice_id":"8",
"choice":"9000",
"is_correct_choice":"0"
}
],
This is my code for that:
<?php
/**
* Created by PhpStorm.
* User: Muhammad
* Date: 19/04/2016
* Time: 00:46
*/
require_once('Database_Connect.php');
$questions_query = "SELECT question, quiz_choice_id, choice ,is_correct_choice, category FROM category_question cq, question q, question_choices qc WHERE q.quiz_question_id = qc.quiz_question_id AND q.cat_ques_id = cq.cat_ques_id LIMIT 10";
$questions_query_result = mysqli_query($con, $questions_query) or die("error loading questions");
$questions_results = array();
encode_result($questions_query_result);
function encode_result($result)
{
//$response = array();
$questions = array();
//$choices = array();
while ($r = mysqli_fetch_array($result)) {
//$response[] = $r;
//$questions = array('question' => $r[0]);
$questions[] = $r['question'];
$questions[] = $r[4];
$choices[] = array('quiz_choice_id' => $r[1], 'choice' => $r[2], 'is_correct_choice' => $r[3]);
$questions[] = $choices;
//array_push($questions, $questions['question']);
//array_push($questions_results, $questions);
}
echo json_encode(array('questions'=>$questions));
}
mysqli_close($con);
The design of the database is this:
I can't find a way to make it work because from the database quiz_choice_id,choice, is_correct_choice are in a different table but I combined all into one table as you can see in my SQL statement $questions_query. Please let me know how can I fix this. Thanks in advance.
Do you want the json to look like this?
[ {
"question" : "What is the approximate number of islands that comprise the Philippines?",
"category" : "Philippine Geography",
"choices" : [
{
"quiz_choice_id":"5",
"choice":"7000",
"is_correct_choice":"1"
},
{
"quiz_choice_id":"6",
"choice":"6000",
"is_correct_choice":"0"
},
{
"quiz_choice_id":"7",
"choice":"8000",
"is_correct_choice":"0"
},
{
"quiz_choice_id":"8",
"choice":"9000",
"is_correct_choice":"0"
}
]
},{
..... // next question
}]
You'll have to do something like this, but I have no idea what the results of the query is.
$questions = array();
while ($r = mysqli_fetch_array($result)) {
$key = $r['quiz_question_id']; // you need a key here that is unique to the question, so i think this will do looking at the schema you posted, this will group them in that segment of the array.
if( !isset( $questions[$key] ) ){
//if we never had this question, create the top level in the results
$questions[$key] = array(
'question' => $r['question'],
'category' => $r['category'],
'choices' => array()
);
}
//add in the choices for this question
//on the next iteration, the key is the same so we only do this part
//and append that rows choices to the previous data using $key to match the question
$questions[$key]['choices'][] = array('quiz_choice_id' => $r['quiz_choice_id'], 'choice' => $r['choice'], 'is_correct_choice' => $r['is_correct_choice']);
}
Make sure to add quiz_question_id to your query if this is the questions id, unique identifier. Essentially this will group them together, as this will be the same for each row with that question's choices.
I added string keys to the output, I wouldn't mix using string keys and numbered index. I hope I mapped them out right.
Also I haven't tested this at all, so sorry if there are any syntax errors.

query inside while loop only shows 1 result

i'm making a while loop in php and it all goes well but the problem is that
I don't only want to get the id of the user but also some other stuff that is inside another table, so when I go ahead and make a query inside this while loop and select everything from that second table (where the id is equal to the id of the result from the first query), it only returns 1 result...
So this is the code that I currently have:
public function getFriends($id)
{
global $params;
$get = $this->db->select("{$this->DB['data']['friends']['tbl']}", "*",
array(
"{$this->DB['data']['friends']['one']}" => $id
)
);
if($get)
{
while($key = $get->fetch())
{
$query = $this->db->query("SELECT * FROM {$this->DB['data']['users']['tbl']}
WHERE {$this->DB['data']['users']['id']} = :id",
array(
"id" => $key->{$this->DB['data']['friends']['two']}
)
);
while($row = $query->fetch())
{
$params["user_friends"][] = [
"id" => $key->{$this->DB['data']['friends']['two']},
"name" => $row->{$this->DB['data']['users']['username']},
"look" => $row->{$this->DB['data']['users']['figure']}
];
}
}
}
else
{
$params["update_error"] = $params["lang_no_friends"];
}
}
Thanks in advance!
Please help me out!
In the absence of answers, I don't know what db framework you are using behind the scenese...PDO, mysqli_, or (hopefully not) mysql_. But, in any case, the problem might be that your second query stops the first from continuing. I would use PDO->fetchAll() to get them all...but you say you can't do that...so, looping the first and loading those results into an array is the first thing I would do to see if this is the problem:
public function getFriends($id)
{
global $params;
$get = $this->db->select("{$this->DB['data']['friends']['tbl']}", "*",
array(
"{$this->DB['data']['friends']['one']}" => $id
)
);
$firstResults = array();
if( $get ) {
while( $key = $get->fetch() ) {
$firstResults[] = $key;
}
}
else
{
$params["update_error"] = $params["lang_no_friends"];
}
foreach( $firstResults AS $key )
{
$query = $this->db->query("SELECT * FROM {$this->DB['data']['users']['tbl']}
WHERE {$this->DB['data']['users']['id']} = :id",
array(
"id" => $key->{$this->DB['data']['friends']['two']}
)
);
while($row = $query->fetch())
{
$params["user_friends"][] = [
"id" => $key->{$this->DB['data']['friends']['two']},
"name" => $row->{$this->DB['data']['users']['username']},
"look" => $row->{$this->DB['data']['users']['figure']}
];
}
}
}
If this doesn't work, then we need more data...e.g. what is the query generated? When you run it manually does it return more than one result? If you get rid of the inner-query, does this fix it? etc.
The first step when diagnosing PHP and Mysql issues is to add lines to your code that tell you what each line is doing (declare each time a loop is entered; when each mysql query is run, spit out the query string) so you can narrow down where the problem is. Often this makes you feel stupid in retrospect: "Duh, this query didn't return anything because I formatted the record ID wrong" and so forth.
The code snippet you've provided above isn't super helpful to me. I'm a troubleshooter (not a parser) so I need diagnostic data (not straight code) to be of any more help than this.

Why is my php returning an empty JSON array?

I'm trying to get Json data from Mysql using the following code. I've verified that the columns being selected exist.
I've searched several sites including SO and haven't noticed anything wrong with it.
I've used the example answer given in the following question:
Here
global $mysqli;
$response = array('faqtbl' => array());
// Query Db
$query = "SELECT ticketID, agentName FROM faqtbl";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$response['faqtbl'][] = array(
'ticketID' => $row['ticketID'],
'agentName' => $row['agentName']
// 'name' => $row['name']
// 'number' => $row['number'],
// 'address' => $row['address'],
);
}
}
// I've added this but it doesn't help
//header('Content-Type: application/json');
echo json_encode($response);
If I remove 'agentName' => $row['agentName'] it works and pulls the data in this manner:
{"faqtbl":[{"ticketID":"8"},{"ticketID":"12"},....
I'm using the following: php 5.5.9, apache 2.4.7
Edit Update:
If I use the following within my while loop I get correct Data (without the json encode line):
echo "ticket: " . $row["ticketID"]. " " . $row["agentName"]." " .$row["ticketDate"]. "<br>";
Use json_last_error()
It should tell the problem.
Also you can use json_last_error_msg()
Most possible that your agent field contains some forbidden characters.

error Array to string conversion in php category and subcategory

i have complies php code which gives a array to string conversion error , creating category and sub category tree node but while compiling occurs the error , let me explain where i got the error.
<?php
$conn = mysqli_connect('localhost','res_user','Res#123','res_db');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = " SELECT * , category.id AS catId FROM category INNER JOIN sub_category ON category.id = sub_category.category_id
ORDER BY category.id, sub_category.category_id";
$res = mysqli_query($conn, $sql);
$categoryArray = array();
$oldCatId = 0;
while ($row = mysqli_fetch_assoc($res)) {
if ($row['catId'] != $oldCatId) {
$categoryArray[$row['catId']] = array(
'success' => true,
'category_' . $row['catId'] = array(
'cat_id' => $row["catId"],
'cat_name' => $row['cat_name'],
'cat_img' => $row['cat_img'],
'sub_category' => array(
'sub_id' => $row['category_id'],
'sub_name' => $row['sub_name']
)
)
);
$oldCatId = $row['catId'];
} else {
$categoryArray[$row['catId']]['category_' . $row['catId']]['sub_category'][] = array(
'sub_id' => $row['category_id'],
'sub_name' => $row['sub_name']
);
}
}
echo $categoryArray;
?>
you cant echo array's, as its for outputting one or more strings, you need to print_r or var_dump it, as:
print_r($categoryArray);
The reason for the error message is that the code is trying to display an array with echo. This construct was designed only for displaying strings, not arrays. As long a you provide PHP with a scalar value (boolean, int, string, float) , if the scalar's data type is not a string, PHP will temporarily promote it to being a string.
Normally you need to iterate through an array to display any scalar values of its elements, writing some kind of looping structure. PHP offers a great convenience for working with multidimensional arrays, the function array_walk_recursive() which works with a callback. Here's a variation of the array mentioned in the question to give you an idea about how to use array_walk_recursive() with a callback. Now that PHP supports anonymous functions, we can use one for the callback, as follows:
<?php
$categoryArray[0]['category_0']['sub_category'][] = array(
'sub_id' => 500,
'sub_name' => '1a'
);
array_walk_recursive($categoryArray,
function($value,$key){
echo "$key: $value\n";
});
// output:
sub_id: 500
sub_name: 1a
What's great about array_walk_recursive() is that it will walk through a multidimensional array and the callback displays any available data. Note, the callback needs its parameters in a certain order, the first parameter must correspond to an element's value while the second must represent its key.
Also see live demo here.

Categories