Displaying query in browser with table - php

Hi there i am using a sqlite database and i have written a query in php that is running. However i cant seem to build a solution that will display the results of this query in the browser (tabular or other). Here is my code. This is the last element of this system so help is appreciated.
Code:
$db = new PDO('sqlite:daypilot.sqlite');
$start = '2018-02-20';
$end = '2018-02-25';
$sql = 'SELECT * FROM events WHERE end > ? AND start < ?';
$stmt = $db->prepare($sql); $stmt->execute([$start, $end]);
$events = $stmt->fetchAll();
[Update] From comment, OP has tried
<table>
<tr>
<th>id</th> <th>name</th> <th>contact</th>
</tr>
<?php foreach ($events as $event): ?>
<tr>
<td><?php echo $event['id'] ?></td>
<td><?php echo $event['name'] ?></td>
<td><?php echo $event['contact'] ?></td>
</tr>
<?php endforeach; ?>
</table>

<?php
$db = new PDO('sqlite:daypilot.sqlite');
$start = '2018-02-20';
$end = '2018-02-25';
$sql = 'SELECT * FROM events WHERE end > ? AND start < ?';
$stmt = $db->prepare($sql); $stmt->execute([$start, $end]);
$events = $stmt->fetchAll(PDO::FETCH_ASSOC);
$table = '<table>';
foreach($events as $event) {
$table .= ' <tr>';
$table .= ' <td>' . $event['column_name'] . '</td>';
// repeat for every column you want to add
$table .= ' </tr>';
}
$table .= '</table>';
echo $table;
?>
Well, this is the simplest (and not the best) way to build the HTML table. You should insert that snippet code in the place where you want the table appears.
I passed PDO::FETCH_ASSOC to fetchAll method to ensure that the data are returned as associative array, then you have to iterate over it and extract the desired columns

Related

Join two table with pdo

I'd like to join two tables in my database. It works fine the 'classic' way but there are a bunch of select query in my script, so I'd like to shorten it...
Here is the joint sql:
SELECT
matches.id, matches.start_time, matches.category_id,
matches.highl, first_team.tid, first_team.t_name,
second_team.tid, second_team.t_name AS ft_name
FROM matches
INNER JOIN teams AS first_team ON matches.first_team_id = first_team.tid
INNER JOIN teams AS second_team ON matches.second_team_id = second_team.tid
ORDER BY matches.id DESC
LIMIT 10
What I want to achive is something like this, but I don't exactly know how to add all the values I copied above.
public function getMatches($table,$conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'';
$sql .= ' FROM '.$table;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("inner_join",$conditions)){
$sql .= ' INNER JOIN '.$conditions['inner_join'];
}
if(array_key_exists("on",$conditions)){
$sql .= ' ON '.$conditions['on'];
}
if(array_key_exists("as",$conditions)){
$sql .= ' AS '.$conditions['as'];
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['limit'];
}
$query = $this->db->prepare($sql);
$query->execute();
if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $query->rowCount();
break;
case 'single':
$data = $query->fetch(PDO::FETCH_ASSOC);
break;
default:
$data = '';
}
}else{
if($query->rowCount() > 0){
$data = $query->fetchAll();
}
}
return !empty($data)?$data:false;
}
}
Here is the output:
<div class="panel-heading">Matches</div>
<table class="table">
<tr>
<th>#</th>
<th>First Team</th>
<th>Second Team</th>
<th>Start Time</th>
</tr>
<?php
include 'inc/functions.php';
$db = new DB();
$matches = $db->getMatches('matches', array('inner_join'=>'teams'), array('as'=>'first_team'), array('on'=>'matches.first_team_id = first_team.tid'), array('inner_join'=>'teams'), array('as'=>'second_team'), array('on'=>'matches.second_team_id = second_team.tid'), array('order_by'=>'matches.id'));
if(!empty($matches)){ $count = 0; foreach($matches as $result){ $count++;?>
<tr>
<td><?php echo $count; ?></td>
<td><?php echo $result['ft_name']; ?></td>
<td><?php echo $result['t_name']; ?></td>
<td><?php echo $result['start_time']; ?></td>
</tr>
<?php } }else{ ?>
<tr><td colspan="4">No entry found!</td>
<?php } ?>
</table>
</div>
With all the honesty, for the life of me I will never ever ever understand, how such wall of PHP arrays
array('inner_join'=>'teams'), array('as'=>'first_team'),
array('on'=>'matches.first_team_id = first_team.tid'),
array('inner_join'=>'teams'),
array('as'=>'second_team'),
array('on'=>'matches.second_team_id = second_team.tid'),
array('order_by'=>'matches.id'));
can be even remotely considered "shorter" than elegant and compact SQL
SELECT
matches.id, matches.start_time, matches.category_id,
matches.highl, first_team.tid, first_team.t_name,
second_team.tid, second_team.t_name AS ft_name
FROM matches
INNER JOIN teams AS first_team ON matches.first_team_id = first_team.tid
INNER JOIN teams AS second_team ON matches.second_team_id = second_team.tid
ORDER BY matches.id DESC
LIMIT 10
Let alone the meaningfulness and readability.
Are you talking of saving yourself typing a few SQL keywords like SELECT or FROM? Seriously? Does it really worth making such a mess out of a meaningful and comprehensible SQL?

