Can't print all rows and columns from table - php

This might be one easy question.
I have this table:
Table Image
bairro = neighborhood / preco = price
This is a reference table with prices.
I'm trying to print a table with the neighborhood and the price, but it's not happening as I'd like:
ProblematicTable
As you guys can see, each value is being printed 3 times!
The code is this:
function getInfo()
{
$this->sql = "SELECT * FROM deliverypricestable";
$this->query = $this->mysqli->query($this->sql);
while($this->result = $this->query->fetch_assoc())
{
foreach ($this->result as $key)
{
echo "<tr><td>".$this->result["bairro"]."</td>";//neighborhood
echo "<td>".$this->result["preco"]."</td></tr>";//price
}
}
I know this problem is probably related with the numbers of column on the deliverypricestable, but I'm just learning to code, and lil lost, please help me!

function getInfo()
{
$query = "SELECT * FROM deliverypricestable";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo "<tr><td>".$query->result["bairro"]."</td>";//neighborhood
echo "<td>".$query->result["preco"]."</td></tr>";//price);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
}
You might find - http://php.net/manual/en/mysqli.query.php - useful for documentation on what you are trying to do.

There's no reason to loop twice. The while loop will execute while there is a new row. This new row is stored in $this->result.
function getInfo()
{
$this->sql = "SELECT * FROM deliverypricestable";
$this->query = $this->mysqli->query($this->sql);
while($this->result = $this->query->fetch_assoc()) {
echo "<tr><td>".$this->result["bairro"]."</td>";//neighborhood
echo "<td>".$this->result["preco"]."</td></tr>";//price
}
}
What your code is doing is looping through all the rows and then for each row, you're looping through all the keys (columns) belonging to the row. You have 3 columns and so for each row, you print the values 3 times.

Related

Adding elements to an array from a sql query

I'm trying to add the returned items from the query to the array. I have already searched similar topics, but I have not been able to properly modify the code to get the table I need.
I am trying to add to the array those elements that contain a category (i.e. those that are not empty). I've used the count function before, but to no avail. When I display an array outside the loop, it shows me all the elements, including the empty ones. I suppose I have a poorly constructed conditional. How should I fix the code to make it work properly?
Thanks for any help
public static function findEmpikCategoryFromEmpikCategories($colectionLilante) {
// print_r($colectionLilante);
$empikCategory = [];
$pdo = PDOConnector::getConnection();
foreach($colectionLilante as $collection)
{
// print_r($collection);
$query = "SELECT empik_category FROM `empik_categories` WHERE lilante_category='$collection' LIMIT 1";
// echo "</br>";
$stmt = $pdo->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// print_r($row);
if($row['empik_category'])
{
$empikCategory[] = $row['empik_category'];
}
}
}
// echo "</br>";
print_r($empikCategory);
return $empikCategory;
}

Pushing values and keys to an multidimensional array from the database inside a foreach loop without repetitions

