Repopulate a table of results with results that match a search - php

I have the following code which echoes out pupil info from a database automatically. However when the user searches for a specific pupil I need to repopulate the same table with relevant pupils to the search request.
All help is greatly appreciated!
if(!isset ($_POST['search'])){
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0 ) {
$totalpupil = "There are currently no Pupils in the system.";
} else{
while($row = mysql_fetch_array($pupils)){
?>
<tr>
<td><?php echo ''.$row['pupil_id'].''; ?></td>
<td><?php echo $row['pupil_name']?></td>
<td><?php echo $row['class_id']?></td>
<td>Edit | Delete</td>
</tr>
<?php
}
}
}

Something like this ?
if(!isset ($_POST['search'])){
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
}
elseif(isset($_POST['search'])){
$search_param = "%".$_POST['search']."%";
$pupils = mysql_query("SELECT * FROM pupil WHERE LOWER(pupil_name) LIKE LOWER($search_param)") or die("Cant find Pupils");
}
$count = mysql_num_rows($pupils);
if($count == 0){
$totalpupil = "There are currently no Pupils in the system.";
}
else{
while($row = mysql_fetch_array($pupils)){
?>
<tr>
<td><?php echo ''.$row['pupil_id'].''; ?></td>
<td><?php echo $row['pupil_name']?></td>
<td><?php echo $row['class_id']?></td>
<td>Edit | Delete</td>
</tr>
<?php
}
I'm assuming that you are searching in the pupil_name column.

Related

PHP: I have failed to select all data i inserted in the table although, some one help me

I inserted the data in the table very well and it's showing in phpMyadmin but when i try to display data from the database only one single item is displayed. I need help.
Code and screenshoots below
<?php
$sql = "SELECT * FROM nw";
$result = mysqli_query($conn, $sql);
if($result == TRUE){
$count = mysqli_num_rows($result);
if($count > 0){
while($row = mysqli_fetch_assoc($result)){
$incidentId = $row['id'];
$icTypeName = $row['inctype_name'];
$addedBy = $row['added_by'];
$addedOn = $row['added_on'];
}
?>
<tr class="tableData">
<td><?php echo $incidentId;?></td>
<td><?php echo $icTypeName;?></td>
<td><?php echo $addedBy;?></td>
<td><?php echo $addedOn;?></td>
<td><i class="uil uil-edit icon editIcon"></i></td>
</tr>
<?php
} else {
$_SESSION['noData'] = 'No incidents to show!';
}
} else {
die('Failed to Connect!');
}
?>
Images below
I expect to get all the data in the database tables displayed with the "SELECT * FROM nw"
Simply move the } that ends the while loop to after the code that is using the variables. You are currently consuming all the resultset before outputting anything, so you will only see the last rows data.
<?php
$sql = "SELECT * FROM nw";
$result = mysqli_query($conn, $sql);
if($result == TRUE){
$count = mysqli_num_rows($result);
if($count > 0){
while($row = mysqli_fetch_assoc($result)){
$incidentId = $row['id'];
$icTypeName = $row['inctype_name'];
$addedBy = $row['added_by'];
$addedOn = $row['added_on'];
//} REMOVED
?>
<tr class="tableData">
<td><?php echo $incidentId;?></td>
<td><?php echo $icTypeName;?></td>
<td><?php echo $addedBy;?></td>
<td><?php echo $addedOn;?></td>
<td><i class="uil uil-edit icon editIcon"></i></td>
</tr>
<?php
} // END OF WHILE LOOP
} else {
$_SESSION['noData'] = 'No incidents to show!';
}
} else {
die('Failed to Connect!');
}
?>

how to fetch data from a table if any of the result matches from mysql results

