PHP foreach loop doesnt itterate over objects, and won't start - php

Whenever i try the following loop
if (is_object($ueberweisung)) {
print_r($ueberweisung);
foreach ($ueberweisung as $item)
{
echo '<h1>test</h1>';
echo '<tr>';
//echo '<td>' . $item['ibansender'] . '</td>';
echo '<td>' . $item->$u->getBetrag() . '</td>';
echo '<td>' . $item->u->getBicempfaenger() . '</td>';
echo '<td>' . $item->u->getBicempfaenger() . '</td>';
echo '<td>' . $item->u->getZahlungsreferenz() . '</td>';
echo '<td>' . $item->u->getVerwendungszweck() . '</td>';
echo '<td>' . $item->u->getBetrag() . '</td>';
echo '<td>' . $item->u->getDatum() . '</td>';
echo '<td>';
echo '</tr>';
}
}
it wont jump into that for each loop even though it is definitely a object and is not null$, and i don't know why.
$ueberweisung is filled by another class which is connected to a mysql database
public static function getUberweisungperIban($iban)
{
$db = Database::connect();
$sql = "SELECT * FROM ueberweisung WHERE ibansender = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($iban));
// fetch dataset (row) per ID, convert to Credentials-object (ORM)
$ueberweisung = $stmt->fetchObject('Ueberweisung');
//$ueberweisung = $stmt->fetchAll();
//return $ueberweisung;
Database::disconnect();
//return $ueberweisung;
return $ueberweisung !== false ? $ueberweisung : null;
}

Related

Delete data from mysql database php

Firstly i'm not a developer so bear with me :)
I'm trying to delete a row from a small inventory system we are setting up but its still not allowing me to do anything, this is my current code:
Assigned page:
<?php
$password = 'notTheRealPassword';
$conn = mysql_connect('localhost', 'root', $password);
if(!$conn)
{
die('Error connecting database');
}
mysql_select_db('inventory_system', $conn);
$query= "SELECT * from assigned";
$result=mysql_query($query);
echo "<table border='0' cellpadding='100' class='table-striped'>";
echo "<th>Asset ID</th><th>Asset</th><th>Type</th><th>Manufacturer</th><th>Model</th><th>PC
Name</th><th>Serial Number</th><th>Purchased</th><th>Warranty
End</th><th>OS</th><th>OS
Bit</th><th>CPU</th><th>Memory</th><th>HDD</th><$
while($row = mysql_fetch_array($result))
{
echo '<td>' . $row['asset_id'] . '</td>';
echo '<td>' . $row['asset'] . '</td>';
echo '<td>' . $row['type'] . '</td>';
echo '<td>' . $row['manufacturer'] . '</td>';
echo '<td>' . $row['model'] . '</td>';
echo '<td>' . $row['pc_name'] . '</td>';
echo '<td>' . $row['serial_no'] . '</td>';
echo '<td>' . $row['purchased'] . '</td>';
echo '<td>' . $row['warranty_end'] . '</td>';
echo '<td>' . $row['os'] . '</td>';
echo '<td>' . $row['os_bit'] . '</td>';
echo '<td>' . $row['cpu'] . '</td>';
echo '<td>' . $row['memory'] . '</td>';
echo '<td>' . $row['hdd'] . '</td>';
echo '<td>' . $row['plant'] . '</td>';
echo '<td>' . $row['location'] . '</td>';
echo '<td>' . $row['username'] . '</td>';
echo "<td>Delete</td>";
echo "</tr>";
}
echo "</table>";
mysql_close();
?>
Delete page:
<?php
$password = 'notTheRealPassword';
$conn = mysql_connect('localhost', 'root', $password);
if(!$conn)
{
die('Error connecting database');
}
mysql_select_db('inventory_system', $conn);
$id = (int)$_GET['asset_id'];
mysqli_query($conn,"DELETE FROM assigned WHERE asset_id='".$id."'");
mysqli_close($conn);
header("Location: assigned1.php");
?>
I'm guessing it will be something simple.
Cheers,
There are a few things wrong here:
Your GET variable, the one you put in the link, is id, not asset_id
You should not use GET to modify things in your database; if your browser or a plugin decides to pre-fetch links, your database will be wiped out.
You can't mix mysql apis, use either mysqli or mysql (although not the latter...).
The mysql_* functions are deprecated, you should use PDO or mysqli in combination with prepared statements.
When you echo out lots of html, it is easier to just close the php section and then open it again when you need it; now you have php tags inside the echoed texts. The php / strings / html are not separated correctly.

PDO dynamic Table column name [duplicate]

