MySQL, PHP: split up output table in categories - php

Hello guys,
I've a problem and I hope anybody can help me.
My MySQL database looks like this:
I would like to output these data in a table this way:
My actual code looks like this:
<html>
<body>
<table>
<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include "$root/config.php";
$stmt = $pdo->prepare('SELECT * FROM TestTable ORDER BY name');
$stmt->execute();
$results = $stmt->fetchAll();
if (empty($results)) {
echo 'Error!';
} else {
foreach( $results as $row ) {
echo
"
<tr>
<td class=\"left\">".$row['name']."</td>
<td class=\"right\">".$row['address']."</td>
</tr>
";
}
}
?>
</table>
</body>
</html>
Output looks like this actual:
What to do to have the name of the profession always on top, when the profession is not the same like in the row before?
To sove this issue I've this code:
<?php
$mysqli = new mysqli(host,username,password,db_name);
$sql = "SELECT * FROM TestTable ORDER BY profession, name";
$array = [];
$html = "";
if ($result = $mysqli->query($sql)) {
while($row = $result->fetch_assoc()) {
if (!isset($array[$row['profession']])) {
$array[$row['profession']] = array();
}
$array[$row['profession']][] = $row['name'];
}
}
foreach ($array as $profession => $name) {
$html .= '<p style="font-weight:bold">'.$profession.'</p>';
foreach ($name as $name) {
$html .= '<p class="name">'.$name.'</p>';
}
}
echo $html;
?>
But I need the street in this table too. And I need this code with PDO not MySQLi. I tried to manage this, but without success.
Can anybody help me please?
Greetings,
David.

try something like this:
$stmt = $pdo->prepare('SELECT * FROM TestTable ORDER BY profession, name');
$stmt->execute();
$results = $stmt->fetchAll();
if (empty($results)) {
echo 'Error!';
} else {
$profession = $row['profession'];
foreach( $results as $row ) {
if ($row['profession'] <>$profession) {
echo "<tr><td>". $row['profession']."</td></tr>";
}
echo "<tr>
<td class=\"left\">".$row['name']."</td>
<td class=\"right\">".$row['address']."</td>
</tr>
";
$profession = $row['profession'];
}
}

Related

Search multiple row separate by comma from mysql using php

It is a tracking system like DHL. Tracking shipment number from MySQL database using php form.
but I need it Search multiple row separate by comma from mysql using php.
<?php
$ship=$_POST['Consignment'];
$cons = explode(',',$ship);
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no = '$cons[]'";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Shipment Name: <?php echo $ship_name; ?>
Shipment Phone: <?php echo $phone; ?>
<?php }//while
}//if
else {
echo 'In else....';
?>
Consignment Number not found.Search Again.
<?php
}//else
?>
So I need my search will work with separating by comma(,).
Thanks for helping me.
You can use IN operator in that case.
<?php
$ship=$_POST['Consignment'];
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Hope it will help to you.
change your sql query you have written '$cons[]' in select query which is wrong . after explode you will get data as 1,2,3 so you just need to write variable in query not array and user IN Operator like this.
`$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";`
You should always prepare/sanitize the POST data before using it in MySql query (in terms of security):
<?php
if (isset[$_POST['Consignment']] && !empty($_POST['Consignment'])) {
$ship = $_POST['Consignment'];
$cons = explode(',', $ship);
$cons = array_filter($cons, function($v){
return trim(strip_tags($v));
});
$cons = '"' . implode('","', $cons) . '"';
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN ($cons)";
$result = dbQuery($sql);
$no = dbNumRows($result);
if ($no == 1) {
while ($data = dbFetchAssoc($result)) {
extract($data);
....
}
....
}
?>
Please Use Find IN SET
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'1,2,3,4,5')
Updated
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'$ship')
Note :- $ship Comma Separated Value not an array
I found the Answer:
if(isset($_POST['Consignment'])){
$ship=$_POST['Consignment'];
$shipment= explode(',',$_POST['Consignment']);
$ship = implode("', '",$shipment) ;
$query = "SELECT * FROM `tbl_courier` WHERE `cons_no` IN('$ship')";
$results = $mysqli->query($query);
if($results){
print '<table border="1">';
while($row = $results->fetch_assoc()) {
print '<tr>';
print '<td>'.$row["cons_no"].'</td>';
print '<td>'.$row["customerName"].'</td>';
print '<td>'.$row["customerPhone"].'</td>';
print '</tr>';
}
print '</table>';
// Frees the memory associated with a result
$results->free();
}
else {
echo "Query Not Match";
}
$mysqli->close();
}
Thanks to Answer.