How to show add one row of a mysql Table?

Hi i want to show all the data of one row in a table.But i can only show 1 column of the table.
function getAllRecipes(): array {
global $connection;
$query = "SELECT * FROM recipe";
$stmt = $connection->prepare($query);
$stmt->execute();
return $stmt->fetchAll();
}
$recipe = getAllRecipes();
<?php foreach ($recipe as $recip) : ?>
<table>
<tr>
<td><?= **$recip["id"];** ?></td> <----here
</tr>
</table>
This is the result
and i want all of the line:
Do you know how to do it ?
Thanks for your help
Based on "i just want by one line show all the contain of th row" in your "answer".
$arr_values = array_values($recipe);
$html = '<table><tr><th>' . implode('</th><th>', $arr_values) . '</tr></table>';
echo $html;
If you simply only want the name of the keys(columns):
$arr_keys = array_keys($recipe);
$html = '<table><tr><th>' . implode('</th><th>', $arr_keys) . '</tr></table>';
echo $html;

php post value from FOREACH to another page

I've never asked any question here before, but after spending many hours searching for a hint I decided to ask a question.
I have a project at school where I need to create a table from DB for all records for one user, and then create an expanded view for all details for a chosen record.
So far I have:
$user = 'myuser';
$pass = 'mypassword';
$db = new PDO( 'mysql:host=localhost;dbname=mydb', $user, $pass );
$sql = "
SELECT id,login
FROM quotes_taxi
WHERE login='[usr_login]'";
$query = $db->prepare( $sql );
$query->execute();
$results
where 'id' is obviously ID for each record. Then I create a table using FOREACH
<?php foreach( $results as $row ){
echo '<tr>';
echo '<td>'; echo $row['id']; echo '</td>';
echo '<td>'; echo $row['login']; echo '</td>';
echo '<td>'; echo ' View All ';
echo '</td>';
echo "</tr>";
}
?>
the problem I am having is: how can I attached that 'id' within the link (and it needs to be a separate button for each ID), so I can pass it to the view/index.php where I am using
$quote_id = $_GET["id"];
to get all other details of a chosen ID...
I know I have an error in that line, I just cannot figure it what. I also assume it is an easy problem, but I just cannot get my head around it
any help is most appreciated.
Thank you
Try to separate your PHP and HTML that way it will be easier to find errors quickly. Try the following code.
<table>
<tr>
<th>Id</th>
<th>Login</th>
<th>View</th>
</tr>
<?php foreach ($results as $row) : ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['login']; ?></td>
<td> View All </td>
</tr>
<?php endforeach; ?>
</table>
Output
I suggest this function
function AddGetParams()
{
$linkParams="";
foreach($GLOBALS["_GET"] as $key=>$value)
{
$linkParams.="$key=$value&";
}
return $linkParams;
}

Display SQLITE output in column rather than row

