PHP Output from mysql database is blank - php

I have this PHP page which accepts 3 items and stores into a database. The output of the results fetched from database is blank. I can see the records being saved in database via phpmyadmin. What's wrong with this code?
This is the code that displays results in a table.
// Add a shortcode to display the employee's attendance record
function attendance_record_shortcode( $atts ) {
global $wpdb;
$table_name = $wpdb->prefix . 'employee_attendance';
// Get the employee ID from the shortcode parameters
$atts = shortcode_atts( array(
'employee_id' => ''
), $atts );
$employee_id = $atts['employee_id'];
// Get the employee's attendance data from the database
$attendance_data = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name WHERE employee_id = %d",
$employee_id
)
);
// Display the attendance data in a table
ob_start();
?>
<table>
<thead>
<tr>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php foreach ( $attendance_data as $attendance ) : ?>
<tr>
<td><?php echo $attendance->date; ?></td>
<td><?php echo $attendance->status; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php
return ob_get_clean();
}
add_shortcode( 'attendance_record', 'attendance_record_shortcode' );
This is the code that accepts input and saves data to database.
// Create the attendance page and display the attendance form
function attendance_page() {
global $wpdb;
$table_name = $wpdb->prefix . 'employee_attendance';
// If the form has been submitted, add the attendance data to the database
if ( isset( $_POST['submit_attendance'] ) ) {
$employee_id = $_POST['employee_id'];
$date = date( 'Y-m-d', strtotime( $_POST['date'] ) );
$status = $_POST['status'];
$wpdb->insert(
$table_name,
array(
'employee_id' => $employee_id,
'date' => $date,
'status' => $status
)
);
}
// Display the attendance form
?>
<h1>Employee Attendance</h1>
<form method="post">
<label for="employee_id">Employee ID</label>
<input type="text" name="employee_id" id="employee_id" required>
<br>
<label for="date">Date</label>
<input type="date" name="date" id="date" required>
<br>
<label for="status">Status</label>
<select name="status" id="status">
<option value="present">Present</option>
<option value="absent">Absent</option>
<option value="late">Late</option>
</select>
<br>
<input type="submit" name="submit_attendance" value="Submit">
</form>
<?php
}
phpMyAdmin Database Snapshot
Blank Output Page

Related

Do not display the array taken from the database without sending data

Why the database isn't displayed without send form?
when I submit using the form, all the data is displayed, but when I open this page at new, it doesn't display table of database, even when refreshed.
all codes are in a page
SQL, connect
<?php
include '../../database/db.php';
if(isset($_POST['submit'])){
$title = $_POST['title'];
$sort = $_POST['sort'];
$result = $conn->prepare("INSERT INTO menu SET title=?, sort=?");
$result->bindValue(1, $title);
$result->bindValue(2, $sort);
$result->execute();
$all = $conn->prepare("SELECT *FROM menu");
$all->execute();
$menus = $all->fetchAll(PDO::FETCH_ASSOC);
}
?>
form
<form method="POST">
<input type="text" name="title">
<input type="number" name="sort">
<input type="submit" name="submit" value="save">
</form>
show database
<?php
foreach ($menus as $menu){ ?>
<tr>
<td><?php echo $menu['title']; ?></td>
<td><?php echo $menu['sort']; ?></td>
</tr>
<?php } ?>

Select and update radio options of a multiple id with PHP MySQL

