Search the results from a query - php

I have a site where members can mark other members as 'a favourite'. User are able to search the members table in various ways and I want to show from any of the results that are returned whether or not the users returned are favourites of the current user.
This is some very simplified code I have been using to try and get this query to work but I just can't figure it out. Whenever I add 'GROUP BY' to avoid duplicate results from my LEFT JOIN the 'if' statement does not work. The 'if' statment does work however, if I omit the 'GROUP BY' but I get all rows from members table and the favourites table. Thanks.
$result = mysqli_query($db_conx, "SELECT members.*, user_favourites.* FROM members LEFT JOIN user_favourites ON members.id = user_favourites.fav_id GROUP BY members.id");
echo "<table border=''>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>A favourite of User</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
if ($visitor == $userid ){
$msgs = "x";
}
else { $msgs = "0";
}
echo "<td>". $msgs. "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

I suggest to you, tu use 2 query's insted one. Simple query is a fast querys. If your site scale up, your query will be slow query and it cause performance problems.
Idea:
For one hand: SELECT FROM members, get all and put it inside array, key=member.id
$members[$row['member_id']]=$row;
On the other hand: SELECT * FROM user_favourites, and put it inside the previous array, refereced by the key fav_id use distinc if you have duplicates.
$members[$row['fav_id']]['favourites']=$row;
Perfect now you have all you need, an array with all information, iterate it.

