Why is the last iteration given, instead of the current one? - php

I have some PHP & HTML code which fetches id's, names & statuses from a mysql database.
Using buttons and $_POST i'm attempting to update the MYSQL database when said the users button is clicked (it's a simple in/out board)
Here is my code
<?php
include 'confile.php';
if(isset($_POST['update'])) {
echo $_POST['update']. " "; //test to show correct name
echo $_POST['staffid']; //test to show the correct staffid << **THIS IS WHERE THE ISSUE IS**
//$incid = $_POST['staffid'];
//$sql = "SELECT status FROM staff WHERE id=$incid";
//$result = $conn->query($sql);
//echo $result; //show the status
} else {
//do nothing.
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Staff Board</title>
<body>
<div align="center" class="header">
<div class="header text">
<h1>Staff Board</h1>
</div>
<div class="header logo">
<img src="/assets/img/logo.gif" width="64px" height="64px">
</div>
</div>
<div id="conbox" align="center" class="content">
<hr>
<?php
//get all staff and their statuses
$sql = "SELECT id, firstname, surname, status FROM $staff ORDER BY surname ASC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
// assign results to values
$id = $row["id"];
$firstname = $row["firstname"];
$surname = $row["surname"];
$status = $row["status"];
$fullname = $firstname . " " . $surname . " " . $id; //The $id variable will be dropped from here... it's just for testing. note, it works here, the correct ID is added to the button value
if ($status == 1) { //pick the correct color for the status
$color = "butGreen";
} else {
$color = "butRed";
}
?>
<form class="staffGrid" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<input type="hidden" id="staffid" name="staffid" value="<?php echo htmlspecialchars($id); ?>"/> <!-- hidden input to pass the id to $_POST -->
<input type="submit" id="update" name="update" value="<?php echo htmlspecialchars($fullname); ?>"/> <!-- submit button to trigger POST -->
</form> <!-- added as per devpro & billyonecan -->
<?php
};
?>
</div>
</div>
</body>
</html>
When I first load the page, the buttons show correctly, and there is no test output at the top of the page, which I expect.
however, when I click a button, the page refreshes correctly, and shows the correct name for the button being pushed (from the echo on line 5), but the wrong staffid is given. It gives the LAST id for the while loop, instead of correct value for that button.
I had assumed that for each iteration, the values would be set for that specific element (the button)... obviously i'm incorrect here.
Why is this happening and how do I fix it?
Additional info
Confile.php has the following variables used in the code:-
$conn = new mysqli($server, $username, $password);
$staff = [Location of db table]
some output :-
echo $sql;
SELECT id, firstname, surname, status FROM inout.staff ORDER BY surname ASC
echo print_r($_POST);
Array ( [staffid] => 17 [update] => First Second 8 )

The solution was to ensure that the closing tag was present in the code, and in the correct location to prevent erroneous iteration!

Related

Indicate the newly added user with different color or symbol or div highlighting

