Update data from database from data got from database - php

I am trying to generate pin and serial number stored in database and display base on demand. For example, if someone needs 1 or 2 pin and serial number, after dispaying those pin and serial number, I want to update their value so that it can't be generated again. I have trouble updating the value.
<?php
if (isset($_POST['card']) && isset($_POST['cn'])) {
$card = $_POST['card'];
$no_of_pin = $_POST['cn'];
if (!empty($card) && !empty($cn)){
$query =mysql_query("SELECT id, pin, sn FROM pin_test WHERE value = '0' LIMIT $no_of_pin");
while($row = mysql_fetch_assoc($query))
echo 'PIN: ' .$row['pin']. ' SN:'. $row['sn']. ' id:'. $row['id'].'<br>';
$pin = $row['pin'];
$sn = $row['sn'];
$id = $row['id'];
$query2 = "UPDATE pin_test SET value = '1' WHERE id = $id";
if(mysql_query($query2)){
echo 'Successful';
}else{
echo 'Unsuccessful';
}
}else{
echo 'All fields are required.';
}
}
?>

You have a logical error which runs but doesn't really affect the table.
Try doing it like this:
$query2 = "UPDATE pin_test SET value='1' WHERE id='$id'";

Try the following syntax:
UPDATED:
$query2 = "UPDATE pin_test SET value=1 WHERE id='$id'";

Related

How do I increment a unique receipt number using PHP and update it in mysql database?

I am trying to increment a receipt number and add that new receipt number in the mysql database.
Here is my code that i have written:
<?php
require 'config.php';
$sql = "SELECT * FROM receipts ORDER BY id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$date = date("ymdhs");
$row2 = $row['id'];
$recnum = $date.'-00'.($row2+);
echo $recnum ;
$sql = "UPDATE receipts SET recnum='$recnum' WHERE id='$row2'";
if ($conn->query($sql) === TRUE) {
echo "updated";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
The order is not specified in your select query. Thus, you get no guarantees from your RDBMS that your data will come back in a certain order - or even in a consistent order - unless you query your data with an ORDER BY clause.
If you want to rely on this order, you must specify your desired order using ORDER BY.
"$row2+" wont increment $row2, use (++$row2) - plus plus should be before the variable- instead.
I have managed to debug my code.
here is the working code.
<?php
require 'config.php';
$sql = "SELECT * FROM receipts ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$date = date("ymdhs");
$row2 = $row['id'];
$recnum = $date.'-00'.$row2;
echo $recnum ;
$sql = "UPDATE receipts SET recnum='$recnum' WHERE id='$row2'";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>

Need to update one row in database

I am making an application and need to update only one row in my database. The way I build the application it updates all my rows in the database. Could someone look in my script and tell me how i can update one row?
I know i need to do something with id's but i dont know how..
Here is the script for the page where users can change the data from the database. In this way every record will update.
<section>
<?php
$sql = "SELECT naam, plaats.plaats, type.type, status FROM devices, type, plaats, status
WHERE devices.type_id = type.type_id
AND plaats.plaats_id = devices.plaats_id
AND status.status_id = devices.status_id
AND plaats.plaats ='benedenverdieping'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
echo '<table><tr><td>Naam</td><td>Plaats</td><td>Type</td><td>Status</td><td>open/dicht</td><td>Submit</td></tr>';
while($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>' .$row['naam']. '</td>';
echo '<td>' .$row['plaats']. '</td>';
echo '<td>' .$row['type']. '</td>';
echo '<td>' .$row['status']. '</td>';
echo '<td>';?>
<form action="opendicht.php" method="post">
<select name="opendicht">
<option name="open" value="1">open</option>
<option name="dicht" value="2">dicht</option>
</select>
<?php '</td>';
echo '<td>'?>
<input type="submit" value="Doorvoeren" name="submit">
</form>
<?php '</td>';
}
echo '</table>';
}
?>
</section>
Here is the script which execute the users input. Because of the sql query's it wont work for only one record. The way it works right now is the query updates every record with status_id 1 or 2. In the database the 1 stands for open and the 2 stands for closed. I can't find a way to let the query update only one row of data.
<?php
session_start();
$naam = $_SESSION['username'];
echo $naam;
include '../dbconnect.php';
date_default_timezone_set("Europe/Amsterdam");
$t=time();
$aanpassing = date("d-m-y h:i",$t);
$sel_device_id = ("SELECT device_id FROM devices");
$run_device_id = mysqli_query($con, $sel_device_id);
if(isset($_POST['submit']))
{ // Fetching variables of the form which travels in URL
$opendicht = $_POST['opendicht'];
if($opendicht =='1')
{
//UPDATE devices SET status_id = $opendicht, username = (SELECT user_id FROM users WHERE username = '$naam'), timestamp = '$timestamp' WHERE status_id = '2'
mysqli_query($con,"UPDATE devices SET status_id = $opendicht, username = '$naam', tijd = '$aanpassing' WHERE status_id = 2");
}
else
{
mysqli_query($con,"UPDATE devices SET status_id = $opendicht, username = '$naam', tijd = '$aanpassing' WHERE status_id = 1");
}
}
else{
echo "er is iets fout gegaan";
}
mysqli_close($con); // Closing Connection with Server
header( "refresh:0;url=index.php" );
?>
These are your UPDATE queries:
mysqli_query($con,"UPDATE devices SET status_id = $opendicht, username = '$naam', tijd = '$aanpassing' WHERE status_id = 1");
mysqli_query($con,"UPDATE devices SET status_id = $opendicht, username = '$naam', tijd = '$aanpassing' WHERE status_id = 2");
You're updating all the rows where the status_id is 1 or 2.
You need to add an AND condition to identify the unique row identifier to update.

