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
Related
I have two databases and i have one table "TabelaX" in database "Servidor1" with out data and other database "Servidor2" with one table "TabelaY". And i want do one select in table "TabelaY" and with her data do one Update in table "TabelaX" which is in another database. I already made some code but it is not working correctly.
<?php
$conn= mysqli_connect('localhost','root',null,'Servidor2') or die
(mysqli_connect_error());
if (!$conn) {
die("Falha de conexao: ". mysqli_connect_error());
}
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
$result = mysqli_query($conn, $sql);
mysqli_select_db($conn,"Servidor1");
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$row1 = $row["ID"];
$row2 = $row["Data"];
}
} else {
echo "0 results";
}
$sql = "INSERT INTO Servidor1.TabelaX (ID, Data)
SELECT ID, Data
FROM Servidor3.TabelaW
WHERE ID = $ID;";
$sql = "UPDATE Servidor1.TabelaX SELECT ID, Data FROM
Servidor3.TabelaW SET Data = $row2 WHERE $row1 = $ID;";
if (mysqli_multi_query($conn, $sql)) {
echo "Dados Inseridos";
} if (mysqli_multi_query($conn, $sql)) {
echo "Dados Atualizados";
}
mysqli_close($conn);
I have no idea what your query is trying to do, because you assign to $sql twice without ever executing the first query, but if you're asking how to update a row in tableX based on data from tableY, then:
UPDATE Servidor1.TabelaX as x, Servidor2.TabelaY as y
SET x.Data = y.Data
WHERE x.id = y.id
AND x.id = $someIdForWhichYouWantToUpdate
Also, do not do this:
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
Imagine what happens when the user posts 1; DROP DATABASE Servidor1 into the form. This is called SQL injection and your code is full of vulnerabilities to it.
I am joining two table and I want to update all the rows.
<?php
include("connection/mysqlconnect.php");
$sql=" SELECT course.duration, course.id, students.ID
FROM course, students
where course.id=course_id and course.duration = '2'";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count>=1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$stat = 'Active';
$year = '2nd Year';
$Graduated = 'Graduated';
$sql1 = "UPDATE students SET Year='$Graduated', Status='non-Active'
WHERE ID = '$id' and (status='$stat' and Year='$year')";
echo "$id</br>";
}
}
?>
I tried the Select Statement above in "Run SQL query" and it query the result i want. and I want to update all of the query, but I cant. I tried Putting echo under the update and it echo the ID's I need to update, but my update statement is not executing.
Instead of selecting all students then updating one by one, you can actually to this in one shot by joining both tables and updating it.
UPDATE students s
INNER JOIN course c ON c.id = s.course_id
SET s.Year = '$Graduated',
s.Status = 'non-Active'
WHERE c.duration = '2'
AND s.status = '$stat'
AND s.Year = '$year'
It must also be taken into consideration that the query above is vulnerable with sql injection. This article below will guide you how to prevent from it.
How to prevent SQL injection in PHP?
The issue with the first query is that there are two columns with the same name; ID. So referencing the ID from the row generates an error. Use alias to fix it as shown below. For a better performance use an inner join instead. You also forgot to run the update query again your database.
<?php
include("connection/mysqlconnect.php");
$sql=" SELECT course.duration, course.id as cID, students.ID as sID
FROM course JOIN students ON course.id=course_id
where course.duration = '2'";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count>=1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['sID'];
$stat = 'Active';
$year = '2nd Year';
$Graduated = 'Graduated';
echo "Student ID to be updated: $id<br/>";
$sql1 = "UPDATE students SET Year='$Graduated', Status='non-Active'
WHERE ID = '$id' and (status='$stat' and Year='$year')";
//you have to execute the query for the update to be done.
if ($conn->query($sql1) === TRUE) {
echo "Record updated successfully ";
} else {
echo "Error updating record: " . $conn->error;
}
}
}
$conn->close();
?>
This is a table column that display message depends on user preferred language choice in the DB. eg if preferred language is ENG only the eng
message will show
PS: in the database, there's 3 column storing 3 types of message of different languages
<?php
$possibleLang = ["繁體","简体","ENG"];
$testAreaField = ["traditionalmessage","simplifiedmessage","engmessage"];
$treatmentName = ["vaccinename1","vaccinename2","vaccinename3"];
$treatmentNameSuffix = ["\n下一個注射期為:","\n下一个注射期为:","\nNext
injection period will be:"];
$index = array_search($row['language'],$possibleLang);
?>
<td>
<textarea rows="3" cols="18" class="url" name="<?php echo
$testAreaField[$index]; ?>[]" data-value="<?php echo
$row[$treatmentName[$index]] . $treatmentNameSuffix[$index]; ?>"><?php echo
$row[$testAreaField[$index]]; ?>
</textarea>
</td>
This table is at an edit page that displays data from DB and also updates data back to the DB.
if (isset($_POST['submit'])){
foreach ($_POST['patientid'] as $index => $patientid) {
$id = mysql_real_escape_string($_POST['id'][$index]);
$data1 = mysql_real_escape_string($patientid);
$data17 = mysql_real_escape_string($_POST['patienthkid'][$index]);
$data2 = mysql_real_escape_string($_POST['vaccineid'][$index]);
$data5 = mysql_real_escape_string($_POST['vaccinename3'][$index]);
$data6 = mysql_real_escape_string($_POST['totalnoofinjection'][$index]);
$data7 = mysql_real_escape_string($_POST['nthinjection'][$index]);
$data8 = mysql_real_escape_string($_POST['date'][$index]);
$data9 = mysql_real_escape_string($_POST['nextdate'][$index]);
$data10 = mysql_real_escape_string($_POST['skip'][$index]);
$data11 = mysql_real_escape_string($_POST['language'][$index]);
$data12 = mysql_real_escape_string($_POST['traditionalmessage'][$index]);
$data13 = mysql_real_escape_string($_POST['simplifiedmessage'][$index]);
$data14 = mysql_real_escape_string($_POST['engmessage'][$index]);
$data15 = mysql_real_escape_string($_POST['status'][$index]);
$data16 = mysql_real_escape_string($_POST['nurse'][$index]);
if ($data12 != null) {
mysql_query("UPDATE patientvaccinedetail SET patientid
='$data1',patienthkid
='$data17',vaccineid='$data2',vaccinename3='$data5',
totalnoofinjection='$data6',nthinjection='$data7',
date='$data8',nextdate='$data9',skip='$data10',language='$data11',
traditionalmessage='$data12',status='$data15',nurse='$data16' WHERE
id=$id") or die(mysql_error());
}
else if ($data13 != null) {
mysql_query("UPDATE patientvaccinedetail SET patientid
='$data1',patienthkid
='$data17',vaccineid='$data2',vaccinename3='$data5',
totalnoofinjection='$data6',
nthinjection='$data7',date='$data8',nextdate='$data9',
skip='$data10',language='$data11',
simplifiedmessage='$data13',status='$data15',nurse='$data16' WHERE
id=$id") or die(mysql_error());
}
else if ($data14 != null) {
mysql_query("UPDATE patientvaccinedetail SET patientid
='$data1',patienthkid ='$data17',vaccineid='$data2',
vaccinename3='$data5', totalnoofinjection='$data6',
nthinjection='$data7',date='$data8',nextdate='$data9',
skip='$data10',language='$data11',
engmessage='$data14',status='$data15',nurse='$data16' WHERE id=$id")
or die(mysql_error());
}
}
}
The issues are whenever I click save and only one column of the message is SAVED, other two column are updated as NULL in the database. The desired outcome is the update both 3 columns while only 1 column is visible to the page.
Any idea. Thanks in advance
Do not update columns which are not being targeted for update. For example, if the traditional message were selected, then you would update only this column. I would probably use separate queries here.
foreach ($_POST['patientid'] as $index => $patientid) {
$id = mysql_real_escape_string($_POST['id'][$index]);
$data1 = mysql_real_escape_string($patientid);
$data2 = mysql_real_escape_string($_POST['traditionalmessage'][$index]);
$data3 = mysql_real_escape_string($_POST['simplifiedmessage'][$index]);
$data4 = mysql_real_escape_string($_POST['engmessage'][$index]);
if ($data2 != null && $data2 != '') {
mysql_query("UPDATE table SET patientid ='$data1',
traditionalmessage='$data2' WHERE id=$id") or die(mysql_error());
}
else if ($data3 != null && $data3 != '') {
mysql_query("UPDATE table SET patientid ='$data1',
simplifiedmessage='$data3' WHERE id=$id") or die(mysql_error());
}
else if ($data4 != null && $data4 != '') {
mysql_query("UPDATE table SET patientid ='$data1',
engmessage='$data4' WHERE id=$id") or die(mysql_error());
}
}
Note that I believe you are using a very old and deprecated PHP API for MySQL. For starters, it would benefit you a lot by using prepared statements.
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'";
I'd like to check if a value is already in the table.
The structure of my table is this:
ApplicantId = INT
EventId = INT
StudentId = INT
No need to use unique because these table has dependencies.
Below is what I have tried so far:
include('../connectdb.php');
$ScholarPointId = $_GET["ScholarPointId"];
$Point = $_GET["Point"];
$ScholarId = $_GET["ScholarId"];
$EventId = $_GET["EventId"];
$verifysql = mysql_query("SELECT EventId FROM scholar_attended_events WHERE ScholarId ='$ScholarId' ");
#$resultVerify = mysql_fetch_assoc($verifysql);
$num_rows = mysql_num_rows($verifysql);
if( $num_rows > 0 )
{
$script = "<script>
alert('The user has already attended this event!');
</script>";
header('updatescholarpoints.php');
exit();
}
else{
$result = mysql_query("UPDATE scholar_points
SET scholar_points.Points =
scholar_points.Points + $Point
WHERE scholar_points.ScholarPointId = '$ScholarPointId' ") or die(mysql_error());
mysql_query("INSERT INTO scholar_attended_events (EventId , ScholarId) VALUES( '$EventId' , '$ScholarId' ) ")
or die(mysql_error());
}
?>
What I want is to check if the EventId is already in taken by the Student = StudentId. If so, then system will prompt an alert box. Otherwise, Update and Insert into respective table. How can I do this? It seems I miss something in here. If you could help, I really appreciate it.
just missing an = ?
$verifysql = mysql_query("SELECT EventId FROM scholar_attended_events WHERE ScholarId =$ScholarId ");
(and use PDO or mysqli, your code is really in a deprecated mode)