JilianJ something like this:
<?
//Prepare
$all_users=array()
$query_users='SELECT * from user';
$query_favourites='SELECT * FROM user_favourites';
//Now I find all members information
$users=mysqli_query($db_conx,$query_users);
while($user = mysqli_fetch_array($users)) {
$all_users[$user['id']]=$user;
}
//Now I add favourite information to the users information
$favourites=mysqli_query($db_conx,$query_favourites);
while($favourite = mysqli_fetch_array($favourites)) {
$all_users[$favourite['fav_id']]['fovourite'][]=$favourite['fav_id'];
}
?>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>A favourite of User</th>
</tr>
<? foreach ($information as $key=>$item) {?>
<tr>
<td><?=$item['firstname'];?></td>
<td><?=$row['lname'];?></td>
<td><?=$row['email'];?></td>
<td>
<? foreach($item['favourites'] as $key2=>$item2) { ?>
<p><?=$all_members[$item2]['name];?></p>
<? } ?>
</td>
</tr>
<? } ?>
</table>
Good luck

Related

How could you use PHP and a SQL database to change HTML <h> content?

I have a webpage that displays cars from the first car in the table to the last car with a while loop.
I have the following columns: Make, Model, Price. In my syntax I have an anchor tag around the Make rows that links to the description page of the Make you click on.
I want my <h> tags to change to the Model of the corresponding Make.
I've spent over an hour trying to achieve this but all I could come up with is this:
<?php
$query = "SELECT Model FROM inventory;";
$Vtitle = $conn->query($query);
$Vtitle_ar = mysqli_fetch_assoc($Vtitle);
echo "<h1>".$Vtitle_ar['Model']."</h1>";
?>
This works to an extent.
Every anchor I click replaces the <h> tags with only the first result under the Model column in my database.
Here is my code for the the entire car inventory page
<?php
$query = "SELECT * FROM inventory;";
/* Try to query the database */
if ($result = $conn->query($query)) {
// Don't do anything if successful.
}
else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
// Create the table headers
echo "<table id='Grid' style='width: 80%'><tr>";
echo "<th style='width: 50px'>Make</th>";
echo "<th style='width: 50px'>Model</th>";
echo "<th style='width: 50px'>Asking Price</th>";
echo "</tr>\n";
$class = "odd"; // keep track of whether a row was even or odd, so we can style it later
// Loop through all the rows returned by the query, creating a table for each row
while ($result_ar = mysqli_fetch_assoc($result)) {
echo "<tr class=\"$class\">";
echo "<td><a href='viewcar.php?VIN=".$result_ar['VIN']."'>".$result_ar['Make']."<a></td>";
echo "<td>".$result_ar['Model']."</td>";
echo "<td>".$result_ar['ASKING_PRICE']."</td>";
echo "</td></tr>\n";
// if the last row was even, make the next one odd and vice-versa
if ($class=="odd") {
$class = "even";
}
else {
$class = "odd";
}
}
echo "</table>";
$conn->close();
?>
Does anyone how I can do this?
I'm new to programming and I'm trying to use this for an actual project I'm working on for a hair salon's website
Add a WHERE clause to the query.
$vin = $_GET['VIN'];
$stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = ?");
$stmt->bind_param("s", $vin);
$stmt->execute();
$stmt->bind_result($model);
$stmt->fetch();
echo "<h1>$model</h1>";
Though not a solution resolved with the use of a where clause as given by #Barmar whilst formatting the code I did find an error within the HTML which was not immediately obvious
The line echo "</td></tr>\n"; has an extra </td> which would break the flow of the html and can have detrimental effects. Also, // Don't do anything if successful. makes no sense - if there are results then process the recordset otherwise show the error ;-)
<?php
$query = "SELECT * FROM inventory;";
if ( $result = $conn->query( $query ) ) {
echo "
<table id='Grid' style='width: 80%'>
<tr>
<th style='width: 50px'>Make</th>
<th style='width: 50px'>Model</th>
<th style='width: 50px'>Asking Price</th>
</tr>";
$i=0;
while( $result_ar = mysqli_fetch_assoc( $result ) ) {
$class = $i %2 == 0 ? 'even' : 'odd';
echo "
<tr class='$class'>
<td><a href='viewcar.php?VIN={$result_ar['VIN']}'>{$result_ar['Make']}<a></td>
<td>{$result_ar['Model']}</td>
<td>{$result_ar['ASKING_PRICE']}</td>
</tr>";
$i++;
}
echo "</table>";
} else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
$conn->close();
?>
For styling alternate table rows ( the above uses a modulus function to calculate odd/even ) you can do it with some simple CSS - such as
tr:nth-child( odd ){/* rules */}

cannot delete row from database using php

I am unable to delete any record from database. I cannot find any error in this.
I have deleted records from another table by just changing a little bit but here it's not working. Below is the code to apply the delete query.The name of table is from where I want to delete records but its not happening here.
deleteSupplier.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("db_kiln");
$id1 = $_GET['id1'];
$query0 = "DELETE FROM tbl_supplier WHERE sup_id='$id1'";
if(mysql_query($query0)){
echo "<script>window.open('supplier_connect.php','_self')</script>";
}
else{
echo "Not deleted";
}
?>
This is the file where I fetch data from database and have delete button against each record. When I click on the button it does not delete record and show the error message. I can't find any error I think there is a logical error in this code. Please help.
supplier_connect.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("db_kiln");
$query = "Select * from tbl_supplier";
$run = mysql_query($query);
echo "<table border='1'>
<tr>
<th>Supplier Id</th>
<th>Name</th>
<th>Contact Number</th>
<th>Quotation </th>
<th>Remove</th>
</tr>";
while($row = mysql_fetch_assoc($run)){
echo "<tr>";
echo "<td>" . $row['sup_id'] . "</td>";
echo "<td>" . $row['sup_name'] . "</td>";
echo "<td>" . $row['sup_contact'] . "</td>";
echo "<td>" .$row['sup_quotation']. "</th>";
echo '<td>Delete</td>';
echo "</tr>";
}
echo "</table>";
?>
You probably have the ID of the supplier referencing to another table, and upon DELETE, no action is set. You need to set the option 'upon DELETE: Cascade or SET NULL.' I'd go for SET NULL, else your whole reference record will be deleted as well.
EDIT: check the relationship between your contacts and quotations, see where your supplierid is going to.

Create multiple tables by cycling through a query

Here is my current code:
$varVeh=$_POST['Veh_num'];
$sql_HiScores = "SELECT
c.course_name as course,
e.distance as distance, e.score as score,
e.time as time, e.user as User
FROM hc_entries e
LEFT JOIN hc_course c on e.course=c.course_num
WHERE e.vehicle=$varVeh
ORDER BY course, score DESC";
$result_HiScores = mysql_query($sql_HiScores);
$sql_vehName="SELECT Veh_name FROM hc_vehicle_type WHERE Veh_num=$varVeh ";
$result_vehName = mysql_query($sql_vehName);
$vehName=mysql_fetch_assoc($result_vehName);
echo "<table><tr><th>Best Scores for ".$vehName['Veh_name']."</th></tr></table>";
echo "<table border='1'>";
echo "<tr><th>Course</th><th>Score</th><th>Distance</th><th>Player</th><th>Time</th></tr>";
while($row = mysql_fetch_array($result_HiScores))
{
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
echo "<td>" .$row['User'] . "</td>";
}
echo "</table>";
What I think I have to do is create a query that selects * from e.course that builds an array. Then cycle through the existing query with the array results. Finally, I would like to display individual tables for each course and limit it to the top 5 results for each course.
Can anyone confirm or deny my logic, and point me in a direction?
First of all, you shouldn't be using the mysql_ functions, they're deprecated. At the least, you should switch to mysqli_ (a pretty easy switch), or better, learn how to use PDO. It's a bit different and more involved to switch, but your code will be better and safer for it.
With that out of the way: your logic is pretty accurate. Limiting your results to the top 5 results for each course in one query isn't something that's easily done with SQL to my knowledge, so your plan is good: query a list of courses, then cycle through them with your existing query, running it once for each course, with a LIMIT 5 to get the top 5.
You might as well keep the table generation within this loop as well, since it's a table-per-course. You'd want to move the VehName query out of the loop, since you only need to run that once.
Also, some unsolicited PHP advice: any text outside of the tags will just be output directly, so take advantage of its built-in-templating and alternative syntax to make your table generation code nicer:
<?php
/* Gather your data here... */
?>
<table>
<tr><th>Best Scores for <?php echo $vehName['Veh_name'] ?></th></tr>
</table>
<table border='1'>
<tr>
<th>Course</th>
<th>Score</th>
<th>Distance</th>
<th>Player</th>
<th>Time</th>
</tr>
<?php while($row = mysql_fetch_array($result_HiScores)): ?>
<tr>
<td><?php echo $row['course'] ?></td>
<td><?php echo $row['score'] ?></td>";
<td><?php echo $row['distance'] ?></td>";
<td><?php echo $row['User'] ?></td>";
</tr>
<?php endwhile; ?>
</table>
put the entire table html inside the while loop and add 'LIMIT 5' to the end of your query

Showing Mysql table data in html form with php

I'm showing data from Mysql table with php inside HTML table, but i need 2 more things to accomplish to the table:
1- How to Alternate colors for table rows to use 4 different css classes, I am using now class='success' i have 3 more that i want to use and each one should apply to each table row, how to do it? any simple example like a loop or something?
2- Data showing from the oldest record in the table to the latest one, and i want to show the reverse, so the last record shows first in the html table.
My code for this table:
<?php echo "<table class='table'>
<thead>
<tr>
<th>Order#</th>
<th>Name</th>
<th>Total</th>
<th>Submitted On</th>
<th>Status</th>
</tr> </thead>";
while($row = mysqli_fetch_array($result))
{
echo "<tr class='success'>";
echo "<td>" . $row['lite_order_id'] . "</td>";
echo "<td>" . $row['lite_item_name'] . "</td>";
echo "<td>" . $row['lite_email'] . "</td>";
echo "<td>" . $row['lite_country'] . "</td>";
echo "<td>" . $row['lite_order_total'] . "</td>";
echo "</tr>"; }
echo "</table>"; ?>
1 - Use id attribute to style individual elements. Check it out here
2 - In your MySQL query, use ORDER BY:
(I presume you have an id column here)
$query = "SELECT * FROM `yourtable` ORDER BY `id` ASC";
See here
To get reverse records you can use mysql ORDER BY clause or PHP function array_reverse()

PHP: Loop through query to create a bullet list in table form

PHP 7.1.7
I'm really new to PHP and having troubling thinking through this or finding a good example.
For the code below, I'm simply making a table of query results. What I need to do is loop through the query for each unique UID to create a bullet list in table form. So, the table output is a UID in COLUMN 1 and then COLUMN 2 of the table contains a new row for each LOG_TEXT (and where the UID would only be echo'd on the first pass of the loop).
Example:
User24: •Opened Door 1
•Opened Door 2
•Opened Door 5
•Opened Door 6
User33: •Opened Door 1
•Opened Door 2
•Opened Door 5
•Opened Door 6
<?php include 'db_connect.php'; ?>
<?php
$result = mysqli_query($con,"
SELECT uid, log_text
FROM logs l
WHERE (l.log_date BETWEEN '2017-07-01' AND '2017-07-31')
");
echo "<table class='table_standard_grey_with_border' >
<tr>
<th>UID</th>
<th>LOG TEXT</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['uid'] . "</td>";
echo "<td>" . $row['log_text'] . "</td>";
}
echo "</tr></table>";
mysqli_close($con);
?>
Order your query-result by userId, so all actions by the same user are 'grouped' together.
$result = mysqli_query($con,"
SELECT uid, log_text
FROM logs l
WHERE (l.log_date BETWEEN '2017-07-01' AND '2017-07-31')
ORDER BY uid
");
And within your PHP, just keep track of the previously printed userId and print an empty cell if it is equal to the previous one:
$previousUid = null;
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
if ($previousUid === $row['uid']) {
echo "<td></td>"; // Empty cell
} else {
echo "<td>" . $row['uid'] . "</td>";
$previousUid = $row['uid'];
}
echo "<td>" . $row['log_text'] . "</td>";
echo "</tr>";
}
Another possible way to do this is to fetch the data from the query into a multidimensional array before displaying it.
$result = mysqli_query($con,"
SELECT uid, log_text
FROM logs l
WHERE (l.log_date BETWEEN '2017-07-01' AND '2017-07-31')
");
while($row = mysqli_fetch_array($result)) {
$data[$row['uid']][] = $row['log_text'];
}
mysqli_close($con);
This will give you an array of data that can be displayed in an HTML view more simply, so that your data access code can be separated from your presentation code. This grouping will work whether or not you include an ORDER BY clause in your query, but you probably should do so anyway to be sure the data displays in the order you expect it to. It looks like ORDER BY uid, log_date would make sense for this data.
<table class='table_standard_grey_with_border'>
<tr>
<th>UID</th>
<th>LOG TEXT</th>
</tr>
<?php foreach ($data as $uid => $log_texts): ?>
<tr>
<td><?= $uid ?></td>
<td>
<ul>
<?php foreach ($log_texts as $log_text): ?>
<li><?= $log_text ?></li>
<?php endforeach ?>
</ul>
</td>
</tr>
<?php endforeach ?>
</table>
A disadvantage to this approach is that it will be a little slower than displaying each row as you fetch it, and will consume more memory.

Categories