At the moment I have the below script which auto generates the table names and row data automatically by looking at a sqlite table. So regardless of if you have 2 or 10 columns this script works.
At the moment the script outputs the results like this:
Output currently appears as a Row
I have tried altering the script so that it outputs the results like below. Can someone assist or guide me in the right direction to achieve this?
Is it possible to output the results of the query in the below format: going down in a column rather than across as a row ?
Output should appear as a Column
<?
$ED = $_GET['ED'];
$ID = $_GET['ID'];
$table_name = $_GET['table'];
?>
<table border="1">
<tr>
<td>
<table>
<?php // Display all sqlite column names for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
if ($table['name'] == "ID") {
echo "<tr><td>" . $table['name'] . "</td></tr>";
} else {
$table_name_header = ucwords(strtolower(str_replace('_', ' ', $table['name'])));
echo "<tr><td>" . $table_name_header . "</td></tr>";
}
}
?>
</table>
</td>
<td>
<table>
<?
// Display all sqlite data for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
// $results = $db->query('SELECT * FROM ADMIN_LOGIN WHERE ID = "57"');
$results = $db->query('SELECT * FROM ' . $table_name . ' WHERE ID = "' . $ID . '"');
while ($row = $results->fetchArray()) {
// echo "<tr>";
$test = $row[0];
foreach ($columns as $col)
echo "<tr><td>" . $row[$col] . "</td></tr>";
}
// echo "</tr>";
?>
</table>
</td>
</tr>
</table>
Modifying the code to the below by putting the data into an combined array and then pulling it back via a loop it will display as required:
<?
// Display all sqlite data for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
// $results = $db->query('SELECT * FROM ADMIN_LOGIN WHERE ID = "57"');
$results = $db->query('SELECT * FROM ' . $table_name . ' WHERE ID = "' . $ID . '"');
while ($row = $results->fetchArray()) {
// echo "<tr>";
$test = $row[0];
foreach ($columns as $col)
$column_data[] = $row[$col];
// echo "<tr><td>" . $row[$col] . "</td></tr>";
}
// echo "</tr>";
?>
<?
$array = $columns;
$array2 = $column_data;
$result = array_combine($array, $array2);
//print_r($result);
?><br><br>
<center>
<table border="0" cellpadding="2" cellspacing="2" color="#4B708D">
<thead>
<?
foreach($result as $key => $value) {
echo "<tr><td bgcolor='#c6d5e1'>$key</td><td bgcolor='#FFFFFF'>$value</td></tr>";
}
?>
</thead>
</table>

PHP MySQL undefined Index and other errors