Invalid argument supplied for foreach()

i'm coding a project and have some troubles when the system inform error:
Invalid argument supplied for foreach() in:
foreach($dbh->query($q1) as $row)
and can't get data from the database. How can i fix it, im a newbie, so if i don't understand, please teach me! thanks!
thank for your helps but i still can't fix it
<?php include("top.html"); ?>
<body>
<div id="main">
<h1>Results for <?php echo $_GET['firstname'] . " " . $_GET['lastname'] ?></h1> <br/><br/>
<div id="text">All Films</div><br/>
<table border="1">
<tr>
<td class="index">#</td>
<td class="title">Title</td>
<td class="year">Year</td>
</tr>
<?php
$dbh = new PDO('mysql:host=localhost;dbname=imdb_small', 'root', '');
$q1 = "SELECT id
FROM actors
WHERE first_name = '".$_GET['firstname']."' AND last_name = '".$_GET['lastname']."'
AND film_count >= all(SELECT film_count
FROM actors
WHERE (first_name LIKE'".$_GET['firstname']." %' OR first_name = '".$_GET['firstname']."')
AND last_name = '".$_GET['lastname']."')";
$id = null;
foreach($dbh->query($q1) as $row){
$id = $row['id'] ;
}
if($id == null){
echo "Actor ".$_GET['firstname']." ".$_GET['lastname']."not found.";
}
`
$sql2 = "SELECT m.name, m.year
FROM movies m
JOIN roles r ON r.movie_id = m.id
JOIN actors a ON r.actor_id = a.id
WHERE (r.actor_id='".$id."')
ORDER BY m.year DESC, m.name ASC";
$i = 0;
foreach($dbh->query($sql2) as $row){
echo "<tr><td class=\"index\">";
echo $i+1;
echo "</td><td class=\"title\">";
echo $row['name'];
echo "</td><td class=\"year\">";
echo $row['year'];
echo "</td></tr>";
$i++;
}
$dbh = null;
?>
</table>
</div>
</div>
<?php include("bottom.html"); ?>
</body>
</html>
Check that your query succeeded before iterating on the result:
if (false !== ($result = $dbh->query($d1))) {
foreach($result as $row){
$id = $row['id'] ;
}
}
By the way, I don't understand what you are trying to do with this pointless loop.
You could do this
$st = $dbh->query($q1);
if ( $st ) {
while ( $row = $st->fetch() ) {}
}
Try to make your code more readable
$result = $dbh->query($q1);
foreach($result as $row){$id = $row['id'];}

How to put array data into table?

I need some help with php code.
I want to put data that I get with this query into simple php/html table.
Can you guys help me with this?
<?php
$konekcija=mysqli_connect("111.111.111.111","test","test123","publishers_instagram_accounts");
if (mysqli_connect_errno())
die ("Error:".mysqli_connect_error());
$select = "select * from publishers_instagram_accounts where followed_id <= (select followed_id from publishers_instagram_accounts where username='zika')*1.2 and followed_id >= (select followed_id from publishers_instagram_accounts where username='zika')*0.8";
$stmt = mysqli_prepare($konekcija, $select);
if (mysqli_error($konekcija))
die ("Error:" . mysqli_error($konekcija));
mysqli_stmt_bind_param($stmt, "ss", $trazi1, $trazi2);
if (!mysqli_stmt_execute($stmt))
{
die ("Error:" . mysqli_stmt_error($stmt));
}
else
{
$rezultat = mysqli_stmt_get_result($stmt);
while ($red = mysqli_fetch_array($rezultat, MYSQL_ASSOC))
{
var_dump($red);
}
}
while ($red = mysqli_fetch_array($rezultat, MYSQL_ASSOC)) {
echo "
<table>
<thead>
<td>Username</td>
<td>Password</td>
</thead>
<tbody>
<td>$red['username']</td>
<td>$red['password']</td>
</tbody>
</table>
";
}
Something like this.. Hope it helps you.
Hello #filipche you can try by replacing your 'while' loop with following code:
echo "<table><thead><tr><th>Field 1</th><th>Field 2</th><th>Field 3</th></tr></thead>";
while ($red = mysqli_fetch_array($rezultat, MYSQL_ASSOC)) {
echo "<tbody><tr>";
echo "<td>".$red["field1"]."</td>";
echo "<td>".$red["field2"]."</td>";
echo "<td>".$red["field3"]."</td>";
echo "</tr><tbody>";
}
echo "</table>";
Hope this is what you are looking for...
$qstring = "Your query goes here";
$result = mysql_query($qstring);
if($result)
{
while($row = mysql_fetch_array($result))
{
echo "<table>";
echo "<td>".$row[column name]."</td>";echo "</table>";
}

Displaying a $result as a result for a Search

I have recently completed my search engine but now I have a new challenge.
This following code I am using it to read out values from a callflow table in my DB and displaying them in a table letting u know wether the call was answered yes or no.
if(isset($res))
{
//creating table
echo '<table style="width:1500px; cell-padding:4px; cell-spacing:0; margin:auto;">';
echo'<th>Time</th><th>Answered Y/N</th></th><th>Naam</th><th>Caller ID</th>';
while($result = mysql_fetch_assoc($res))
{
echo '<tr>';
echo '<td>'.$result['statusCalling'].'</td>';
if ($result['statusAnswered'] =="NULL"||$result['statusAnswered'] =="Null" || $result['statusAnswered'] =="null" || $result['statusAnswered'] =="")
{
echo "<td>Not Answered!</td>";
}
else
{
echo "<td>Answered!</td>";
}
echo '<td>'.$result['calleridname'].'</td>'.'<td>'.$result['calleridnum'].'</td>' ;
echo '</tr>';
}
echo '</table>';
}
I need now to display these results in a search engine result!
I tried this but I doesnt work! No idea how else to go about this! Please help!
$output = '';
//collect
if(isset($_POST['asd'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query('SELECT * FROM callflow WHERE statusCalling LIKE "%'.$searchq.'%" OR calleridname LIKE "%'.$searchq.'%" OR calleridnum LIKE "%'.$searchq.'%" OR $results LIKE "%'.$searchq'%"');
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
}else{
while($row = mysql_fetch_array($query)) {
$statusCalling = $row['statusCalling'];
$calleridname = $row['calleridname'];
$calleridnum = $row['calleridnum'];
$results = $row['statusAnswered'];
$id = $row['ID'];
$output .= '<div>'.$statusCalling.' '.$calleridname.' '.$calleridnum.' '.$results.'</div>';
}
}
}
I know that mysql is deprecated, I am learning to program still and i figure if I don't know mysql I cant learn pdo because I don't understand what is what. Please help!
I've worked out the answer and I am posting it here so others can see a way of solving this when they researching for something similar.
<?php
mysql_connect("localhost","root","") or die("Could not connect");
mysql_select_db("voizxl_wachtrij") or die("Could not find Database");
$output = '';
//collect
if(isset($_POST['asd'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query('SELECT * FROM callflow WHERE statusCalling LIKE "%'.$searchq.'%" OR calleridname LIKE "%'.$searchq.'%" OR calleridnum LIKE "%'.$searchq.'%"');
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
}else{
while($row = mysql_fetch_array($query)) {
$statusCalling = $row['statusCalling'];
$calleridname = $row['calleridname'];
$calleridnum = $row['calleridnum'];
$id = $row['ID'];
$output[] = $row;
}
}
}
?>
<?php foreach($output as $o){;
if($o['statusAnswered']){
echo $o['statusCalling'].' Answered: '.$o['calleridname'].' '.$o['statusAnswered'].' '.$o['calleridnum'].'<br />';
}else{
echo $o['statusCalling'].' Not Answered: '.$o['calleridname'].' '.$o['calleridnum'].'<br/>';
}
}?>
<br/><br/><br/>
<?php
Cheers

Return No Record Found Value in PDO::FETCH_OBJ Loop

I need to add an if/then into my PDO::FETCH_OBJ result statement to display a "No Records Found" message if the query is blank.
My working query:
<?php
$command = "SELECT ";
$command .= "id, ";
$command .= "firstName, ";
$command .= "FROM mytable ";
$command .= "ORDER BY sortOrder";
$STH = $DBH->query($command);
$STH->setFetchMode(PDO::FETCH_OBJ);
while($row = $STH->fetch()) { ?>
<tr>
<td><?php echo $row->firstName; ?></td>
</tr>
<?php } ?>
I was able to find similar code that would work for an array, but I can't get it to work with the FETCH_OBJ code above.
This is similar code that illustrates the if/then I would like to implement:
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
print_r($row);
}
} else {
echo "No rows returned.";
}
I'm brand new to PDO so I'm sure it's a context issue, I just can't get it to work.
Set a variable to determine if you found any rows during the loop.
$no_rows_found = true;
while ($row = $STH->fetch() {
$no_rows_found = false;
...
}
if ($no_rows_found) {
echo "No rows found";
}

Categories