I want to indicate the currently newly added user through symbol or unique color, like when someone click on Save and the user that is added should be shown in a different color or highlighted at that glimpse and then disappear after refresh, something like what the stackoverflow does in commenting system.
This is my code of index.php in this page I'v form and after submitting this form I' added the user to the database and then I'v shown them in descending order
<form action="save.php" method="post">
<div class="text-center" id='input_tag'>
<input type="text" name="name" id= 'input'>
<input type="submit" name="submit" class="btn btn-dark " id = "button" value="Save">
</div>
</form>
<div class="container">
<div class="row">
<div class="col-md-4">
<table width="100" class="table" id = 'tb'>
<?php
$connect = mysqli_connect('localhost','root','root','user');
$query = "SELECT name from userdata order by id DESC";
$run = mysqli_query($connect,$query);
while($row = mysqli_fetch_array($run))
{
echo "<tr>";
echo "<td>".$row['name']."<td>";
echo "</tr>";
}
?>
</table>
</div>
</div>
</div>
This is save.php where the user are added to DB and then redirected to the index.php page
$connect = mysqli_connect('localhost', 'root' ,'root' ,'user');
if($connect){
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$query = "INSERT INTO `userdata`(`name`) values ('$name')";
if(mysqli_query($connect,$query)){
header('location:index.php');
}
}
}
else{
echo "not connected";
}
You can achieve this with simple CSS and JS.
Change the header function in save.php to
header('location:index.php?added=1');
Add CSS style to index.php
<style type="text/css">
tr:last-of-type {
transition: .7s background;
}
</style>
At the end of index.php add the following
<?php
if (isset($_GET['added'])){
print '<script type="text/javascript">
document.querySelector("tr:first-of-type").style.background = "red";
setTimeout(function() {document.querySelector("tr:first-of-type").style.background = unset"},2000);
</script>';
}
?>
I'm assuming that the new user is going to be displayed at first.
If you want to display the user differently the first time, then you will need
some sort of flag that says if the user has been shown yet or not.
At the time you insert the user, set the didShow flag to false.
When you show the user, check the flag and if false, show the user
with the symbol and set the didShow flag to true.
When you show the user, if the didShow flag is false, show the
user without the symbol.
Add a new column named didShow to your database. Set it to default to 0 (false).
Change the query like this:
$query = "SELECT id, name, didShow from userdata order by id DESC";
In the loop, use different formatting and update the rows that have to be updated.
$run = mysqli_query($connect, $query);
$style = 'style="color:#ccc"';
while($row = mysqli_fetch_array($run))
{
echo "<tr>";
if ( $row['didShow'] == 0 ) {
echo "<td><span {$style}>".$row['name']."</span><td>";
$updateQuery = "UPDATE `userdata` SET didShow=1 WHERE id = {$row['id']}";
mysqli_query($connect, $updateQuery);
} else {
echo "<td>".$row['name']."<td>";
}
echo "</tr>";
}

How to input a number into a database based of a drop down menu consisting of data from another table in PHP?

I wish to input a number into a database based of a drop down menu consisting of data from another table.
Links table:
Category table:
So basically my drop down will consist of the category.cat written information. But when I submit the form it will input category.id into the links.catID column in the database.
The code I have so far is:
<?php
// since this form is used multiple times in this file, I have made it a
function that is easily reusable
function renderForm($links, $url, $catID, $type, $error){
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != ''){
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>Link Title: *<br></strong> <input type="text" name="links" size="40" value="<?php echo $links; ?>" /><br><br/>
<strong>URL: *<br></strong> <input type="text" name="url" size="40" value="<?php echo $url; ?>" /><br><br/>
<?php
require 'db/connect.php';
echo" <strong>Category: *<br></strong>";
echo "<select name='catID' id='catID'>";
$sql = "SELECT * FROM links";
$results = $db->query($sql);
if($results->num_rows){
while($row = $results->fetch_object()){
echo "<option>";
echo "{$row->catID}";
echo "</option>";
}
} echo "</select><br>";
?>
<br>
<strong>Type: *<br></strong> <input type="text" name="type" size="40" value="<?php echo $type; ?>" /><br><br/>
<p>* Required</p><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])){
// get form data, making sure it is valid
$links = mysql_real_escape_string(htmlspecialchars($_POST['links']));
$url = mysql_real_escape_string(htmlspecialchars($_POST['url']));
$catID = mysql_real_escape_string(htmlspecialchars($_POST['catID']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
// check to make sure all fields are entered
if ($links == '' || $url == '' || $catID == '' || $type == ''){
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($links, $url, $catID, $type, $error);
} else {
// save the data to the database
mysql_query("INSERT links SET links='$links', url='$url', catID='$catID', type='$type'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the form hasn't been submitted, display the form
renderForm('','','','','');
}
?>
Which gives me the following:
May be try this? (Considering the links.links columns and category.cat columns are common)
Store the value of dropdown in a variable say $dropdown_selected_option
Getting the id from the category table using sql:
$sql = "Select id from category where cat = '$dropdown_selected_option'";
$result = mysqli_query($conn, $sql);
Later run a query again to update the given fields in second table;
Update links set
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result))
{
// Run update query here where $row['id'] has the ID from the category table required.
}
}

PHP SEARCH and DELETE

I've changed the code following people advices but my delete button doesn't work. The empID is a VARCHAR, not an INT
The way i wanted it to be done when i search a string of letters i would get a list of employees containing that string, then choose some checkboxes and when button is pressed they'd get deleted from the DB and the list of not chosen would still stay on that page.
Thanks in advance for any help!!!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Delete Record</title>
<link rel="stylesheet" href="style1.css" />
<style>dialog{margin-left:100px}
select { font-size:24px;}</style>
</head>
<body>
<div class="header">
<h2>List of the employees with the name entered</h2>
</div>
<form name="action_form" action="" method="post" />
<div class="input-group">
<input type="text" name="name" placeholder="Employee name" />
</div>
<button type="submit" class="btn" name="submit">SEARCH</button>
<?php
require('db.php');
$errors = array();
if(isset($_POST["name"])&&!empty($_POST["name"]))
{
$name=$_POST['name'];
$sqlResult=mysqli_query($con, "SELECT * FROM Employee WHERE empName LIKE '%$name%'");
if (mysqli_num_rows($sqlResult) > 0)
{
echo "<table>";
while($row=mysqli_fetch_assoc($sqlResult))
{
echo "<tr>";
echo "<td>"; ?><input type= 'checkbox' name='num[]' value='<?php echo $row['empID'] ?>'/><?php echo "</td>";
echo "<td>".$row['empID']."</td>";
echo "<td>".$row['empName']."</td>";
echo "<td>".$row['deptNo']."</td>";
echo "<td>".$row['addCounty']."</td>";
echo "<td>".$row['salary']."</td>";
echo "</tr>";
}
echo "</table>";
}
if(isset($_POST['delete'])&&(!empty($_POST['num'])))
{
$list = array();
$list = $_REQUEST['num'];
foreach($list as $delID)
{
$sqlResult = mysqli_query($con,"DELETE FROM employee WHERE empID LIKE '$delID'");
}
}
}
?>
<div class="input-group">
<label>Please choose the person from the list below</label>
</div>
<div class="input-group">
<button type="submit" class="btn" name="delete">FIRE SELECTED</button><br><br>
<button type="reset" class="btn" name="reset">RESET</button><br><br>
Back to the Menu
</div>
</form>
</body>
</html>
Try this :
if(isset($_POST["name"])&&!empty($_POST["name"]))
{
$name=$_POST['name'];
$sqlResult=mysqli_query($con, "SELECT * FROM Employee WHERE empName
LIKE '%$name%'")
}
The reason for the error (Undefined variable $name) is because you are only setting $name in your "if" statement when $_POST['name'] is set, but you are running the line:
$sqlResult = mysqli_query($con, "SELECT * FROM Employee WHERE empName LIKE '%$name%'");
every time the page is loaded. Because you have used $name in the SQL string, but it isn't always declared, you get the error.
I'm finding your code a little hard to read, but I think you probably just want to put the mysqli_query() line inside the "if" statement.
if(isset($_POST['name'] && !empty($_POST['name'])) {
$name = $_POST['name'];
$sqlResult = mysqli_query($con, "SELECT * FROM Employee WHERE empName LIKE '%$name%'");
}
Looks like you should wrap the $delId in "%"
So your delete query should look like this:
$sqlResult = mysqli_query($con,"DELETE FROM employee WHERE empID LIKE '%$delID%'")
Also bear in mind that the like statement will delete any row where the id is like any other id. You might consider changing this to:
$sqlResult = mysqli_query($con,"DELETE FROM employee WHERE empID = '$delID' ")
Another thing to keep in mind is that you should consider using parameterized queries to prevent sql injection. Read thise for more details:
What is parameterized query?

how to delete the specified row from html table and also in mysql table using php

I am currently displaying the data using a html table in php from mysql database, and i also i am allowing the user to delete only their own data from the table,my problem is how to match the delete button with the respected row,when user clicks the delete buttons only the specified row should be deleted, but it deletes all the records which is connected to the user in the database, please help me how to do this, PS i am a learner and new to php
UPDATED CODE GOES HERE
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>View cart-d2dn</title>
</head>
<body>
<?php
include('header.php'); ?>
<h1>View Cart</h1>
<table border='1'>
<tr>
<th> VIN </th>
<th> Vehicle Description </th>
<th> Price </th>
</tr>
<?php
session_start();
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT vin,description,price FROM products where user_id='".$_SESSION['use_i']."' ";
$result = mysqli_query($conn, $sql);
$uq=mysql_query("select * from td_user where user_id='".$_SESSION['use_i']."' ");
$u_row=mysql_fetch_array($uq);
if(isset($_REQUEST['delete']))
{
$sql_s =" DELETE FROM `products` WHERE user_id='".$u_row['user_id']."' AND vin='".$_REQUEST['vin']."' " ;
$result_s = mysqli_query($conn,$sql_s) ;
if($result_s == true)
{
echo '<script language="javascript">';
echo 'alert("Deleted successfully")';
echo '</script>';
}
else
{
echo '<script language="javascript">';
echo 'alert("Error in deletion")';
echo '</script>';
}
}
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr>
<td>'.$row['vin'].'</td>
<td>'.$row['description'].'</td>
<td>'.$row['price'].' </td>
<td> <form method="post"> <input type="submit" name="delete" value="Delete">
<input type="hidden" name="vin" value="'.$row['vin'].'">
</form></td>
</tr>';
}
}
else
{
echo "Your cart is empty!";
}
?>
<?php
echo '</table>';
?>
<form><input type="button" value="Go back" onClick="window.location.href='automobile_list.php'">
<input type="button" value="Submit" onClick="window.location.href='mail.php'">
</form>
<?php
mysqli_close($conn);
?>
<?php
include('footer.php');
?>
</body>
</html>
You can do same only if your MySQL table have primary/unique key OR each row is different...
If VIN is unique then Let me show where you need to change. You need to SEND the unique key with delete request to detect which row selected to be deleted. Change the delete button code to:
<form method="post"> <input type="submit" name="delete" value="Delete">
<input type="hidden" name="vin" value="'.$row['vin'].'">
</form>
And in code of deleting row:
if(isset($_REQUEST['delete']))
{
$sql_s =" DELETE FROM `products` WHERE user_id='".$_SESSION['use_i']."' AND vin='".$_REQUEST['vin']."' ";
}
ALSO Delete the mysql code you are using to retrieve user ID (which is just before the code written above). [AND put this delete-code before displaying table(before selecting from product table-look at comments for more info :p )]
If vin is not the primary key then add primary in table by following mathed:
In mysql workbench: right click -> Alter table -> add column ID as INT and check the PK (primary key), AI (auto increment) -> apply -> finish.
Now use ID in place of VIN
As you said you are new to PHP. Then let me give a suggestion:
Use $_POST in place of $_REQUEST coz POST var contains data which sent by POST method only BUT REQUEST contains both POST & GET data... so anybody can delete via just typing in URL as ?delete=delete&vin=3
BTW, its not the issue here, but will help you in future.
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr id="<?php echo $row['id']; ?>" >
<td>'.$row['vin'].'</td>
<td>'.$row['description'].'</td>
<td>'.$row['price'].' </td>
<td> <form method="post"> <input type="submit" name="delete" value="Delete"></form> </td>
</tr>';
$vinrow =$row['vin'] ;
}
}