I'm trying to get all the students test reports of a specific date in a table and display whether they have passed or failed in a radio button for each student. From the table, I'm trying to update their test result (passed/failed). But in my query, I'm getting only result of either one of the students and when I update, only that specific student gets updated, none other does.
Here is my index.php file. In the table only one students report radio button is active:
<?php
$mysqli = new MySQLi( 'localhost', 'root', '', 'students' )or die( mysql_error( $mysqli ) );
$result = $mysqli->query( "SELECT * FROM class_nine WHERE test_date = '2020-06-20' ORDER BY ID DESC" )or die( $mysqli->error );
?>
<div class="container">
<div class="row">
<form action="process.php" method="POST">
<input type="hidden" name="id" value="<?php echo $id;?>">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Report</th>
</tr>
</thead>
<?php
while ( $row = $result->fetch_assoc() ):
?>
<tr>
<td><input type="text" name="id" value="<?php echo $row['id']; ?>"></td>
<td><?php echo $row['name'];?></td>
<td><label class="radio-inline">
<input type="radio" name="report" value="Passes" <?=$row['report'] == "Passed" ? "checked" : ""?>>
Passed</label>
<label class="radio-inline">
<input type="radio" name="report" value="Failed" <?=$row['report'] == "Failed" ? "checked" : ""?>>
Failed</label></td>
</tr>
<?php endwhile; ?>
</table>
<button type="submit" name="update">Update</button>
</form>
</div>
</div>
This is my process file:
<?php
session_start();
$mysqli = new MySQLi( 'localhost', 'root', '', 'students' )or die( mysql_error( $mysqli ) );
$id = 0;
$report = '';
if ( isset( $_POST[ 'update' ] ) ) {
$id = $_POST[ 'id' ];
$report = $_POST[ 'report' ];
$mysqli->query( "UPDATE class_nine SET
report = 'report'
WHERE id = $id" )or die( $mysqli->error );
header( "location: index.php" );
}
?>
This is how my MySQL table is structured:
CREATE TABLE class_nine(
id INTEGER NOT NULL PRIMARY KEY
,name VARCHAR(1) NOT NULL
,test_date DATE NOT NULL
,report VARCHAR(6)
);
INSERT INTO class_nine(id,name,test_date,report) VALUES (23,'A','2020-06-20','Passed');
INSERT INTO class_nine(id,name,test_date,report) VALUES (33,'B','2020-06-20',NULL);
INSERT INTO class_nine(id,name,test_date,report) VALUES (35,'C','2020-06-20','Failed');
INSERT INTO class_nine(id,name,test_date,report) VALUES (45,'D','2020-06-22',NULL);
You are using the same name="report" for all radio buttons, that is the reason why only one is being checked. Use this instead
name="<?=$row['id']?>"
You will have each student result posted with the name being assigned to student id, In your process file loop through these value and update each student's result.

display data from database of an HTML form

I am trying to display results from my database using PHP through an HTML form. Once the user clicks the submit button, based on what they enter in each field, results should be shown accordingly.
E.g. if I click on "Rooms" in my drop down menu, and when I specify a certain price in the text field for price and for the rest of the fields, anything related to what I searched should be displayed.
I was able to do it for the drop down menu, but I don't know how I can enter multiple values and when I click submit it generates the data accordingly.
Here's what I've done so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="dropdown2.php" method="POST">
<select name="testing" type="text">
<option value="Choose">Choose type of stay</option>
<option value="Flat">Flat</option>
<option value="Room">Room</option>
<option value="Apartment">Apartment</option>
<option value="Villa">Villa</option>
</select>
<p></p>
<table>
<tr>
<td width="14%" class="label">Minimum Price MYR</td>
<td width="42%"><input type="text" name="textfield4" id="textfield4" class="text" /></td>
<td class="label">Maximum Price MYR</td>
<td><input type="text" name="textfield2" id="textfield2" class="text" /></td>
</tr>
<tr>
<td class="label">Bed Rooms</td>
<td>
<label>
<input type="text" name="search" id="textfield5" class="text smalltextarea" />
</label>
</td>
<td class="label">Bathrooms</td>
<td><input type="text" name="textfield3" id="textfield3" class="text" /></td>
</tr>
</table>
<p></p>
<input type="submit" value="Submit" name="submit">
</form>
<?php
mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
mysql_select_db("test") or die(mysql_error());
if(isset($_POST['testing'])){
$query = $_POST['testing'];
$min_length = 3;
if(strlen($query) >= $min_length){
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
$raw_results = mysql_query("SELECT * FROM rooms
WHERE (`name` LIKE '%".$query."%') OR (`price` LIKE '%".$query."%') OR (`description` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){
while($results = mysql_fetch_array($raw_results)){
echo "<p><h3>".$results['name']."</h3>"."RM " .$results['price']."</p>"."<p>".$results['description']."</p>";
}
}
else{
echo "No results";
}
}
else{
echo "Minimum length is ".$min_length;
}
}
?>
</body>
</html>
I'm new to PHP and MySQL... any help is appreciated!
first id say change the names to something a bit more reconcilable
also you are missing a name or description field not sure which one (since the names don't resemble the database fields)
replace mysql for pdo or mysqli i used pdo in this example
since if you upgrade to php 7 mysql functions are removed (like suggested in the comments above)
instead of the mysql real escape etc you can use a prepared statement
also what you were missing in the query were the other post fields like suggested in the comments for example how many bathrooms, the minprice, the maxprice etc (these fields are posted by the user but not used in the query)
you were using the same postfield for all of those values in your query
now based on your fields i am assuming for example if someone fills in minprice = 12 and descr = flat that the result both has to have a minimum price of 12 and a description like flat so you need to change the OR's you used in your query for AND's based on which field are filled in
here is a bit of an example on how to go about it:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="" method="POST">
<select name="description" type="text">
<option value="Choose">Choose type of stay</option>
<option value="Flat">Flat</option>
<option value="Room">Room</option>
<option value="Apartment">Apartment</option>
<option value="Villa">Villa</option>
</select>
<p></p>
<table>
<tr>
<td width="14%" class="label">Minimum Price MYR</td>
<td width="42%"><input type="text" name="minprice" id="textfield4" class="text" /></td>
<td class="label">Maximum Price MYR</td>
<td><input type="text" name="maxprice" id="textfield2" class="text" /></td>
</tr>
<tr>
<td class="label">Bed Rooms</td>
<td>
<label>
<input type="text" name="bedrooms" id="textfield5" class="text smalltextarea" />
</label>
</td>
<td class="label">Bathrooms</td>
<td><input type="text" name="bathrooms" id="textfield3" class="text" /></td>
</tr>
</table>
<p></p>
<input type="submit" value="Submit" name="submit">
</form>
<?php
$minDescriptionLength = 3;
if(isset($_POST['description'])) {
$descr = $_POST['description'];
if(strlen($descr) >= $minDescriptionLength) {
$connectionConfigArr = array('host' => 'localhost', 'dbname' => 'test', 'user' => 'root', 'password' => '');
// here we are making the database connection,
// first param = connection string, second param = user, third param = password
$dbh = new PDO(
'mysql:host=' . $connectionConfigArr['host'] . ';dbname=' . $connectionConfigArr['dbname'],
$connectionConfigArr['user'],
$connectionConfigArr['password']
);
$bindParamArr = array();
//since we check this one in the start i assumed it's required so we can use it in the base for the query
$query = 'SELECT * FROM rooms WHERE `description` LIKE :descr ';
//here for each extra field that is filled in we basicaly are going to add it to the query string
//and we push the value to the bindParamArray which will after we added the query add the values safely to the query
if(isset($_POST['minprice']) && $_POST['minprice']) {
$query .= 'AND `price` > :minprice ';
array_push($bindParamArr, array('field' => ':minprice', 'value' => $_POST['minprice'], 'type' => PDO::PARAM_INT));
}
if(isset($_POST['maxprice']) && $_POST['maxprice']) {
$query .= 'AND `price` < :maxprice ';
array_push($bindParamArr, array('field' => ':maxprice', 'value' => $_POST['maxprice'], 'type' => PDO::PARAM_INT));
}
if(isset($_POST['bathrooms']) && $_POST['bathrooms']) {
$query .= 'AND `bathrooms` = :bathrooms ';
array_push($bindParamArr, array('field' => ':bathrooms', 'value' => $_POST['bathrooms'], 'type' => PDO::PARAM_INT));
}
if(isset($_POST['bedrooms']) && $_POST['bedrooms']) {
$query .= 'AND `bedrooms` = :bedrooms ';
array_push($bindParamArr, array('field' => ':bedrooms', 'value' => $_POST['bedrooms'], 'type' => PDO::PARAM_INT));
}
//we still need to push the description to the array
array_push($bindParamArr, array('field' => ':descr', 'value' => '%' . $descr . '%', 'type' => PDO::PARAM_STR));
//here we prepare the query
$stmt = $dbh->prepare($query);
//here we bind the params safely
foreach($bindParamArr as $bParam) {
$stmt->bindParam($bParam['field'], $bParam['value'], $bParam['type']);
}
$stmt->execute();
//use this to get the amount of rows the query returned
$rowCount = $stmt->rowCount();
if($rowCount > 0) {
//we loop through the stmt fetch function which will iterate through the resultset
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<p><h3>".$row['name']."</h3>"."RM " .$row['price']."</p>"."<p>".$row['description']."</p>";
}
}
else {
echo "No results";
}
}
else {
echo "Minimum length is ".$minDescriptionLength;
}
}
?>
</body>
</html>

How do I update mysql table using pdo and multiple arrays?

I've got a list of form fields in an html table. This page is designed to allow someone to modify multiple records at once...using an update query. Because I have multiple customer records present, I need to update based on the record Id. I thought that I was supposed to create a composite array then update the database by pointing to the various key, value pairs, but nothing seems to work...all help is appreciated..hoping its a small typo I'm not catching:
....SQL to pull data (works)...
echo "<form action='#' method='POST' >";
echo "<center><table>";
echo "<tr><th> Email Address </th> <th>Created On</th><th> Ip Address</th><th> Front of Card</th><th> Back of Card</th><th> Last 4 of Card</th><th> Decision</th><th> Notes (for Reject)</th>";
foreach ($customer as $row){
echo '<tr><input type="hidden" name="record[]" value='.$row[' id '].'/>
<td>'.$row["email"].' </td>
<td>'.$row["created_on"].'</td>
<td>'.$row["ip_address"].'</td>
<td>
<img class="fixed" src="imgReader.php?img='.$row[" card_front "].'"/>
</td>
<td>
<img class="fixed" src="imgReader.php?img='.$row[" card_back "].'"/>
</td>
<td><input type="number" name="last4[]" value="" /></td>
<td><select name="decision[]">
<option value="PENDING">Pending</option>
<option value="APPROVED">Approved</option>
<option value="DENIED">Denied</option>
<option value="DUPLICATE">Duplicate</option></select></td>
<td><input type="textarea" rows="5" name="notes[]" value="" /></td>
</tr>';
if ($_POST){
$last4 = $_POST["last4"];
$status = $_POST["decision"];
$notes = $_POST["notes"];
$ids = $_POST["record"];
$tableSet = array('last4' => $last4,
'decision' => $status,
'notes' => $notes,
'ids' => str_replace('/','', $ids)
);
var_dump($tableSet);
foreach( $tableSet as $i) {
$updateUserData = $db->prepare("UPDATE cards SET `last_4_cc` = :l4cc, `status` = :status, `notes` = :notes WHERE `id` = :record");
$updateUserData->execute([
':l4cc' => $i[$tableSet["last4"]],
':status' => $i[$tableSet["decision"]],
':notes' => $i[$tableSet["notes"]],
':record' => $i[$tableSet["ids"]]
]);
}
}
?>

Sort from database tables by multiple checkbox php

I have a question about display data from the database alphabetically.
I have 2 ckeckboxes and if the nr.1 is checked, it must display data alphabetically from table "companyName" but if chechbox nr.2 is checked, it must display data alphabetically from table "stade".
I am very new to coding, so I will be happy if there was someone who could explain or show me exactly how it should look.
Here is the checkboxes:
<fieldset>
<dl">
<dt><label for="sleep">Sortering:</label></dt>
<dd>
<input type="checkbox" name="" value="Alfabetisk A-Z"/>
<label for="alfabetiskA-z" class="opt">Alfabetisk A-Z</label>
<input type="checkbox" name="" value="Alfabetisk Stade"/>
<label for="alfabetiskStade" class="opt">Alfabetisk Stade</label>
</dd>
</dl>
</fieldset>
Here is where I show my data fra the database:
echo '
<table class="tableUser">
<tr class="topColor">
<td>Stade</td>
<td>Firmanavn</td>
<td>Navn</td>
<td>Telefon nr.</td>
<td>E-mail adresse</td>
</tr>';
$class0 = "trColor0";
$class1 = "trColor1";
$query = mysqli_query($conn,"SELECT * FROM creatUser ORDER BY companyName ASC");
while( $result = mysqli_fetch_array($query)) {
$id = $result['id'];
$class = "trColor". $i%2;
echo '
<tr class="'.$class.'">
<td VALIGN=TOP>'.$result['locationNumber'].'</td>
<td VALIGN=TOP>'.$result['companyName'].'</td>
<td VALIGN=TOP>'.$result['fName'] . ' ' . $result['lName'].'</td>
<td VALIGN=TOP>'.$result['phone'].'</td>
<td VALIGN=TOP>'.$result['eMail'].'</td>
</tr>';
$i++;
}
You have to give names to your checkboxes, so you can get what the user selected:
<input type="checkbox" name="sort" value="Alfabetisk A-Z"/>
<label for="alfabetiskA-z" class="opt">Alfabetisk A-Z</label>
<input type="checkbox" name="sort" value="Alfabetisk Stade"/>
<label for="alfabetiskStade" class="opt">Alfabetisk Stade</label>
Then in your PHP, you do:
if (!isset($_POST['sort']) || $_POST['sort'] == 'Alfabetisk A-Z') {
$order = 'companyName'
} else {
$order = 'stade';
}
$sql = "SELECT * FROM creatUser ORDER BY $order ASC";
$query = mysqli_query($conn, $sql) or die (mysqli_error($conn));

Categories