PHP Update only updates last record

I have a form where the user input is used and compared with the same value on the database and if the input is invalid it rejects and does not update.
When the user input is correct the form thens forwards it and my code finds the corresponding ID from that input and then update it.
But so far what this does is update the last record.
Here's my code :
I do apologize it's a bit long so please bear with it. I am still a student and a total noob.
require("connect.php");
$query = mysql_query("SELECT * FROM driver LEFT JOIN vehicle ON driver.vehicle_id = vehicle.vehicle_id");
while($driverlist = mysql_fetch_array($query)){
$vehiclestatus = $driverlist['v_status'];
$driver = $driverlist['d_fname'];
$driver_id =$driverlist['driver_id'];
$v_model = $driverlist['v_model'];
$plate_number = $driverlist['plate_number'];
$vehicleid = $driverlist['vehicle_id'];
echo '<tr>';
echo '<td>'.$driver.'</td>';
echo '<td>'.$driver_id.'</td>';
echo '<td>'.$v_model.'</td>';
echo '<td>'.$plate_number.'</td>';
echo '</tr>';
}
if(isset($_POST['edit'])){
$vehicle_id = $_POST['vehicle_id'];
$driverid = $_POST['driver_id'];
require("connect.php");
mysql_query("UPDATE vehicle RIGHT JOIN driver ON vehicle.vehicle_id = driver.driver_id SET v_status = '1' WHERE driver.vehicle_id = '".$vehicle_id."' AND driver_id = '".$driverid."'")
or die(mysql_error());
}
if(isset($_POST['update']))
{
$vehicle_id = $_POST['vehicle_id'];
$driverid = $_POST['driver_id'];
require("connect.php");
mysql_query("UPDATE vehicle RIGHT JOIN driver ON vehicle.vehicle_id = driver.driver_id SET v_status = '0' WHERE driver.vehicle_id = '".$vehicle_id."' AND driver_id = '".$driverid."'")
or die(mysql_error());
header('Location: drivers.php');
}
if(!empty($_POST['registerbtn']))
{
$driver = $_POST['driver'];
require("connect.php");
$match_driver = mysql_query("SELECT * FROM driver WHERE d_fname = '$driver'");
$rows = mysql_num_rows($match_driver);
if($rows != 0)
{
while($row_driver = mysql_fetch_array($match_driver))
{
$a_fname = $row_driver[2];
$a_id = $row_driver[0];
}
}
error_reporting(0);
if($driver == $a_fname){
require("connect.php");
mysql_query("UPDATE trip_reservation SET driver_id = '".$a_id."' WHERE trip_id = '".$tripid."'");
//mysql_query("INSERT INTO trip_reservation (trip_id, driver_id) VALUES('".$tripid."', '".$a_id."') ON DUPLICATE KEY UPDATE trip_id = '".$tripid."'")or die(mysql_error());
echo "Driver Added Successfully";
}
else{
echo "The Driver is not found in the database <br>
Please input a valid Driver.";
}
}
else {
echo $registerform;
}
?>
Why joining tables when updating records on a single table.
And secondly, you're comparing a WHERE clause on a table you're not even updating
Instead of this
"UPDATE vehicle RIGHT JOIN driver ON vehicle.vehicle_id = driver.driver_id SET v_status = '0' WHERE driver.vehicle_id = '".$vehicle_id."' AND driver_id = '".$driverid."'"
Do this
"UPDATE vehicle SET v_status = '0' WHERE id = '".$vehicle_id."' AND driver_id = '".$driverid."'"
This is assuming your vehicle table has a primary key field named id and a foreign key field to the drivers_table named driver_id
And yes, it should update JUST ONE RECORD