having trouble getting a script of mine to run correctly, I have 2 undefined index errors and an invalid argument supplied error that for the life of me I can't figure out why I'm getting. the 2 undefined index errors come from these lines.
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
and
if (!is_null($_GET['page']))
and my invalid argument error is this
Warning: Invalid argument supplied for foreach() in
generated from this
<?php foreach ($books as $book) : ?>
my full code between the two classes is this.. any ideas of what I've done wrong? tearing my hair out over this.
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Catalog</title>
</head>
<body bgcolor="white">
<?php
/////////////////////////////////////////////////
//connect to db
/////////////////////////////////////////////////
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
{
$thesort = $_GET['order'];
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY ".$_GET['order'];
}
else
{
$thesort = "courseTitle";
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY $thesort";
}
//if page is null go to first page otherwise query for correct page
if (!is_null($_GET['page']))
{
$query = $query." LIMIT ".($_GET['page']*8-8).", 8";
}
else
{
$query = $query." LIMIT 0, 8";
}
//query result
$books = $db->query($query);
//get number of overall rows
$query2 = $db->query("SELECT * FROM book");
$count = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$count = $count->fetch();
$count = $count['totalRecords'];
?>
<table border =" 1">
<tr>
<th bgcolor="#6495ed"><a href="?order=course">Course #</th>
<th bgcolor="#6495ed"><a href="?order=courseTitle">Course Title</th>
<th bgcolor="#6495ed"><a href="?order=bookTitle">Book Title</th>
<th bgcolor="#6495ed"></th>
<th bgcolor="#6495ed"><a href="?order=price">Price</th>
</tr>
<?php foreach ($books as $book) : ?>
<tr>
<td><?php echo $book['course']; ?></td>
<td><?php echo $book['courseTitle']; ?></td>
<td><?php echo $book['bookTitle']; ?></td>
<td><?php
$bookcourse = $book['course'];
$isbn = $book['isbn13'];
$booklink = "<a href=\"course.php?course=$bookcourse&isbn=$isbn\">";
echo $booklink ;?><img src='images/<?php echo $book['isbn13'].'.jpg'; ?>'></a></td>
<td><?php echo $book['price']; ?></td>
</tr>
<?php endforeach; ?>
</tr>
</table>
<?php
//paging function... not sure if it works correctly?
for ($j=1; $j <= ceil($count/8); $j++)
{ ?>
<a href=<?php echo "?page=".$j."&order=".$thesort; ?>><?php echo $j; ?></a>
<?php
}?>
</body>
</html>
**course.php**
<?php
//get data from index.php
$course = $_GET['course'];
$isbn = $_GET['isbn'];
//connect to db
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
$query = "Select * FROM book, course, author, publisher
WHERE book.isbn13 = $isbn AND book.course = '$course' AND book.course = course.courseID AND book.bookID = author.bookID AND book.publisher = publisher.publisherID
ORDER BY book.bookID";
//query results
$books = $db->query($query);
//error troubleshooting
if (!$books) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
//count the number of rows in the result
$results = $books->fetchAll();
$rowCount = count($book);
//get data from results
foreach($results as $book){
$bookID = $book['bookID'];
$bookTitle = $book['bookTitle'];
$isbn = $book['isbn13'];
$price = $book['price'];
$desc = $book['description'];
$publisher = $book['publisher'];
$courseTitle = $book['courseTitle'];
$courseID = $book['courseID'];
$credits = $book['credit'];
$edition = $book['edition'];
$publishDate = $book['publishDate'];
$length = $book['length'];
$firstName = $book['firstName'];
$lastName = $book['lastName'];
}
if($numrows > 1)
{
foreach ($books as $book)
{
$authorArray[] = $book['firstName'] + ' ' + $book['lastName'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CIS Department Book Catalog</title>
</head>
<body bgcolor=white">
<table border="0">
<tr>
<td>
<img src='images/<?php echo $isbn.'.jpg'; ?>'>
</td>
<td>
<?php
echo "For Course: $courseID $courseTitle ($credits)";
echo "</br>";
echo "Book Title: $bookTitle";
echo "</br>";
echo "Price: $price";
echo "</br>";
echo "Author";
if ($numResults > 1)
{
echo "s:";
for ($i = 0; $i < $numResults; $i++)
{
if ($i!=0)
echo ", $authorArray[i]";
else
echo $authorArrat[i];
}
}
else
echo ": $firstName, $lastName";
echo "</br>";
echo "Publisher: $publisher";
echo "</br>";
echo "Edition: $edition ($publishDate)";
echo "</br>";
echo "Length: $length pages";
echo "</br>";
echo "ISBN-13: $isbn";
?>
</td>
</tr>
<tr>
<td colspan="2">
<?php echo "Description: $desc"; ?>
</td>
</tr>
</table>
</body>
</html>
You should be using isset not is_null to keep it from warning about undefined variables.
$books is never defined It was defined, just incorrectly ... foreach needs it to be an array. You really don't need it anyway, fetch each row into the array with a while loop. (see my example below). You're also redefining $count several times in your query.
And like #Brad said. Use prepared statements and placeholders. Your database will end up hacked with your current code.
EDIT
Answer to your question. query() returns a statement handle. (I've defined it as $sth). fetch() returns a result which you need to pass one of the fetch mode constants (or define it by default earlier with $db->setFetchMode())
To get the books you need to have
$books = array();
$sth = $db->query($query);
while( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
$books[] = $row; // appends each row to the array
}
Here's how your code should look to get a count.
// you're not using the $query2 you defined ... just remove it
$sth = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$result = $sth->fetch(PDO::FETCH_ASSOC);
$count = $result['totalRecords'];
Take a look at:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers Looks like a good guide to give you an in-depth understanding of how to use PDO. Pay special attention to error handling and to prepared statements!

Categories