I am creating a system in which I want to fetch data from a table complaints Now i Have two variables that on behalf of which i want to fetch data from table complaints. One is the district variable and second is pin code and there are a lot of pin codes attached to one center. For example a center signs up and he wants to work on multiple pin codes lets say 110007 and 110008 so his pin code data is stored in a table named center. And his details like his district is stored in users table. Now i have made a page in which i want to show data from a table complaints where district matches his center and pin code matches his pin code. And the code is working fine if one pin code matches but if there are multiple pin codes attached to a center and the complaint is of only 1 pin code then it shows no result but i want it to show results even if it matches only 1 or any of the pin code.
i have tried some code this is my code
session_start();
if(!isset($_SESSION['username']) || (trim($_SESSION['username']) == '')) {
header("location: login.php");
exit();
}
$username = $_SESSION['username'];
if ($username=="dhruv") {
header("location: complaint.php");
}
$sql = "SELECT * FROM users where username = '$username'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
$district = $row['district'];
}
}
$sql = "SELECT * FROM center where username = '$username'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
$pin = $row['id'];
echo $pin."<br>";
}
}
$sql = "SELECT *
FROM complaints
where city_pin = '$pin'
AND status = 'pending'
And district ='$district'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$status = $row['status'];
?>
<tr>
<td><?php echo"<a href='otp.php'>".$row['center']."</a>"?></td>
<td><?php echo $row['time2']?></td>
<td><?php echo $row['product']?></td>
<td><?php echo $row['quantity']?></td>
<td><?php echo $row['warranty']?></td>
<td><?php echo $row['date_of_purchase']?></td>
<td><?php echo $row['customer_name']?></td>
<td><?php echo $row['contact']?></td>
<td><?php echo $row['customer_email']?></td>
<td><?php echo $row['customer_address']?></td>
<td><?php echo $row['city_pin']?></td>
<td><?php echo $row['issue_complaint']?></td>
<td class="red"><?php echo $row['status']?></td>
</tr>
<?php
}
} else {
echo "0 results".mysqli_error($con);
}
please feel free to ask if you didn't understand any part of my question
So i made you a mysqli procedural Code.
That you have to test,
Take all advices from the comments about sql injection and the rest.
as you can see, you have to bind the result,
So please check https://phpdelusions.net/pdo#prepared
For the future use.
So to the code.
I combined all SQL statement to one, you should still get all complaints to one user. Of course yoi shoult test ot in phpmyademin or mysql workbench if you get all the complaints.
To the mysqli i used still the procedural stile, feel free to change every thing to a more object oriented style and of course pdo
session_start();
if(!isset($_SESSION['username']) || (trim($_SESSION['username']) == '')) {
header("location: login.php");
exit();
}
$username = $_SESSION['username'];
if ($username=="dhruv") {
header("location: complaint.php");
}
$stmt = mysqli_prepare($con, "SELECT
c.id
,c.center
,c.time2
,c.product
,c.quantity
, c.warranty
, c.date_of_purchase
, c.customer_name
, c.contact
, c.customer_address
, c.city_pin
, c.issue_complaint
, c.status
FROM
complaints c
INNER JOIN (SELECT `district` FROM users where username = ?) u
ON c.`district` = u.`district`
INNER JOIN (SELECT id FROM center where username = ?) ce
ON c.city_pin = ce.id
where
c.status = 'pending';";
mysqli_stmt_bind_param($stmt, "ss", $username, $username);
mysqli_stmt_execute($stmt);
if (mysqli_stmt_affected_rows($stmt)) > 0) {
/* bind result variables */
mysqli_stmt_bind_result($stmt,$id, $center, $time2, $product, $quantity,
$warranty, $date_of_purchase, $customer_name, $contact,
$customer_address, $city_pin, $issue_complaint,$status);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
?>
<tr>
<td><?php echo"<a href='otp.php'>".$center."</a>"?></td>
<td><?php echo $time2 ?></td>
<td><?php echo $product ?></td>
<td><?php echo $quantity ?></td>
<td><?php echo $warranty ?></td>
<td><?php echo $date_of_purchase ?></td>
<td><?php echo $customer_name ?></td>
<td><?php echo $contact ?></td>
<td><?php echo $customer_email ?></td>
<td><?php echo $customer_address ?></td>
<td><?php echo $city_pin ?></td>
<td><?php echo $issue_complaint ?></td>
<td class="red"><?php echo $status ?></td>
</tr>
<?php
}
} else {
echo "0 results".mysqli_error($con);
}
/* close connection */
mysqli_close($link);

Weird data output about PHP & MySQL