How to trigger a sql query by clicking a button in PHP?

so I am trying to make a a online shop , basically what isn't working is to execute a query when the buy clicks the "BUY" button.The query is :
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
and the button is
<form action=\"\" method=\"post\">
<input type=\"submit\" value=\"BUY\">
</form>
The whole code :
<?php
$id = $_SESSION['SESS_MEMBER_ID'];
include ('config2.php');
$result = mysql_query("select * from shop_vehicule ORDER BY id DESC");
$result2 = mysql_query("select * from accounts where id = '$id'");
while($row = mysql_fetch_array($result2))
$credit = $row['credits'];
while($row = mysql_fetch_array($result)){
$name = $row['nume'];
$price = $row['pret'];
$left = $credit - $price;
$vehid = $row['vehid'];
echo "<p><center><b>$name</b> | $price </center>
More information about $name</p>
<div id=\"toPopup\">
<div class=\"close\"></div>
<span class=\"ecs_tooltip\">Press Esc to close <span class=\"arrow\"></span></span>
<div id=\"popup_content\"> <!--your content start-->
<p>
The $name costs $price, after you'll have $left !</p>
<form action=\"\" method=\"post\">
<input type=\"submit\" value=\"BUY\">
</form>
</div>
</div>
<div class=\"loader\"></div>
<div id=\"backgroundPopup\"></div>";
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
}
mysql_close();
?>
Here's my attempt to help, I didn't test the codes but it should be working. Please read the comments in the codes. It explains what it does.
$id = $_SESSION['SESS_MEMBER_ID'];
/* To use PDO the following line must be included in your config2.php
define('DB_HOST', 'localhost');
define('DB_NAME', 'database');
define('DB_USER', 'username');
define('DB_PASS', 'password');
$db = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASS);
You can either use define or put the info straight into the PDO() function but I like it when it's easy to read and modify if needed.
*/
include ('config2.php');
$query = $db->prepare("SELECT * FROM accounts WHERE id = :id"); //Please use PDO or MySQLi, MySQL is outdated and unsecure. For this example, I am using my favorite method which is PDO.
$query->execute(array(':id' => $id));
$account = $query->fetchObject(); //Since we only need one line, we're going to use fetchObject object.
$query2 = $db->prepare("SELECT * FROM shop_vehicule ORDER BY id DESC");
$query2->execute();
$vehicules = $query2->fetchAll(); //I am using fetchAll due to multiple row will be returned.
foreach ($vehicules as $row) {
echo '<p><center><b>'.$row['nume'].'</b> | '.$row['pret'].' </center>
More information about $name</p>
<div id="toPopup">
<div class="close"></div>
<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!--your content start-->
<p>The '.$row['nume'].' costs '.$row['pret'].', after you\'ll have '.$account->credit - $row['pret'].' !</p>
BUY
</div>
</div>
<div class="loader"></div>
<div id="backgroundPopup"></div>';
}
// Basically what this part does is whenever the user click on the link, purchase will be set and it'll trigger the query to insert into the vehicule table then return a message if it was successful or not.
if ( isset($_GET['purchase']) ) {
$query = $db->prepare("INSERT INTO vehicles (model,owner) VALUES (':vehid',':id');");
$query->execute(array(':vehid' => $_GET['purchase'], ':id' => $id));
if ($query) {
echo 'Congratulations! You have successfully purchased the vehicule!';
} else {
echo 'An error has occured, the purchase was not complete.';
}
}
Use action=$_SERVER['PHP_SELF'] in the form tag and make a write the MySQL Insert Code in condition where isset($_POST['Buy']) is true.
you can do this in php, but in 2 different files.
The first will have the form, and the second will read the POST value and perform the query
Example(please fill missing pieces)
File 1 . php
<form action="file2.php" method="post">
<input type="hidden" value=<?php echo $vehid;?>" name="vehid">
<input type="hidden" value=<?php echo $id;?>" name="id">
<input type="submit" value="BUY">
</form>
File2.php
$vehid=$_POST['model'];
$id=$_POST['id'];
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
For a complete tutorial see http://www.w3schools.com/php/php_mysql_insert.asp

Categories