This question already has an answer here:
How to get column names from PDO's fetchAll result?
(1 answer)
Closed 2 years ago.
I want to create table with PHP. I need to get the name of all column dynamically.
Something like this:
id name username email
. . . .
. . . .
. . . .
. . . .
My code is:
$query = "SELECT * FROM user";
$result = $connection -> prepare($query);
$result -> execute();
echo "<table border=1 width=100%>";
echo '<tr>';
foreach ($result -> fetch(PDO::FETCH_OBJ) as $key => $value)
{
echo "<th>$key</th>";
}
echo '</tr>';
foreach ($result -> fetchAll(PDO::FETCH_OBJ) as $value)
{
echo '<tr>';
echo "<td>".$value -> id."</td>";
echo "<td>".$value-> name."</td>";
echo "<td>".$value-> username."</td>";
echo "<td>".$value -> password."</td>";
echo "<td>".$value -> account."</td>";
echo '</tr>';
}
echo '</table>';
But I lose my first record in second foreach loop, when I fetch my all records.
In fact my first record is $value in the first foreach loop.I want to set that in TD tags, in the second foreach loop.
Try caching the results.
The problem you are having is ->fetch doesn't just grab the keys of the table - it grabs the first row AND the keys.
The following code should work for you :
$query = "SELECT * FROM user";
$result = $connection -> prepare($query);
$result -> execute();
// store results in memory
$headers = '<tr>';
$output = '<tr>';
foreach( $result->fetch(PDO::FETCH_OBJ) as $key=>$value ) {
$headers .= '<th>' . $key . '</th>';
$output .= '<td>' . $value . '</td>';
}
$headers .= '</tr>';
$output .= '</tr>';
foreach ($result -> fetchAll(PDO::FETCH_OBJ) as $value)
{
$output .= '<tr>'
. '<td>' . $value->id . '</td>'
. '<td>' . $value->name . '</td>'
. '<td>' . $value->username . '</td>'
. '<td>' . $value->password . '</td>'
. '<td>' . $value->account . '</td>'
. '</tr>';
}
$output = '<table border="1" width="100%">' . $output . '</table>';
// output result set (full table)
echo $output;
The above example takes all the result set and builds the table on the fly. Since it is storing to memory, this also has the advantage of processing much faster over echo on each partial html element. It outputs the table once it has finished building in a single echo.

Invalid argument supplied for foreach php pdo in hostinger