It's wired that only Field name is correct but others. I can't get the the expected result from the code.
How get the correct meta data from the database?
The expected result
Actual result
<?php
// Open a connection to the server and USE the winestore
$link = mysqli_connect("localhost","root","","winestore");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Run a query on the wine table in the winestore database to retrieve
// one row
$query = "SELECT * FROM wine LIMIT 1";
$result = mysqli_query($link, $query);
// Output a header, with headers spaced by padding
print "\n" .
str_pad("Field", 20) .
str_pad("Type", 14) .
str_pad("Null", 6) .
str_pad("Key", 5) .
str_pad("Extra", 12) . "\n";
// How many attributes are there?
$x = mysqli_num_fields($result);
// for each of the attributes in the result set
for($y=0;$y<$x;$y++)
{
// Get the meta-data for the attribute
$info = mysqli_fetch_field ($result);
// Print the attribute name
print str_pad($info->name, 20);
// Print the data type
print str_pad($info->type, 6);
// Print the field length in brackets e.g.(2)
print str_pad("({$info->max_length})", 8);
// Print out YES if attribute can be NULL
if ($info->not_null != 1)
print " YES ";
else
print " ";
// Print out selected index information
if ($info->primary_key == 1)
print " PRI ";
elseif ($info->multiple_key == 1)
print " MUL ";
elseif ($info->unique_key == 1)
print " UNI ";
// If zero-filled, print this
if ($info->zerofill)
print " Zero filled";
// Start a new line
print "\n";
}
mysqli_free_result($result);
mysqli_close($link);
?>
As per the query the expected result is the detail of the table structure and for that one can use mysql Describe table query which will provide the structure of the table.
<?php
$con = mysqli_connect(HOST,USER,PASSWORD,DATABASE NAME);
$data = mysqli_query($con,"DESCRIBE tablename");
?>
<table>
<tr>
<td>Field</td>
<td>Type</td>
<td>Null</td>
<td>Key</td>
<td>Default</td>
<td>Extra</td>
</tr>
<?php while($row=mysqli_fetch_array($data,MYSQLI_ASSOC)){ ?>
<tr>
<td><?php echo $row['Field']; ?></td>
<td><?php echo $row['Type']; ?></td>
<td><?php echo $row['Null']; ?></td>
<td><?php echo $row['Key']; ?></td>
<td><?php echo $row['Default']; ?></td>
<td><?php echo $row['Extra']; ?></td>
</tr>
<?php } ?>
</table>
As per the query the expected result is the detail of the table structure and for that one can use mysql Describe table query which will provide the structure of the table.
you can try following code.I think it will help you.
<?php
error_reporting(0);
$conn = mysqli_connect('localhost', 'root', '');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('winestore');
$result = mysql_query('SELECT * FROM wine LIMIT 0,1');
if (!$result) {
die('Query failed: ' . mysql_error());
}
?>
<table>
<th>Field</th>
<th>Type</th>
<th>Null</th>
<th>Key</th>
<th>Extra</th>
<?php
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
$meta = mysql_fetch_field($result, $i);
if (!$meta) {
echo "No information available<br />\n";
}
$i++;
?>
<tr>
<td><?php echo $meta->name;?></td>
<td><?php echo $meta->type."(".$meta->max_length.")";?></td>
<td><?php if($meta->not_null==1){echo 'NO';}else{echo 'YES';}?></td>
<td><?php if($meta->multiple_key==1){ echo 'MUL';}if($meta->primary_key==1){echo 'PRI';}?></td>
<td><?php echo $meta->not_null;?></td>
</tr>
<?php
}
mysql_free_result($result);
?>
if you have any more doubt about this issue,please visit this link http://php.net/manual/en/function.mysql-fetch-field.php

Explode string from table and compare output with other table

Hello my first question here, I have a bad of trouble getting this code to work or better said how to proceed.
I have 2 tables, table 1 holds a string separated by commas, after exploding the array I want to compare the strings to another table that holds product prices related to the string.
<?php
function packages()
{
global $db;
$query = "SELECT * FROM product_package WHERE package_id > 1; ";
$result = mysqli_query($db, $query) or die('<h3>Query failed</h3>');
$rowcount = mysqli_num_rows($result);
if ($rowcount < 1)
{
return;
}
else
{
while ($row = mysqli_fetch_array($result))
{
$singles = explode(',', $row["product_ids"]);
$query2 = "SELECT product_price FROM products WHERE product_id = $single; ";
$result2 = mysqli_query($db, $query2);
?>
<tr>
<td><?php echo $row["package_id"] ?></td>
<td><?php echo $row["package_name"] ?></td>
<td><?php echo $row["product_ids"] ?></td>
<td>
EDIT
</td>
<td>
<?php
foreach($singles as $single)
{
echo $single . '<br />';
}
?>
</td>
</tr>
<?php
}
}
}
?>
How do I echo the prices that are overlapping with $single?

Using MySql to populate a html table using a specific column

Essentially, I am creating a movie ordering system that has 7 movie genres, and I want each movie tab to populate according to genre. At this point I cant even get the table to show up. Can anyone help me out?
<div id="content">
<table>
<tr><th>Name</th> <th>Genre</th> <th>Year</th> <th>Rating</th></tr>
<?php
//connect to database
$dbc = mysql_connect('localhost' , 'username' , 'password');
$test = mysql_select_db('movies', $dbc);
if ($test = mysql_select_db('movies', $dbc))//test
{
$query = "SELECT * FROM 'movies' WHERE 'genre' = 'Action'";
//call query
$result = mysql_query($query, $dbc);
while ($row = mysql_fetch_array($result))
{
?>
<tr>
<td><?php print $row['name']; ?></td>
<td><?php print $row['genre']; ?></td>
<td><?php print $row['year']; ?></td>
<td><?php print $row['rating'];?></td>
</tr>
<table>
<?php
}//close the while loop
}//close the if statement
mysql_close($dbc);
?>
First of all, do not use mysql because of secure problems and it will be not suported in PHP later. Read about this http://php.net/manual/en/function.mysql-connect.php .
Try to use PDO or mysqli, for example :
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 'movies' WHERE 'genre' = 'Action'");
while($row = mysqli_fetch_array($result))
{
echo $row['name'];
echo "<br>";
}
mysqli_close($con);

Categories