I will put my code below. I basically check on value in the database and if it's 1 or 0 i want to change it to the opposite (so if 1 change it to 0, if 0 change to 1).
If I execute one SQL statement without using the function (but then it only works one way once) it works. But if I want to execute the specific function with it depending on what the value currently is, it doesn't seem to work. Do you know what I am doing wrong here?
<?php
$date_id = $_POST['dateID'];
$con = mysqli_connect("localhost","root","","secret_name");
$sql = "SELECT * FROM date_list WHERE date_id = ".$dateID;
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
$occupied = $row['occupied'];
if($occupied == 1){
decross_entry();
} elseif( $occupied == 0){
cross_entry();
}else{
echo "Error"
}
}
function decross_entry(){
$dateID = $_POST['dateID'];
$con_2 = mysqli_connect("localhost","root","","secret_name");
$sql_edit = "UPDATE date_list SET occupied= '0' WHERE date_id = ".$dateID;
if($con_2 -> connect_errno){
echo "Failed to connect to database!" . $con_2->connect_error;
}
if ($con_2 -> query($sql_edit) === TRUE)
{
echo "saved!";
} else {
echo "error: " .$sql_edit."<br>".$con_2->error;
}
}
function cross_entry(){
$dateID = $_POST['dateID'];
$con_2 = mysqli_connect("localhost","root","","secret_name");
$sql_edit = "UPDATE date_list SET occupied= '1' WHERE date_id = ".$dateID;
if($con_2 -> connect_errno){
echo "Failed to connect to database!" . $con_2->connect_error;
}
if ($con_2 -> query($sql_edit) === TRUE)
{
echo "saved!";
} else {
echo "error: " .$sql_edit."<br>".$con_2->error;
}
}
?>
If the only possible values of occupied are 0 and 1 then you can do what you want in one query without needing to look up the value of occupied first:
UPDATE date_list
SET occupied = 1 - occupied
WHERE date_id = ?
In PHP, using a prepared query to avoid SQL injection:
$date_id = $_POST['dateID'];
$con = mysqli_connect("localhost","root","","secret_name");
$sql = "UPDATE date_list SET occupied = 1 - occupied WHERE date_id = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param('i', $date_id); // use 's' if $date_id is not an integer
$stmt->execute();
Related
if (isset($_POST["AddErrorCode"]))
{
$AddErrorCodeDB = $_POST["AddErrorCode"];
$AddErrorDescriptionDB = $_POST["AddErrorDescription"];
$AddQuantityDB = $_POST["AddQuantity"];
$AddStartDateDB = $_POST["AddStartDate"];
$AddCompletionDateDB = $_POST["AddCompletionDate"];
$AddReviewTypeDB = $_POST["AddReviewType"];
session_start();
$WO_ID = $_SESSION['SELECTED_WO_ID'];
if ($AddReviewTypeDB === 'PR')
{
$AddReviewerType = 'Peer Review';
$insert = "INSERT INTO `wo_errorinfo` (
`Error_Code` ,
`Error_Description` ,
`Error_Quantity` ,
`Review_Type` ,
`WO_NO`) VALUES (
'$AddErrorCodeDB' ,
'$AddErrorDescriptionDB' ,
'$AddQuantityDB' ,
'$AddReviewerType' ,
'$WO_ID')";
if ($AddCompletionDateDB === '')
{
//echo 'ritwik';
$status = 'Peer RWK';
$update = "UPDATE `associated_wos` SET `WO Status` = '$status' WHERE `ID` = '$WO_ID'";
}
else
{
//echo 'ritwik1';
$status = 'Peer Review Complete';
$update = "UPDATE `associated_wos` SET `WO Status` = '$status' WHERE `ID` = '$WO_ID'";
}
$sql = "SELECT * FROM `wo_reviewerqa` WHERE `WO_ID` = '$WO_ID' AND `reviewType` = '$AddReviewerType'";
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_num_rows($result);
//echo $num_rows;
if ($num_rows === 0)
{
//echo 'ritwik';
$insertreview = "INSERT INTO `wo_reviewerqa` (
`reviewType`,
`reviewStartDate`,
`reviewCompleteDate`,
`WO_ID`) VALUES (
'$AddReviewerType',
'$AddStartDateDB',
'$AddCompletionDateDB' ,
'$WO_ID')";
//echo $insertreview;
}
else
{
if ($AddStartDateDB !== '')
{
echo "<script type='text/javascript'>alert('Review Already Started, Start Date cant be changed');</script>";
}
}
if($conn->query($insertreview) === True)
{
echo "<script type='text/javascript'>alert('Start date updated successfully');</script>";
}
if ($conn->query($insert) === True)
{
echo "<script type='text/javascript'>alert('Error Code Submitted successfully');</script>";
}
}
All my condition are getting satisfied. I am even getting all the correct values in the echo but only the first insert query i.e. insert into 'wo_errorinfo' is working and all else are having no effect on the table. Can we not insert into multiple tables during a session. Is it due to session_start()? I have been trying to figure this out for more 1 day now but can't figure it.
You need to execute your statements, currently only $sql is executed.
You should also avoid building queries by concatenating strings as this will leave you vulnerable to SQL injection attacks where your users can modify your queries by passing special characters in the input. You should use mysqli::prepare, e.g:
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
}
Current update: I've cleaned up the code, and there are still some issues.
NOTE this code runs every 3 seconds. The outermost 'else' statement seems to run, setting the time to 0 in the database table, but then there is no activity.
After the initial time of running, the outermost 'else' statement should never run, and the time value stored under the user's alias should keep updating with the latest time stamp, but it just sits at '0'.
This is the JS that runs the php file:
//CHECK FOR NEW CHAT MESSAGES
setInterval(function()
{
$.post("chat_update.php", function(data) { $("#rect_comments_text").append(data);} );
}, 3000);
Code:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$time_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$timestamp = time();
$last_time_query = "SELECT alias FROM $time_table";
$last_time_result = mysqli_query($connection,$last_time_query);
$last_time_rows = mysqli_fetch_array($last_time_result);
if ($last_time_rows['alias'] === $alias)
{
$last_time = $last_time_rows['time'];
$query = "SELECT * FROM $table WHERE time > $last_time ORDER BY text_id ASC"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
//APPEND NEW MESSAGES
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
}
//UPDATE LAST SYNC TIME
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
echo '<p> HERE </p>';
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','0')";
mysqli_query($connection,$update_query);
}
?>
You try this
$sql_update = "UPDATE time_table SET time= '$timestamp' WHERE alias = '$alias'";
if ($con->query($sql_update ) === TRUE) {
}
else{
echo "Error: " . $sql_update . "<br>" . $con->error;
}
You need to only check mysqli_num_rows to whether to insert or update data. You have to add ' around $alias in select query also. change your code as below:
//EITHER UPDATE THE EXISTING VALUE OR CREATE ONE FOR FIRST TIME VISITORS...
$last_time_query = "SELECT * FROM $time_table WHERE alias = '$alias'"; //change here add '
$last_time_result = mysqli_query($connection,$last_time_query);
if (mysqli_num_rows($last_time_result) == 0) //Only check number of rows
{
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','$timestamp')";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
I'm inserting into my database id and hours, which is working successfully. However when i insert a new value for an id that has a previous value, the old val isn't replaced by the new, instead they're kept both. I'm trying to update the function with an if/else statement (commented part). But still the same result. The if/else statement must check first if hours (a column in the table) value is empty, if so then perform sql insert, else perform sql update. Any help please?
if (isset($_POST['submit'])) {
$hours = $_POST['Hours'];
$selectid = $_POST['SelectID'];
$sql1 = "INSERT INTO `editedworkhours` (`id`,`H`) VALUES('$selectid','$hours')";
$getResult = mysql_query($sql1);
if (mysql_affected_rows() > 0) {
} else {
}
$tempname = $row['Field'];
$sql2 = "UPDATE editedworkhours SET H ='" . $_GET["hours"] . "' WHERE IDNumber='" . $_GET["selectid"] . "'";
$result2 = mysqli_query($con, $sql2);
if ($con->query($sql2) === TRUE) {
} else {
}
}
echo $menu;
Try this
<?php
if(isset($_POST['submit']))
{
$addedhours = $_POST['AddedHours'];
$selectaf = $_POST['SelectAF'];
$sql1="SELECT * FROM editedworkhours WHERE AFNumber='$selectaf' and AddedWH ='$addedhours'";
$getResult = mysql_query($sql1);
$count = count($getResult);
if(!empty($count) || $count==1)
{
$tempname = $row['Field'];
$sql2 = "UPDATE editedworkhours SET AddedWH ='$addedhours' WHERE AFNumber='$selectaf'";
$result2 = mysql_query($sql2);
if (isset($result2))
{
//Data inserted
}
else
{
//Insert Failed
echo '<script>swal("Error", "Something went wrong error");</script>';
}
echo '<script>swal("Success", "Changes have been saved", "success");</script>';
}
else
{
$sql3 = "INSERT INTO editedworkhours (AFNumber,AddedWH) VALUES('$selectaf','$addedhours')";
$Result = mysql_query($sql3);
if(isset($Result))
{
echo 'Success';
}
else
{
echo 'Failed';
}
}
}
echo $menu;
I'm preparing some statements and want to check if the row exists before I update. If it exists then update it, if it doesn't then output a message "No such animal". I have the update bit working, but unsure how to check if the row exists. Please assist.
$v = array();
$v[] = $_POST['status'];
$v[] = $_POST['id'];
$dbh = dbh_get();
$sql = 'UPDATE tap SET status=?
WHERE id =?';
$stmt = $dbh->prepare($sql);
$stmt->execute($v);
\\ if row isn't there display message "No such animal"
\\ otherwise print the below
printf("Status was changed to - %s", $v[0]);
\\then either way have my continue button for me to click on
print '<div class="button" style="float:left;" onclick="window.location.href=\'admin.php\';">Admin</div>' . "\n";
dbh_free($dbh)
According to your question, you want to check if the row exists before performing update. you can try this -
$id_exist = 0;
$sql = "SELECT id
FROM tap" ;
$sql_prepare = $dbh->prepare($sql);
$sql_prepare->execute();
while($row = $sql_prepare->fetchObject()) {
if($_POST['id'] == $row->id) {
$id_exist = 1;
}
}
if($id_exist == 1) {
// perform update here
} else {
echo 'No such animal';
}
$sql = "UPDATE reservations SET status = '$this->status',remaining_time ='$this->remain',cost = '$this->cost' WHERE id = '$this->id'";
This code is not working although it's correct
I am using object oriented php.
$this->id is a variable passed by link from another page.
When I run the code it tells me it was successful but that there are zero affected rows.
The one line above is part of the following code:
<?php
class edit {
private $status;
private $remain;
private $cost;
private $id;
public function edit_data() {
$this->status = strtoupper(strip_tags($_POST['status']));
$this->remain = strip_tags($_POST['remain']);
$this->cost = strip_tags($_POST['cost']);
$submit = $_POST['submit'];
$this->id = $_GET['edit'];
$con = mysql_connect("localhost","root","")
or die("Failed to connect to the server: " . mysql_error());
mysql_select_db("Users")
or die("Failed to connect to the database: " . mysql_error());
if($submit) {
if($this->status and $this->remain and $this->cost) {
$sql = "UPDATE reservations SET status = '".$this->status."',remaining_time ='".$this->remain."',cost = '".$this->cost."' WHERE id = '".$this->id."'";
$query = mysql_query($sql,$con);
if(!$query) {
echo("Could not update data: " . mysql_error());
}
echo "<h4>Customer reservation data has been updated successfully.</h4>";
echo "Number of affected rows: " . mysql_affected_rows();
}
else {
echo "Please fill in all fields.";
}
}
mysql_close($con);
}
}
$edit = new edit();
echo $edit->edit_data();
?>
Are you sure about your concatenation?
$sql = "UPDATE reservations SET status = '$this->status',remaining_time ='$this->remain',cost = '$this->cost' WHERE id = '$this->id'";
Print $sql to see the value.
If your database is already updated, you will receive 0 affected lines.
I am not totally sure but try this,
"UPDATE reservations SET status = '".$this->status."',remaining_time ='".$this->remain."',cost = '".$this->cost."' WHERE id = '".$this->id."'";
It seems that your table doesn't contain a value which satisfies where condition.
You can check this by executing a simple query.
$sql = "select * from reservations where id='$this->id'";