All rows displayed when trying to display rows that contain a string - php

I have some code where I want it to only show rows where there is a certain string in a column. I have a column called "Tags" where it has tags in this format "tag1, tag2" Etc. I want to have links so people can only show products with a certain tag. This is where I run into problems. I can't get it to show rows with certain tags, it shows every row.
<?php
try {
//open the database
$db = new PDO('sqlite:prodDb.sqlite');
$tag = $_POST['tag'];
if (isset($tag)) {
$result = $db->query('SELECT * FROM Products WHERE instr(Tags, $tag) > 0');
} else {
$result = $db->query('SELECT * FROM Products ');
}
//now output the data to a simple html table...
$result = $db->query('SELECT * FROM Products');
foreach ($result as $row) {
print "" . $row['Id'] . "<br />";
print "" . $row['Name'] . "<br />";
$tags = explode(', ', $row['Tags']);
foreach ($tags as $tag) {
print "Tag: " . $tag . "<br />";
}
print "" . $row['Link'] . "<br />";
print "" . $row['Screenshot'] . "<br />";
print "" . $row['Download'] . "<br />";
}
// close the database connection
$db = NULL;
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
Any ideas where I went wrong?

Get rid of the $db->query line here:
//now output the data to a simple html table...
$result = $db->query('SELECT * FROM Products');
You're discarding the results from the query that matched the tag, and using this query that returns all products.
In the query with the tag, you have a syntax error, because you need quotes around the string. It would be better to use a prepared query:
$stmt = $db->prepare('SELECT * FROM Products WHERE INSTR(Tags, :tag)');
$stmt->execute(array(':tag' => $tag));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Also, if you have all the tags in a single column, you have a poor table design. You should normalize your data by moving the tags into a separate table, with one row per tag for each product.

It probably doesn't work because here:
//now output the data to a simple html table...
$result = $db->query('SELECT * FROM Products');
You are simply selecting all products and ignoring the previous query/filter.

Related

Display the information from a SQLite Query in the browser

So, I'm trying to use PHP in order to query an sqlite database, I have no problem with the connection or with the query itself, however, I don't know what I could do in order to display the data in a clean way, or even put it inside an HTML table. The code I'm working with right now is:
<?PHP
$connection = new SQLite3('my_db.db');
if($connection){
echo "Connected\n";
}
$results = $connection->query('SELECT * FROM Meter1');
while($row=$results->fetchArray()){
var_dump($row);
}
?>
After you have done a $row = fetchArray() the variable $row is a array containing the data returned from your query in the form of an Array. If you add SQLITE3_ASSOC it will be an Associative Array where the keys are the names of the database columns.
So lets assume your table has the columns id, name, dob then this would be how you get to that column data
<?php
$connection = new SQLite3('my_db.db');
if($connection){
echo "Connected\n";
}
$results = $connection->query('SELECT * FROM Meter1');
while($row=$results->fetchArray(SQLITE3_ASSOC)){
echo 'id = ' . $row['id'] . '<br>';
echo 'name = ' . $row['name'] . '<br>';
echo 'Date of Birth = ' . $row['dob'] . '<br>';
}
?>
So if you want the data in a table its just a case of wrapping the HTML around that while loop like this
echo '<table>';
echo '<tr><td>id</td><td>name</td><td>Date of Birth</td></tr>';
while($row=$results->fetchArray(SQLITE3_ASSOC)){
echo '<tr>';
echo "<td>$row[id]</td><td>$row[name]</td><td>$row[dob]</td>";
echo '</tr>';
}
echo '</table>';

While statement only echoing last result

I am very new, I am having a small problem.. I cannot get my while loop to loop through my entire result set, it is only retrieving the last result set, and i am expecting 2 result sets.
I echo'd my query out to see the result i would get, and the echo printed out both the result sets i want to print out. Leading me to the confusion my while loop is the issue.
I have looked through lost on here but the posts i have seen it was a problem with their query, rather then their while loop. Any assistance would be greatly appreciated. I have used different posts on here to construct my query, but i don't know where to go from here.
date_default_timezone_set("Europe/London");
$date = jddayofweek(unixtojd());
$sql = "SELECT * FROM tbl WHERE ID = $ID AND Day = $date";
$results = $conn->query($sql);
echo $sql;
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$output = "Test2" . "</br>" . $row["time"] . "</br>";
}
} else {
$output = $output . "test1" . "</br>";
}
}
You are not echoing anything inside your while loop.
I think you need to concatenate the variable $output.
while ($row = $results->fetch_assoc()) {
$output .= "Test2" . "</br>" . $row["time"] . "</br>";
}
You are overwritting the content of $output on every iteration of the loop, you should use the concatenation operator to attach the value of the content to the end of the string.
$output .= "Test2" . "</br>" . $row["time"] . "</br>";

