I have been trying to make my select sticky so that it will retain the value of the firstname and lastname of the user that is currently being searched. I have tried many approaches including structuring my php differently so that the script is at the beginning of the file and starts with if(isset($_POST['submit'])){} then it echoes the html with the fields filled out and else{} echo the html blank. This approach below is the closest I have gotten to making it sticky I think but I still can't get it to work.
<?php
$user_id = 2;
$user_firstname = "Soren";
$user_lastname = "Craig";
require ('mysqli_connect.php');
# based on student name, get list of files uploaded
$pageTitle = "View User Files";
include ('includes/header.html');
?>
<div class="container">
<h2>Uploaded Files</h2>
<div class="form-group col-xs-4">
<form action="newview.php" method="POST">
<label for="sel1">Select User:</label>
<select class="form-control" id="select-user" name="select-user">
<option><?php if(isset($firstname) && isset($lastname)) echo $lastname . ", " . $firstname?></option>
<?php
$query = "SELECT user_id, firstname, lastname FROM studentusers ORDER BY lastname ASC";
$stmt = mysqli_prepare($dbconnect, $query);
if(mysqli_stmt_execute($stmt))
{
mysqli_stmt_bind_result($stmt, $user_id, $firstname, $lastname);
while(mysqli_stmt_fetch($stmt))
{
echo '<option value="' . $user_id . '">' . $lastname . ", " . $firstname . "</option>";
}
}
echo "</select>";
mysqli_stmt_close($stmt);
echo '<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>';
if(isset($_POST['submit']))
{
$user_id = $_POST['select-user'];
echo '<p>' . $firstname . " " . $lastname . '</p>
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Date</th>
</tr>
</thead>
<tbody>';
$query = "SELECT filename, posteddate FROM fileuploads WHERE user_id = ?";
$statement = mysqli_prepare($dbconnect, $query);
mysqli_stmt_bind_param($statement, 'i', $user_id);
if(mysqli_stmt_execute($statement))
{
// bind the result
mysqli_stmt_bind_result($statement, $fileName, $fileDate);
while(mysqli_stmt_fetch($statement))
{
echo "<tr>
<td> " . $fileName . " </td>
<td></td>
<td>" . date('F j, Y', strtotime($fileDate)) . "</td>
</tr>";
}
}
}
?>
</div>
</body>
</html>
Any help is much appreciated... Thanks!
You mean that after the form's submitted and re-displayed, you want the previous selected values to be already-selected in the form?
Easy enough:
while(...) {
if (should be selected) {
<option selected="selected">...</option>
} else {
<option>...</option>
}
}
Related
Hello guys I'm new to OOP PHP and I want to imitate the retaining of user generate data in form from procedural
here is my code:
<?php
class View_LType extends Config{
public function view_ltype(){
$con = $this->con();
$sql = "SELECT * FROM `tbl_leave_type`";
$data = $con->prepare($sql);
$data->execute();
$result = $data->fetchAll();
foreach ($result as $data){
echo "
<tr class='table-head'>
<td class='numbers'>$data[leave_id]</td>
<td>$data[leave_code]</td>
<td>$data[leave_name]</td>
<td class='small'>$data[leave_description]</td>
<td><a href='#'></a></td>
</tr>";
}
}
public function select_ltype(){
$con = $this->con();
$sql = "SELECT * FROM `tbl_leave_type`";
$data = $con->prepare($sql);
$data->execute();
$result = $data->fetchAll();
foreach ($result as $data){
echo '<option value="' . $data['leave_name'] . '">' . $data['leave_name'] . '</option>';
}
}
}
html page:
<div class="form-group">
<label for="ltype">Leave Type</label>
<select name="ltype" id="ltype" name="ltype" required >
<option>Select leave...</option>
<?php $view_leave->select_ltype(); ?>
</select>
</div>
$data[leave_name] is what the user will select what I want is to echo selected when the user select its prefered leave name. please help me guys
If the current $data['leave_name'] is the same as the submitted "ltype", then select that option:
echo '<option value="' . $data['leave_name'] . '"' . (($data['leave_name'] == $_REQUEST['ltype']) ? ' selected' : '') . '>' . $data['leave_name'] . '</option>';
I am doing attendance management system but I am unable to understand. please help me
<form method="post">
<div class="table-responsive py-4">
<table class="table table-flush" id="datatable-basic">
<thead class="thead-light">
<tr>
<th>Name</th>
<th>Father's Name</th>
<th>Hall Ticket</th>
<th>Department</th>
<th>Attendace</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_POST["search_students"])){
$department=$_POST['department'];
$sql = "SELECT * FROM student_info WHERE department='$department'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["father_name"]."</td>";
echo "<td>".$row["hall_ticket"]."</td>";
echo "<td>".$row["department"]."</td>";
echo "<td>
Present <input type='radio' name='attendance[".$row['hall_ticket']."][".$row['department']."]' value='Present'>
Absent <input type='radio' name='attendance[".$row['hall_ticket']."][".$row['department']."]' value='Absent'>
</td>";
echo "</tr>";
}
}
}
?>
</tbody>
</table>
</div>
<div class="col-lg-12 mb-3">
<button type="submit" name="mark_attendance" class="btn btn-success">Mark Attendance</button>
</div>
</form>
</div>
<?php
if(isset($_POST["mark_attendance"])){
$attendance=$_POST['attendance'];
foreach ($attendance as $key => $value) {
if($value=="Present") {
$query="Insert into attendance (hall_ticket,attendance) values ('$key','Present')";
$insertAttendance=$conn->query($query);
}
else {
$query="Insert into attendance (hall_ticket,attendance) values ('$key','Absent')";
$insertAttendance=$conn->query($query);
}
}
if($insertAttendance){
echo "Attendance Updated Sucessfully";
}
}
?>
</div>
Here i want 2 key to store into my database as hall ticket value and department value.
attendance[".$row['hall_ticket']."][".$row['department']."]
how to use both variables to store into my db. I want to store each table person attendance with their department and hallticket. i will get the hallticket if i remove department from name and simply use $key to store the values.
Try following code:
HTML Code (Created dummy data for reference):
<form action='new.php' method="POST" >
Presnt<input type="radio" name="attendance[111][555]" value="present"><br>
Absent<input type="radio" name="attendance[111][555]" value="absent"><br><br>
Presnt<input type="radio" name="attendance[222][555]" value="present"><br>
Absent<input type="radio" name="attendance[222][555]" value="absent"><br><br>
Presnt<input type="radio" name="attendance[333][555]" value="present"><br>
Absent<input type="radio" name="attendance[333][555]" value="absent"><br>
<input type="submit">
</form>
PHP Code:
<?php
$attendance=$_POST['attendance'];
$data = "";
foreach ($attendance as $key => $value) {
$department = array_keys($value)[0];
$data.="('". $key ."','". $department ."', '" . $value[$department] . "'),";
}
$query = "INSERT INTO attendance (hall_ticket,department,attendance) VALUES " .
rtrim($data, ",");
// Your Query will look like:
// Query = "INSERT INTO attendance (hall_ticket,department,attendance)
// VALUES ('111','555', 'present'),
// ('222','555', 'present'),
// ('333','555', 'absent')";
// Now execute your query
$conn->query($query);
echo $sql;
?>
Note :
Never hit the database in for loops
Even this code will work for you but this is open for SQL injection, you should use a prepared statement to build and execute you query.
so you $attendance is
$attendance=array(
$row['hall_ticket'] => array(
$row['departement']"=> [" present " OR "absence"]
);
this what i understand
my solution is
foreach ($attendance as $hall => $departements) {
foreach($departements as departement => $value){
$req="INSERT INTO attendance (hall_ticket,department,attendance)
values ('".$hall. "','". $departement ."' ,'". $value ."')";
$insertAttendance=mysqli_query($dataBaseConnect,$req);
}
I'm looking for help with my products list.
My Code:
<!DOCTYPE html>
<html>
<head>
<title> Produktliste </title>
</head>
<body>
<iframe name="dir" style="display:none;"></iframe>
<form action="shop.php" method="post">
<p> <h2> Produkt hinzufügen </h2> </p>
<p> Produktname: <input type="text" name="Produktname"/> </p>
<p> Produktbeschreibung: <textarea rows=2 cols=20 name="Produktbeschreibung"></textarea> </p>
<p> Preis: <input type="text" name="Preis"/> </p>
<input type="submit" name="speichern" value="Speichern"/>
</form>
<?php
$connect = new mysqli ('localhost', 'root', '');
$connect->select_db('shop');
if (#$_REQUEST["Produktname"] && #$_REQUEST["Produktbeschreibung"] && #$_REQUEST["Preis"]) {
$produktname = #$_REQUEST["Produktname"];
$beschreibung = #$_REQUEST["Produktbeschreibung"];
$preis = #$_REQUEST["Preis"];
$result = $connect->query("INSERT INTO `shop`.`produkte` (`Produktname`, `Beschreibung`, `Preis`) VALUES ('$produktname', '$beschreibung', '$preis');");
if(!$result) {
echo "SQL Fehler: " . $connect->error;
die;
} else { echo "Letzte ID: " . $connect->insert_id;
}
}
?>
<table border="2" width="30%" style="border:1px solid #000000; border-spacing:inherit; text-align:left;">
<br><br>
<tr>
<td> Produkt </td>
<td> Beschreibung </td>
<td> Preis </td>
<td> Funktionen </td>
<?php
$result = $connect->query("SELECT * FROM produkte");
while($obj = $result->fetch_object()) {
echo '<tr><td>' . $obj->Produktname . '</td><td>' . $obj->Beschreibung . '</td><td>' . $obj->Preis . ' EUR ' . '</td><td> Bearbeiten, Löschen </td></tr>';
}
?>
</tr>
</table>
<?php
if (isset($_REQUEST["delete"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
$result = $connect->query("DELETE FROM `shop`.`produkte` WHERE `ProduktID` = $ProduktID;");
header('Location: ./shop.php');
}
if(isset($_REQUEST["id"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
// Update SQL Data?
}
if (!$result) {
echo "SQL Fehler: " . $connect->error;
die;
}
?>
</body>
</html>
I'm now looking for a way to retrieve the MySQL Data with the equivalent ID into the existing HTML Form and update it back to the MySQL Database... I'm currently learning PHP at the University and I can't think any further by myself.
It needs to get done withing this PHP File, like everything else is.
Thanks for any help! :)
If I understand you correct, you want to echo inserted row from database. Change the line:
$result = $connect->query("SELECT * FROM produkte");
into:
$result = $connect->query("SELECT * FROM produkte WHERE ID_prod_column = '$insertID'");
Try something like this. Just change "ID_prod_column" to correct name and $insertID to correct variable.
This question already has answers here:
delete row in my database using php pdo [closed]
(2 answers)
Closed 7 years ago.
I want to delete a selected row from my database, but I don´t know how to accomplish it. I am completly new to this topic, so it would be really nice, when you could explain to me.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> PHP F1 - Datenbank</title>
<style>
button {
margin:5px;
margin-left:-0px;
}
.insert {
position:relative;
margin:0px;
margin-bottom:5px;
margin-top:-25px;
}
</style>
</head>
<body>
<h2> Insert Dokument für deine Datensätze ! </h2>
<form action="F1_PHP.php" method="post">
<input type="text" name="jahr" placeholder="Albert-Park"> <br><br>
<input type="text" name="sieger" placeholder="Australien"> <br><br>
<input type="text" name="schnellster" placeholder="Melbourne"> <br><br>
<input type="text" name="strecke" placeholder="Laenge"><br><br>
<input type="submit" name="formdaten" class="insert" value="Insert"> <br>
</form>
<table border="1">
<tr>
<th></th>
<th>Strecke</th>
<th>Land</th>
<th>Stadt</th>
<th>Länge</th>
</tr>
<?php
try {
$server = 'mysql:dbname=f1;host=localhost';
$user = 'root';
$password = '';
$options = array
(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$pdo = new PDO($server, $user, $password, $options);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($pdo){
if (isset($_POST["formdaten"])) {
$jahr = $_POST["jahr"];
$sieger = $_POST["sieger"];
$schnellster = $_POST["schnellster"];
$strecke = $_POST["strecke"];
$eintrag = $pdo->prepare("INSERT INTO Strecke
(pk_Strecke, Land, Stadt, Laenge) VALUES (?, ?, ?, ?);");
$eintrag->execute(array($jahr, $sieger, $schnellster, $strecke));
if ($eintrag == true) {
echo "Eintrag war erfolgreich";
} else {
echo "Fehler";
}
}
}
}
catch (PDOException $error) {
echo 'Verbindung fehlgeschlagen: ' . $error->getMessage();
}
try {
$query= 'SELECT pk_Strecke, Land, Stadt, Laenge FROM Strecke';
$stmt = $pdo -> query($query);
$deleteString = "";
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
echo '<tr>';
echo ' <td>'."<input type='radio' name='markiert'>".'</td>';
echo ' <td>'. $row["pk_Strecke"].'</td>';
echo ' <td>'. $row["Land"]. '</td>';
echo ' <td>'. $row["Stadt"]. '</td>';
echo ' <td>'. $row["Laenge"]. '</td>';
echo '</tr>';
}
echo '</table>';
}
catch (PDOException $error) {
echo 'Fehler beim Lesen der Daten ' . $error->getMessage();
}
?>
<br>
<input type="submit" name="delete" value="Delete">
<?php
// delete button
?>
<input type="submit" name="update" value="Update">
<?php
//Update button
?>
<br>
<table border="1">
<tr>
<th> </th>
<th> Jahr </th>
<th> Sieger </th>
<th> Schnellste Runde </th>
<th> Strecke </th>
</tr>
<?php
try {
$query= 'SELECT pk_Jahr,Sieger,SchnellsteRunde,pk_fk_Strecke
FROM Rennen join Strecke on pk_fk_Strecke = pk_Strecke
order by pk_Jahr';
$stmt = $pdo -> query($query);
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) )
{
echo '<tr>';
echo ' <td>'."<input type='radio' name='markiert'>".'</td>';
echo ' <td>'. $row["pk_Jahr"].'</td>';
echo ' <td>'. $row["Sieger"]. '</td>';
echo ' <td>'. $row["SchnellsteRunde"]. '</td>';
echo ' <td>'. $row["pk_fk_Strecke"]. '</td>';
echo '</tr>';
}
echo '</table>';
}
catch (PDOException $error) {
echo 'Fehler beim Lesen der Daten ' . $error->getMessage();
}
?>
</body>
</html>
I appreciate every tip from you.
Use the following statements:
$sql = "DELETE FROM `Rennen` WHERE `pk_Jahr` = :id_to_delete";
$query = $db->prepare( $sql );
$query->execute( array( ":id_to_delete" => 'Value of pk_Jahr of the row to delete' ) );
It looks like you have a good idea of how to set up the PHP side of things, so I'll just deal with the SQL part.
The general syntax for a delete using PDO and MySQL would be as follows:
$query = "DELETE FROM TableName WHERE Field = :value";
$stmt = $pdo->prepare($query);
$stmt-> bindParam(':value', $value);
$stmt->execute();
The field you're querying against on that table needs to be unique, unless you're wanting to delete multiple rows (so best to use a primary key for the field and value).
It looks like you're using racing circuits in one of your tables, so your table may look like this (I'll call the table "circuits"):
id (primary key), circuit, country.
You may have the following data in it:
1, Albert Park, Australia
2, Silverstone, Great Britain
3, Adelaide, Australia
To delete Albert Park from the database, you'd run this:
$value = 1;
$query = "DELETE FROM circuits WHERE id = :value";
$stmt = $pdo->prepare($query);
$stmt-> bindParam(':value', $value);
$stmt->execute();
To delete all circuits in Australia (2 of the 3 above records):
$value = "Australia;
$query = "DELETE FROM circuits WHERE country = :value";
$stmt = $pdo->prepare($query);
$stmt-> bindParam(':value', $value);
$stmt->execute();
You could pass the value for $value through a form, and using bindParam() protects against SQL injection.
Once users fill out the "main_search" form, a list of results should populate, depending on their selection on the previous page. Either the entire list pops up or nothing at all. Below, my HTML starts here and then I need the results to populate on the next page. Please, please, please help!!
For a reference, check this site out: www.lemassif.com
<form name="main_search" action="displaydata.php" id="nl-form" class="nl-form" method="post">
<select name="main1">
<option value="featured" selected>any city</option>
<option value="city1">City 1</option>
</select>
<select name="reason">
<option value="family" selected>family</option>
<option value="romantic">romantic</option>
<option value="business">business</option>
<option value="leisure">leisure</option>
</select>
<select name="budget">
<option value="modest" selected>modest</option>
<option value="moderate">moderate</option>
<option value="lavish">lavish</option>
</select>
<div class="nl-submit-wrap">
<button class="nl-submit" type="submit" name="submit">Create my trip</button>
</div>
Here is my displaydata.php page that should populate the filtered results on the next page.
<?php
// Include the connection file.
include("func.inc.php");
$sql = mysql_query("SELECT * FROM venues");
if(isset($_POST['submit'])) {
$search_term = mysql_real_escape_string($_POST['$venues']);
$sql .= "WHERE city = '{$search_term}'";
$sql .= "OR reason = '{$search_term}'";
$sql .= "OR budget = '{$search_term}'";
}
$query = mysql_query($sql) or die(mysql_error());
?>
<table cellpadding="5" cellspacing="5">
<tr>
<td><strong>Venue Name</strong></td>
<td><strong>Image</strong></td>
<td><strong>Description</strong></td>
</tr>
<?php
while($row = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $row['venue_name']; ?></td>
<td><?php echo $row['image']; ?></td>
<td><?php echo $row['description']; ?></td>
</tr>
<?php }
?>
</table>
Here is my func.inc.php file.
<?php
include_once 'connection.php';
function close(){
mysql_close();
}
function city_query(){
$myData = mysql_query("SELECT city FROM venues");
while($record = mysql_fetch_array($myData)){
echo '<option value="' . $record['city'] . '">' . $record['city'] . '</option>';
}};
function reason_query(){
$myData2 = mysql_query("SELECT reason FROM venues");
while($record2 = mysql_fetch_array($myData2)){
echo '<option value="' . $record3['reason'] . '">' . $record2['reason'] . '</option>';
}};
function budget_query(){
$myData3 = mysql_query("SELECT budget FROM venues");
while($record3 = mysql_fetch_array($myData3)){
echo '<option value="' . $record3['budget'] . '">' . $record3['budget'] . '</option>';
}};
function search_venues() {
$city = $_POST['city'];
$reason = $_POST['reason'];
$budget = $_POST['budget'];
//Do real escaping here
$query = "SELECT * FROM venues";
$conditions = array();
if($city !="") {
$conditions[] = "city='$city'";
}
if($reason !="") {
$conditions[] = "reason='$reason'";
}
if($budget !="") {
$conditions[] = "budget='$budget'";
}
$sql = $query;
if (count($conditions) > 0) {
$sql .= " WHERE " . implode(' AND ', $conditions);
}
$result = mysql_query($sql);
return $result;
}
?>
What am I missing? Thanks in advance!
I think you're builting a malformed query in displaydata.php
It should be:
<?php
// Include the connection file.
include("func.inc.php");
$sql = "SELECT * FROM venues "; //<----note here: no mysql_query() and a blank at the end
if(isset($_POST['submit'])) {
$search_term = mysql_real_escape_string($_POST['$venues']);
$sql .= "WHERE city = '{$search_term}' "; //<----note here: blank at the end
$sql .= "OR reason = '{$search_term}' "; //<----note here : blank at the end
$sql .= "OR budget = '{$search_term}' "; //<----note here: blank at the end
}
[....]