Need to update one row in database - php

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.

Related

Sending options from html select box into database

Update: I’m now getting an error telling me that roomID is null and this is why it’s not going into the database. Can you see why it would be null when it should be the option that the user selects in the select box?
I'm working on a hotel booking system as an exercise. I am trying to make a form that will insert a new booking into the database. I have the customer and room IDS in the mySQL database and I have put them into HTML select boxes for the user to select an option.
This works fine until I try to save the new booking to the database. I don't get any errors and it tells me the booking has been saved on my page but if I go into the database it hasn't been saved. I have tried inserting the customerID and roomID values from text boxes so just typing it in instead of the drop down menu and that inserts into the database just fine.
I'm pretty sure the problem is something to do with getting the value out of the select box and into the POST variable but I'm not 100% sure. I've only been coding for 6 months so I don't really know what I'm doing! I've tried to figure it out by looking at other examples on here but nothing seems to work.
Here's my code:
Getting the data to fill the select boxes:
//Locate room names
$query = $query = 'SELECT `roomID` FROM `room`';
$result2 = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result2);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result2);}
//Locate customerIDs
$query = $query = 'SELECT `customerID` FROM `customer`';
$result = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result);}
Creating Select boxes:
<form method="POST" action="newbooking.php">
<p>
<label for="customerID">Customer ID: </label>
<?php
echo "<select name='customerID'id='customerID' input type='number'>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='customerIDselect'>" . $row['customerID'] . "</option>";
//customerID
$customerID = cleanInput($_POST['customerIDselect']);
}
echo "</select>";
?>
</p>
<p>
<label for="rooms">Room (name, type, beds): </label>
<?php
echo "<select name='roomID'id='roomID' input type='number'>";
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "<option value='roomIDselect'>" . $row['roomID'] . "</option>";
//roomID
$roomID = cleanInput($_POST['roomIDselect']);
}
echo "</select>";
?>
</p>
Inserting data into database:
//save the customer data if the error flag is still clear
if ($error == 0) {
$query = 'INSERT INTO `bookings` (`customerID`,`roomID`,`checkin`,`checkout`, `extras`) VALUES (?,?,?,?,?)';
$stmt = mysqli_prepare($DBC,$query); //prepare the query
mysqli_stmt_bind_param($stmt,'sssss', $customerID, $roomID, $checkin, $checkout, $extras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>booking saved</h2>";
} else {
echo "<h2>$msg</h2>".PHP_EOL;
}

PHP Selecting from table 1 and inserting in table 2 with id return be 0 on table 2

first sorry for my english. I have a problem on my isset Here's the codes:
PHP:
if(isset($_POST['insert'])) {
$insert = $_POST['insert'];
}
{
require('./clanconfig.php');
$cln = $_POST['clanname'];
$cms = $_POST['mesa'];
$checkup = "SELECT id FROM clan WHERE cname='$cln'";
$upsql = mysqli_query($conn, $checkup);
while($srcclan=mysqli_fetch_array($upsql) )
{
$checked = $srcclan['id'];
}
$sql2 = "INSERT INTO clanrequest (clanid, plname, message, playerid) VALUES('$cln', '$uname', '$cms', '$player_id')";
$sql3 = mysqli_query($conn, $sql2) or die();
}
mysqli_close($conn);
Problem is While searching on table1 with a Post value it's okay but while inserting on table 2 with a id of table 1 and on table 2 adding but value is only 0 on id column
Html:
<form class="clan-form-join action="clanjoin.php" method="post">
<?php
require('./clanconfig.php');
$sql = "SELECT * FROM clan";
$sql2 = mysqli_query($conn, $sql);
echo "<html>";
echo "<body>";
echo "<select name='clanname'>";
while($sonuct=mysqli_fetch_array($sql2) )
{
$cnamer = $sonuct['cname'];
echo '<option value=" '.$cnamer.'">'.$cnamer.'</option><br />';
}
echo "</select>";
echo "</body>";
echo "</html><br>";
echo'<b>Message</b><br><textarea name="mesa" rows=3 cols=40></textarea><br/>';
echo'<input type="submit" name="insert" class="clanbutton" value=" Send Application ">';
?>
</form>
Here's the html codes, i select the details of clan in a clan table and when member select the clan name and insert the button the codes sent with a clan name selected like test clan in isset value and in the isset select the id of clan selected on option value clan name on table clan and return to insert clan request with name,id of player and where id of clan the problem is id of clan adding automatically 0 without add real id of clan
All the code for inserting should be inside the if (isset($_POST['insert'])). You only have the variable assignment there (and you never even use that variable), you have the rest of the code in a separate block (there's no purpose to putting it in a block).
if(isset($_POST['insert'])) {
$insert = $_POST['insert'];
require('./clanconfig.php');
$cln = $_POST['clanname'];
$cms = $_POST['mesa'];
$checkup = "SELECT id FROM clan WHERE cname='$cln'";
$upsql = mysqli_query($conn, $checkup);
while($srcclan=mysqli_fetch_array($upsql) )
{
$checked = $srcclan['id'];
}
$sql2 = "INSERT INTO clanrequest (clanid, plname, message, playerid) VALUES('$cln', '$uname', '$cms', '$player_id')";
$sql3 = mysqli_query($conn, $sql2) or die();
mysqli_close($conn);
}

SQL query failing to INSERT new row into table

I have a chunk of PHP code that triggers if a button is pressed by the user. What I expect to happen is it checks to see if the user has the skill already assigned to them, and if not it performs an INSERT. Then if it does do nothing. And finally if the checkbox next to a skill is un-checked it checks to see if they have the skill already assigned and delete it if found.
The code is deleting the skills from the user no matter the condition of the checkboxes. Im sure I must be missing something but after starring at the code for hours I cannot see it.
Can anyone suggest a resolution?
PHP code:
if(isset($_POST['Update']))
{
$default = 0;
foreach($skills_array AS $skills_id=>$skills_name)
{
if (isset($_POST[$skills_name]))
{
if (empty($_POST[$skills_name.'exp']))
{
$exp = $default;
}
else
{
$exp = $_POST[$skills_name.'exp'];
}
$sql = $con->query("SELECT count(`UserID`) as total FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
if ($row = mysqli_fetch_assoc($sql))
{
$sql = $con->query("INSERT INTO `userskills` ( `UserID`, `SkillID`, `Experience`) VALUES ('$User', '$skills_id', '$exp')")
or die(mysqli_error($con));
//If the checkbox is not checked it will check to see if skill is already a skill assigned to the user. If they are it will delete it. If not it will ignore.
}
else
{
$sql = $con->query("UPDATE `userskills` SET `Experience` = '$exp' WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
}
}
else
{
$sql = $con->query("DELETE FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
}
}
header('Location: Account.php');
die();
}
else
{
echo 'Incorrect password please try again.';
}
}
HTML Code:
<div class="RightBody">
<form id="form2" name="form2" method="post" enctype="multipart/form-data">
<p><h3>Skills:</h3>
<?php
$result1 = $con->query("SELECT skills.`SkillID`, skills.`Description`, COUNT(userskills.`SkillID`) AS SkillUserHas, MAX(`Experience`) AS Experience
FROM `skills`
LEFT OUTER JOIN userskills
ON skills.`SkillID` = userskills.`SkillID` AND userskills.`UserID` = '$User'
GROUP BY skills.`SkillID`, skills.`Description`
ORDER BY FIELD(skills.`SkillID`, 1, 7, 9, 3, 4, 5, 6, 8)")
or die(mysqli_error($con));
while ($skillrow = $result1->fetch_assoc())
{
?>
<div class="CheckboxText">
<?php
echo '<label>';
echo '<input type="checkbox" name="'.$skillrow['Description'].'" id="CheckboxGroup1_'.$skillrow['SkillID'].'" class="skillselect" value="yes" '.(($skillrow['SkillUserHas'] > 0) ? 'checked' : '').'>';
echo $skillrow['Description'].'</label>';
echo '<input type="number" name="'.$skillrow['Description'].'exp" class="expnumber" placeholder="Enter Experience in years." value="'.$skillrow['Experience'].'">';
echo '<br />';
echo '<br />';
}
?>
</div>
</p>
</form>
</div>
Im not familiar with PHP, but yesterday I help in a similar problem
Here you create your query but your COUNT will always return a row, and if not skill the value is 0
$sql = $con->query("SELECT count(`UserID`) as total FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
So instead of if ($row = mysqli_fetch_assoc($sql)) you need something like
$row = mysqli_fetch_assoc($sql);
$skill = $row['total'];
if ($skill == 0 )
But that doesnt solve the error you describe, delete all skills or just the one selected?
Any way you have to check this IF that is the branch sending your skill to delete.
if (isset($_POST[$skills_name]))
This mean your $skills_name isnt defined. Maybe you should check for the value inside the array $skills_array?
My second guess check the code create on the webpage. Right click your page and selece see source code

Update data from database from data got from database

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'";

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

Categories