Is it possible to wrap looping PHP output in tags?

everyone. I'm having a bit of a PHP conundrum here and I couldn't find a good answer that already existed. You see, I'm working on a project where I have to take a classmate's discography website and revamp it with PHP, to where, instead of having the album covers and tracklists hard-coded in, it would query the database for them. My problem is that I have to keep the general style of his site intact, and I'm having trouble doing that. Basically his styles depend on having the album cover, name, and tracklists in div tags, and the style he's got in place is achieved through both Bootstrap and his own, custom CSS stylesheet.
Before I start to ramble, my question is: is there any way to wrap looping output in HTML tags? I need to get the album cover, album name, and tracklists in a div tag, but only the tracklists loop. Here is the code I have in place to query the database:
<?php
require ('mysqli_connect.php');
// Connect to database server
mysql_connect("localhost", "admin", "instructor") or die(mysql_error());
// Select database
mysql_select_db("phprediscography") or die(mysql_error());
// SQL query
$q = "SELECT DISTINCT albums.albumname, albums.albumID, albums.coverart
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID"; //select UNIQUE results from database
$t = "SELECT trackname FROM tracks WHERE albumID = 1";
$b = "SELECT trackname FROM tracks WHERE albumID = 2";
$n = "SELECT trackname FROM tracks WHERE albumID = 3";
$r = "SELECT trackname FROM tracks WHERE albumID = 4";
$result = mysqli_query($dbcon, $q);
$result1 = mysqli_query($dbcon, $t);
$result2 = mysqli_query($dbcon, $b);
$result3 = mysqli_query($dbcon, $n);
$result4 = mysqli_query($dbcon, $r);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { //loop through database to get each album
echo '<img class="img-responsive" src=' . $row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
if ($row['albumID'] == 1) {
foreach($result1 as $row1) { //loop through tracks and output to page
echo '<p>' . $row1['trackname'] . '</p>';
}
}
if ($row['albumID'] == 2) {
foreach($result2 as $row2) { //loop through tracks and output to page
echo '<p>' . $row2['trackname'] . '</p>';
}
}
if ($row['albumID'] == 3) {
foreach($result3 as $row3) { //loop through tracks and output to page
echo '<p>' . $row3['trackname'] . '</p>';
}
}
if ($row['albumID'] == 4) {
foreach($result4 as $row4) { //loop through tracks and output to page
echo '<p>' . $row4['trackname'] . '</p>';
}
}
}
// Close the database connection
mysql_close();
?>
If I need to post anything else, let me know, this is my first-ever question so I'm just kind of feeling it out.
By doing your $t = "SELECT trackname FROM tracks WHERE albumID = #"; and if($row['albumID']==#) you are essentially still hardcoding similar to your friend. Just do 1 query, where you join all the tracks. Then when looping, group by the albumname -
<?php
require('mysqli_connect.php');
// SQL query
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$current_albumID = ""; //create current albumID var to be used below.
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){//loop through database to get each album
if($row['albumID'] != $current_albumID){
echo '<img class="img-responsive" src='.$row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
$current_albumID = $row['albumID']; // set current albumID to this albumID
}
echo '<p>' . $row['trackname'] . '</p>';
}
?>
Try something like this instead: Get all the data you're after in your first query, then use php to process that into your output:
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$lastAlbumId = null;
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
if ($lastAlbumId != $row['albumID']) {
echo '<img class="img-responsive" src="'.htmlentities($row['coverart']).'"><br />';
echo '<h2>'.htmlentities($row['albumname']).'</h2><br />';
}
echo '<p>'.htmlentities($trackname).'</p>';
$lastAlbumId = $row['albumID'];
}
A few things to note:
I added use of htmlentities to escape the user data so malicious people can't type in HTML somewhere and have it appear on your site. This is something you should do almost everywhere you're displaying data from a database in a html site, except for very rare cases where you know what you're doing.
You probably don't need those <br /> tags - <h2> is a block level element so it'll force itself onto it's own line anyway (unless there's some silly CSS rules somewhere).
Also note - the above code is untested - typed straight into browser. There may be some syntax errors - let me know if you see any problem and I'll happily edit the answer. (or you can suggest an edit).