What is The Scope Of PHP Variable for MYSQLI

I'm trying to set up a simple comment system and I want to create the correlation between the comment and the page landed.... so when a user arrives at blog.php?id=3 they would be presented the correct comments.
What I'm doing is creating the comments table with a pageid column. The pageid column will be filled when a user posts to the page. Maybe a hidden form field? How do I make this correlation within my MYSQLI
This is what I was thinking...
<?php
include_once("includes/check_login_status.php");
?>
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
include "includes/db_conx.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = "UPDATE content SET views=views+1 WHERE ID=$id";
$update = mysqli_query($db_conx,$sql);
$sql = "SELECT * FROM content WHERE id=$id LIMIT 1";
$result = mysqli_query($db_conx,$sql);
$productCount = mysqli_num_rows($result);
if ($productCount > 0) {
// get all the product details
while($row = mysqli_fetch_array($result)){
$article_title = $row["article_title"];
$category = $row["category"];
$readmore = $row["readmore"];
$author = $row["author"];
$date_added = $row["date_added"];
$article_content = $row["content"];
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
<?php
include_once "includes/db_conx.php";
$sql = "SELECT * FROM comment WHERE pageid ="$id"ORDER BY id DESC";
$sql_comments = mysqli_query($db_conx,$sql);
while($row = mysqli_fetch_array($sql_comments)){
$name = $row["name"];
$comment = $row["comment"];
$commentlist .= 'name : '.$name.'<br />comment : '.$comment.'<hr>';
}
//////////////
?>
Is the lower half in scope of the get variable? So that I can determine what page we're on? Can this type of variable be passed thorugh a variable in the comment form?
The 3rd sql statement contains an error:
$sql = "SELECT * FROM comment WHERE pageid ="$id"ORDER BY id DESC";
to
$sql = "SELECT * FROM comment WHERE pageid =".$id."ORDER BY id DESC";
You might also want to change the pre_replace statement to intval:
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
to
$id = intval($_GET['id']);
The reason being if $_GET['id'] = 'ABC123' then preg_replace will return 123 whereas the intval will return 0.

PHP MySQL single column/row display?

I'm trying to get a single result from my database, just one name.
I tried using;
$row = mysql_fetch_array(mysql_query("SELECT * FROM persons WHERE id = '$id'"));
echo $row['name'];
But that din't work, any other way to simply show only one result?
Thanks in advance!
[EDIT:]
(I'm using PHP 5.3)
<?php
include("connection.php");
$id = $_GET['deletid'];
$result = mysql_query("SELECT * FROM persons WHERE id = '$id' LIMIT 1");
if(!$result){
echo mysql_error();
}
if ($row = mysql_fetch_array($result)){
echo $row['name'];
}
echo "<p>id:$id</p>";
?>
If you need just the name and you need just one result you should rewrite your query as follow:
$row = mysql_fetch_array(mysql_query("SELECT name FROM persons WHERE id = '". (int) $id ."' LIMIT 1"));
Now to get the result you should just get it with a
$row['name'];
EDIT
Now that you posted your entire code i got what's wrong: You are deleting that result before getting its name. Basically you delete that user and then you attempt to get its name.
EDIT
<?php
include("connection.php");
if (empty($_GET['deleteid'])) {
exit('"deleteid" is empty');
}
$id = mysql_real_escape_string($_GET['deletid']);
$result = mysql_query("SELECT name FROM persons WHERE id = '". (int) $id ."' LIMIT 1");
if(!$result){
echo mysql_error();
}
$row = mysql_fetch_assoc($result); // for just one result you don't need of any loop
echo $row['name'];
echo "<p>id:". htmlspecialchars($id) ."</p>";
?>
try
$row = mysql_fetch_array(mysql_query("SELECT name FROM persons WHERE id = ". (int) $id));
echo $row['name'];

Categories