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();
}
Related
How can I change one value or more values of choice? If I enter a single value, it works. Still, if I enter two values in two input fields, it doesn't work, showing me the following error.
Error updating record: You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax to use near 'nat = 'saf' WHERE id = '16'' at line 1
if (isset($_POST['modifica'])) {
$id = $_POST['id'];
$semaphore = false;
$sql = "UPDATE users SET ";
$fields = array('nume', 'nat', 'email', 'telefon');
foreach ($fields as $field) {
if (isset($_POST[$field]) and !empty($_POST[$field])) {
$var = ($_POST[$field]);
$sql .= $field." = '$var'";
$semaphore = true;
}
}
if ($semaphore) {
$sql .= " WHERE id = '$id'";
($sql);
}
if ($conn->query($sql) === true) {
echo "Record updated successfully";
} else {
echo "Error updating record: ".$conn->error;
}
$conn->close();
}
An inplementatiom aproach of #m-eriksson comments:
$sql = "UPDATE users SET nume = :nume, nat = :nat, email = :email, telefon = :telefon";
$fields = array('nume', 'nat', 'email', 'telefon');
if(count($fields) > 0 ){
$this->update($sql, $fields, $con)
$semaphore = true;
}
public function update ($sql, $fields, $con)
{
$update = $con->prepare($query);
return $update->execute($fields);
}
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();
I have a problem with my PHP code, I can't get it to delete some data inside my MySQL database. I have tried some different things but it just won't work.
What iv'e tried: Deleting $productId, switched $producId to 1, 2, 3 and 4.
if (isset($_POST['remove_product'])) {
$productId = 4
$sql = "DELETE FROM products WHERE id = '.$productId.'";
$stmt = mysqli_init($conn);
if (!mysqli_prepare($stmt, $sql)) {
header("Location: products.php?error=sqlerror");
exit();
} else {
mysqli_execute($stmt);
}
}
I would like if it could delete the data from the MySQL table, so if someone could come with a solution, thanks : )
Thanks!
You are using the wrong functions to initialise, prepare and execute your statement. You should be using mysqli_stmt_init, mysqli_stmt_prepare and mysqli_stmt_execute instead. Also, since you are preparing a statement, you should take advantage of that to avoid SQL injection. Try this:
if (isset($_POST['remove_product'])) {
$productId = 4;
$sql = "DELETE FROM products WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: products.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, 'i', $productId);
mysqli_stmt_execute($stmt);
}
}
You are lacking a semicolon
$productId = 4
--------------^
Use
$productId = 4;
You have some issues with quotation marks:
$sql = "DELETE FROM products WHERE id = '.$productId.'";
-------^--------------------------------^------------^^
It should say:
$sql = "DELETE FROM products WHERE id = " . $productId;
Also you are not using prepared statements in the right way
if (isset($_POST['remove_product'])) {
$productId = 4;
$sql = "DELETE FROM products WHERE id = ?";
if (!$stmt = mysqli_prepare($sql)) {
header("Location: products.php?error=sqlerror");
exit();
} else {
$stmt->bind_params("i", $productId);
$stmt->execute();
}
}
There are some syntactic mistakes in your code. Use mysqli-query to execute the the query. it is used frequently
if (isset($_POST['remove_product'])) {
$productId = 4;
$sql = "DELETE FROM products WHERE id = ".$productId;
$stmt = mysqli_init($conn);
if (!mysqli_query($stmt, $sql)) {
header("Location: products.php?error=sqlerror");
exit();
} else {
mysqli_execute($stmt);
}
}
try this once
I've got the following code:
<?php
include 'payment/dbConfig.php';
$email = $_GET['email'];
$account = $_GET['account'];
if($email != ''){
$sql = "SELECT command FROM bots WHERE email='".$email."' AND account='".$account."' limit 1";;
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$value = $row["command"];
}
}
if($value != ''){
echo $value;
$sql = "UPDATE `bots` SET command='' WHERE email='".$email."' AND account='".$account."'";
$db->query($sql);
}else{
$sql = "INSERT INTO `bots`(`email`, `account`) VALUES ('".$email."','".$account."')";
$db->query($sql);
}
}
?>
Which definitely looks like a mess, and this isn't working right.
Specifically, it endlessly adds the same 'email' and 'account' into the database, even though it should be done only when $value is not equal to emptiness.
What should I do?
You can do this in less code.
if ($result->num_rows > 0) {
// Update
$sql = "UPDATE `bots` SET command='' WHERE email='".$email."' AND account='".$account."'";
$db->query($sql);
} else {
// Insert
$sql = "INSERT INTO `bots`(`email`, `account`) VALUES ('".$email."','".$account."')";
$db->query($sql);
}
Note: You are passing the user inputs ($_GET) directly in the query, Sanitize all user inputs ($_GET, $_POST) and check for SQL Injection before execute any query.
I'm working on this project and I need help with something. I am trying to check if someone is already in the database upon logging in and if they are not, they will be added. However, my code always adds them to the database...
Login code:
<?php
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE '$emaillogin' = `emailadress`
AND '$passwordlogin' = `password` LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
echo "E-mail or password incorrect! <br>";
}else{
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
header("location:home.php");
die();
}
}
?>
The function in functions.php:
function check_firstest($accnr){
$query = mysql_query("SELECT count(*) AS 'num' FROM `VRIENDEN` WHERE `accnr` = '$accnr' AND `vriendnr` = '$accnr'");
if($result > 0){
return true;
}
else{
return false;
}
}
The login on its own works just fine, so thats no problem.
Thank you!
Your first query is somewhat odd and you do not capture the values from $_POST into the variables that you are using in the query either
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE `emailadress` = '{$_POST['emaillogin']}'
AND `password` = '{$_POST['passwordlogin']}'
LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
// something went REALLY WRONG, report it
echo mysql_error();
exit;
}
if ( mysql_num_rows($result) == 1 ) {
// found user and password matches
header("location:home.php");
exit;
}else{
// new user, create the account
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
// and go to home page
header("location:home.php");
die();
}
}
?>
And of course the fix for the check_firstest() is also required
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
But I have to add
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements
And
You should not be using the mysql_ database extension, it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions and prepared statements.
Start here
You have to count the resulting rows:
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
Here the mysql_num_rows() function gives the number of rows in the result set. If it is greater than 0 then it means that there is some data.