i hope you understand my problem, i don't know to much english, but i'll try. I've a page in a hostinger and when i generate the code to show the rows, gives me this error:
Warning: Invalid argument supplied for foreach()
Connection code:
public static function conexion() {
try {
$con = new PDO('mysql:host=localhost;dbname=example', 'usuario', 'clave');
return $con;
} catch (PDOException $e) {
return false;
}
}
And:
include 'functions.php';
$con = Functions::conexion();
$sql = 'SELECT * FROM Products p, Prices ps, ProductsPrices pc where p.IDP=pc.IDP AND ps.ID=pc.ID ORDER BY p.IDP ASC';
foreach ($con->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['IDP'] . '</td>';
echo '<td>'. $row['Name'] . '</td>';
echo '<td>'. $row['Description'] . '</td>';
echo '<td style="color: #333;">'. $row['Price'] . '</td>';
echo '<td>' . '<a class="btn" href="update.php?id='.$row['IDP'].'">Edit</a>' . '</td>';
echo '</tr>';
But when i load in localhost there is not any problem, shows the rows.
That is because, you are still setting the host as
$con = new PDO('mysql:host=localhost;dbname=example', 'usuario', 'clave');
change host name to the hostingers provided name
$con = new PDO('mysql:host=hostinger_host_name;dbname=example', 'usuario', 'clave');
hope this helps
try this
<?php
$sql = $con->prepare("SELECT * FROM Products p, Prices ps, ProductsPrices pc where p.IDP=pc.IDP AND ps.ID=pc.ID ORDER BY p.IDP ASC'");
$sq->execute();
$results = $sql->fetchall(PDO::FETCH_ASSOC);
if (count($results > 0)) {
foreach ($con->query($sql) as $row) {
echo '<tr>';
echo '<td>' . $row['IDP'] . '</td>';
echo '<td>' . $row['Name'] . '</td>';
echo '<td>' . $row['Description'] . '</td>';
echo '<td style="color: #333;">' . $row['Price'] . '</td>';
echo '<td>' . '<a class="btn" href="update.php?id=' . $row['IDP'] . '">Edit</a>' . '</td>';
echo '</tr>';
}
}
?>
Add this line before foreach loop
$sql = 'SELECT * FROM Products p, Prices ps, ProductsPrices pc where p.IDP=pc.IDP AND ps.ID=pc.ID ORDER BY p.IDP ASC';
$pdoStatement = $con->query($sql);
$data = $pdoStatement->fetchAll();
foreach($data as $row){
//...
}

PHP While Loop: Second While Loop not showing data

I'm having trouble on While Loop. Here is my code:
<?php
//DISPLAY'S SKILL LIST
$showItemList = $con->query('SELECT * FROM items');
if ($showItemList->num_rows > 0) {
$x=1;
// output data of each row
while($row = $showItemList->fetch_assoc()) {
echo '<tr>';
echo '<td>' . $x++ . '</td>';
echo '<td>' . $row['item_id'] . '</td>';
echo '<td>' . $row['item_name'] . '</td>';
echo '<td>' . $row['item_category'] . '</td>';
echo '<td>' . $row['item_costprice'] . '</td>';
echo '<td>' . $row['item_retailprice'] . '</td>';
echo '<td>' . $row['item_tax'] . '%</td>';
echo '<td>';
$showInHouseQty = $con->query('SELECT SUM(item_quantity) AS TotalQuantityInStock FROM item_inventory_inhouse WHERE item_id="'.$row['item_id'].'"');
while($row = $showInHouseQty->fetch_assoc()) {
echo $row['TotalQuantityInStock'];
}
echo '</td>';
echo '<td>';
$showPharmaQty = $con->query('SELECT SUM(item_quantity) AS TotalPharmaQty FROM item_inventory_inpharmacy WHERE item_id="'.$row['item_id'].'"');
while($row = $showPharmaQty->fetch_assoc()) {
echo $row['TotalPharmaQty'];
}
echo '</td>';
echo '</tr>';
}
}
?>
Well, the problem is, I can't get the result of $row['TotalPharmaQty'];
If you use the same variables in nested while loops as are in the parent while loop, they will overwrite. Change $row in the second and third while loops to $row2 and $row3 respectively, and it should work fine.

Mysqli_fetch_assoc not storing as a session variable

I am trying to store my outputted table from mySQL query into session variables and for use in another page. Here's what I have so far, but I do not get an output:
First page that displays the results of my search:
<?php
session_start();
$personid = ($_POST['personid']) ? $_POST['personid'] : $_GET['personid'];
if (empty($personid)) {
echo 'Please enter some search parameters';
} else {
$sql = "SELECT * FROM persons WHERE 1=1";
if ($personid)
$sql .= " AND personid='" . mysqli_real_escape_string($mysqli,$personid) . "'";
$total_records = mysqli_num_rows(mysqli_query($mysqli,$sql));
$sql .= " ORDER BY surname";
$loop = mysqli_query($mysqli,$sql)
or die ('cannot run the query because: ' . mysqli_error($mysqli));
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>Name</th> <th>Address</th> <th>City</th> <th>Province</th> <th>Postal Code</th> <th>Phone Number</th> <th>Email</th> <th></th></tr>";
while ($record = mysqli_fetch_assoc($loop)) {
echo "<tr>";
/* echo '<td>' . $record['firstname'] . $record['surname'] .'</td>';*/
echo "<td>$record[firstname] $record[surname]</td>";
echo '<td>' . $record['address'] . '</td>';
echo '<td>' . $record['city'] . '</td>';
echo '<td>' . $record['province'] . '</td>';
echo '<td>' . $record['postalcode'] . '</td>';
echo '<td>' . $record['phone'] . '</td>';
echo '<td>' . $record['email'] . '</td>';
echo ("<td>Edit</td>");
echo "</tr>";
}
echo "</table>";
$_SESSION['animals']=$loop;
echo "<center>" . number_format($total_records) . " search results found</center>";
}
?>
Click here to see if sessions work
This then goes to this script:
<?php
session_start();
echo "The results";
while ($record = mysqli_fetch_assoc($_SESSION['animals'])) {
echo "<tr>";
echo "<td>$record[firstname] $record[surname]</td>";
echo '<td>' . $record['address'] . '</td>';
echo '<td>' . $record['city'] . '</td>';
echo '<td>' . $record['province'] . '</td>';
echo '<td>' . $record['postalcode'] . '</td>';
echo '<td>' . $record['phone'] . '</td>';
echo '<td>' . $record['email'] . '</td>';
echo ("<td>Edit</td>");
echo "</tr>";
}
What might the problem be? Thanks in advance.
Session are meant to store primitive data types.
Storing a resulstset into a session is a terrible idea and mostly likely bad for server ressources.
If you really need that data somewhere else in your app just query your database again which is not overly expensive.
I can see the problem that you are trying to store the mysqli resource object to the session.
$loop = mysqli_query($mysqli,$sql)
If you want to store the final html to the session, then create a single variable that holds final html string.
$html = "<table>";
while ($record = mysqli_fetch_assoc($loop)) {
$html .= $record['something'];
// Likewise add other variables to html string.
}
$html . = "</table>";
$_SESSION['animals'] = $html
But if you want the array that holds all the database result then you can do like this
$rows = array();
while ($record = mysqli_fetch_assoc($loop)) {
$rows[] = $record;
}
$_SESSION['animals'] = $rows;
Now you use this session value in another pages and iterate and create html.
Just as other website with session variables, using isset will make the script run smoothly
if (!isset($_SESSION['basket'])){
$_SESSION['basket'] = array();
}
Pascal
multiskillz

Categories