I'm trying to combine two tables from a database, and based on my first one, I want to retrieve some value from the other one, and add them to an array.
Here's my problem:
My first database looks like that:
FIRST TABLE:
id, credit_type, association_name, address, city, province, postal_code, country, cycle_type, cycle_begin, cycle_months
My second database instead looks like that:
SECOND TABLE:
id, association_id, designation_name
The id in my first table matches the association_id in my second table so I don't need an INNER JOIN.
My approach is the following:
<?php
public function my_function()
{
$sql = ee()->db->select('*')->from('first_table')->get();
$data['database'] = [];
if ($sql->num_rows() > 0)
{
foreach($sql->result_array() as $row)
{
$id[] = $row['id'];
$data['database'][] = $row;
}
}
foreach ($data['database'] as $key => $value) {
$association_query = ee()->db->query("SELECT * FROM second_table WHERE id = $id");
foreach($association_query->result_array() as $row_two)
{
if ($association_query->num_rows() > 0)
{
$data['database'][$key]['associations'][] = $row_two['designation_name'];
}
}
}
return ee()->load->view('index', $data, true);
}
?>
The sintax ee()->db->select('*') is a prepared statment from expression engine and it's equal to SELECT * FROM first_table (sanitaized).
So as you can see, I try to pass the value $id, which is an array, to my query. The thing is that as soon as I push the value like that $id[] = $row['id'] I create a nice array, but when I loop through my foreach loop, it multiplies my array in many other arrays so I'm not able to run my query, even if I'm technically in a foreach loop.
Plus, as soon as I try to push the result of my query in my array, let's say changing the id in a static id for instance id=3, I obtain a really weird result, like so many arrays repeated with 1 value, 2 value, 3 value and so on, when I'd like to push my key 'association' only where it is presented in the other table.
If you won't do it on SQL, at least don't execute the second query so many times.
<?php
public function my_function()
{
$assocs = array();
$data = array('database' => array());
$association_query = ee()->db->query("SELECT * FROM second_table");
if ($association_query->num_rows() > 0) {
foreach($association_query->result_array() as $row) {
$assocs[$row['association_id'][] = $row['designation_name'];
}
}
$sql = ee()->db->select('*')->from('first_table')->get();
if ($sql->num_rows() > 0) {
foreach($sql->result_array() as $row) {
$id_check = $row['id'];
if (isset($assocs[$id_check])) {
$row ['associations'] = $assocs[$id_check] ;
}
$data['database'][] = $row;
}
}
return ee()->load->view('index', $data, true);
}
?>
Regards

Create PHP array out of table column

I am trying to create a loop that displays each row in a table. I think I need to make an array out of the PK, but I can't figure out how to do that. Here is my code so far:
$conn = dbConnect('read');
$getData = 'SELECT * FROM table';
$allData = $conn->query($getdata);
if (!$allData) {
$error = $conn->error;
} else {
$data = $allData->fetch_assoc();
$rowId = array($data['PK']);
} while ($rowId <= count($rowId)) {
// code to be run for each row
$rowId++;
}
EDIT: Sorry my question is confusing, I'm new to PHP.
Your question is a bit confusing but I think this is what you are trying to do:
$sql = 'SELECT * FROM table';
$query = $conn->query($sql);
while ($row = $query->fetch_assoc()) {
$data[$row['PK']] = $row;
}
That would iterate over each row, creating an array and using the row's value for column PK as an associative array key.
fetch_assoc() (I assume mysqli here now) doesn't fetch all data from a result, but one row after each other. So you don't need to make an array of $row['PK'], but need to loop over the results.
$conn = dbConnect('read');
$getData = 'SELECT * FROM `table`'; // you would need backticks here, if the table really is called "table" (what you shouldn't do...)
$result = $conn->query($getData); // it's not 'allData', it is a result_set. And be carefull about Case! $getData!=$getdata
if (!$result) {
$error = $conn->error;
} else {
$cnt=0;
while($row = $result->fetch_assoc()) {
// code to be run for each row
// you can display $row['PK'] now:
echo $row['PK'];
// or add that value to something else, whatever you need
$cnt = $cnt+$row['PK'];
// or to have a new array with the values of one table-column:
$columnRows[] = $row['PK'];
}
// now you can use the created array
foreach($columnRows as $PK) {
echo $PK;
}
}

Fetching inside if statement using PDO

Will fetch twice from the same table in same function cause problems?
Im trying to fetch all "items" from the logged user, if the user has no items the function should return false, else, it should return false and echo "nothing", if there are items in the database from the logged user it should return true and echo all the itemnames.
Everything works except the first item gets cutted off, so if user X, has items One, Two, Three, Four, the output will be: TwoThreeFour.
I guess its because im using the Fetch twice from the table, if so, how can i fix it so it works?
Heres the function:
public function myitems() {
$user_user_id = $_SESSION['userSession'];
$stmt = $this->db->prepare("SELECT * FROM item WHERE user_user_id=:user_user_id");
$stmt->execute(array(":user_user_id" => $user_user_id));
if ($itemRow = $stmt->fetch(PDO::FETCH_ASSOC) == 0) {
echo "nothing";
return false;
} else {
while ($itemRow = $stmt->fetch(PDO::FETCH_ASSOC)) {
$item_item_id = $itemRow['item_id'];
$stmt2 = $this->db->prepare("SELECT * FROM picture WHERE item_item_id=:item_item_id");
$stmt2->execute(array(":item_item_id" => $item_item_id));
$imgRow = $stmt2->fetch(PDO::FETCH_ASSOC);
echo $itemRow['itemname'];
}
return true;
}
}
When you fetch once, your pointer will move by one row. So you will not get the first row when iterating by while. You can better fetch all row into a array and count the array to know if data exists. Also I would suggest a JOIN instead of running multiple queries for each item_id. So it can be like this:
$stmt = $this->db->prepare("SELECT * FROM item JOIN picture ON item.item_id = picture.item_item_id WHERE item.user_user_id=:user_user_id");
$stmt->execute(array(":user_user_id" => $user_user_id));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($rows) == 0) {
echo "nothing";
return false;
} else {
foreach ($rows as $itemRow) {
$item_item_id = $itemRow['item_id'];
//You can get your picture details also from $itemRow
echo $itemRow['itemname'];
}
return true;
}
Note: Use LEFT OUTER JOIN in place of JOIN, if you expect some items which will not have any entry in picture table and you want to get the data for the item at least in that case. (Image fields will provide NULL value here)

PHP array not updating

There is probably something dumb I am doing wrong here.
public function get_scores($id)
{
$results = array();
$sql = "SELECT * FROM scores WHERE comp_id = $id";
$rows = $this->db->query($sql)->result();
foreach($rows as $row) {
if($row->confirmed_id) {
$results[$row->uid] += $row->score;
}
}
sort($results);
return $results;
}
So basically what I am trying to do is add all of the users scores in the database and return them in order of rank. confirmed->id is just a check to make sure the score has been confirmed (and thus is addable to their total score). I am basically trying to just make an associative array where the key is the users ID, and the score of each question they have in the database is added on. The query works fine, and $row-uid and $row->score both return the correct thing for every row, but $results[] never has anything added to it. If I even change it just to something silly like $results[3] = 0 at top, and then $results[3]++ or += 1 in the for loop, it doesn't add anything to $results[3].
EDIT: Problem solved. Indeed was something dumb -- confirmed_id was set to null by my partner when he reran our database after I had previously set it all to 1. Thanks guys :)
You are adding to $results[something] before it exists. You need to create it in the first case and then only increment it once it exists.
You need to remove the "+=" operation from the code. Check with this.
public function get_scores($id)
{
$results = array();
$sql = "SELECT * FROM scores WHERE comp_id = $id";
$rows = $this->db->query($sql)->result();
foreach($rows as $row)
if($row->confirmed_id)
$results[$row->uid] = $row->score;
sort($results);
return $results;
}
Your previous operation is similar to
$results[$row->uid] = $results[$row->uid] + $row->score;
So it will not add values to your row.

Categories