List all table contents from generated list of table column names

I have got one piece of code which gives me a list of all the column names for a specific table. Can i use this list as my $row['VARIABLE'] instead of specifying every row?
The current output of the table names can be seen here this is the second paragraph of text, the first ones are my table names (USERS, ADMIN_LOGIN)
I am working on making a small script which will list all the table contents of a table but it is likely the table will change often so i want a script which can auto generate the table of contents without me having to manually re-enter it all as i have done in the second piece of code below?
Thanks guys
<?php
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
echo $table['name'] . '<br />';
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
echo "ID = ". $row['ID'] . "\n";
echo "USERNAME = ". $row['USERNAME'] ."\n";
echo "AGE = ". $row['AGE'] ."\n";
echo "LOCATION = ".$row['LOCATION'] ."\n\n";
echo "ANYTHING_ELSE = ". $row['ANYTHING_ELSE'] . "\n";
echo "EMAIL = ". $row['EMAIL'] ."\n";
echo "PROFILE_APPROVED = ". $row['PROFILE_APPROVED'] ."\n";
echo "NUMBER_OF_BATTLES = ".$row['NUMBER_OF_BATTLES'] ."\n\n";
echo "TOTAL_WINS = ".$row['TOTAL_WINS'] ."\n\n";
}
?>
Yes, you can use variables for the index values of an array. For example,
$row = array('col_name' => 'column value');
$index = 'col_name';
echo $row[$index]; // Equivalent to $row['col_name']. Prints "column value"
You should be able to accomplish what you want pretty easily using the above logic. Basically just store the column names from the first query into an array, then loop through that array to get the column names each time you print a row.
Give this a try:
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
foreach ($columns as $col)
echo $col . " = " . $row[$col] . "\n";
}
I use the following in order to get a list of columns names in the order they are defined in the table. I use it to populate an insert/select when preserving data.
sel columnname
from dbc.columns
where databasename='databasename'
and tablename='tablename'
order by columnid;

How to fix this simple MySQL display order issue

I'm very new to MySQL so I need some help please,
I have a table called "posts", this table has the following columns:
id - this is auto increment and primary key
title
content
I have a PHP page where I want to display all the posts from the database table. I want the title to show first and then the post content followed by the title of the next post and it's post content and so on... However if I do this:
$select = mysql_query("SELECT * FROM posts ORDER BY id DESC");
while ($result = mysql_fetch_array($select))
{
echo $result['title'] . "<br />";
echo $result['content'];
}
Of course I get a list of all my post titles followed by all my post contents. In other words it's like this:
DogsCats
Are also known as canines.Are also known as felines.
Instead of:
Dogs
Are also known as canines
Cats
Are also known as felines
What would I need to do to fix this?
Many thanks.
What about
while ($result = mysql_fetch_array($select))
{
echo $result['title'] . "<br />";
echo $result['content'] . "<br /><br />";
}
You're missing a line break after your content, so first occurrence would be fine, but it'll merge first content with second title.
Try the following for your loop:
while ($result = mysql_fetch_array($select))
{
echo $result['title'] . "<br />" . $result['content'] . "<br />";
}
Alternatively:
while ($result = mysql_fetch_array($select))
{
printf("%s <br /> %s <br />", $result['title'], $result['content']);
}
You should tell PHP what kind of array you want (MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH).
Since you are using column names as array subscripts, you should use MYSQL_ASSOC or MYSQL_BOTH:
while ($result = mysql_fetch_array($select, MYSQL_ASSOC))
...

Categories