SQL syntax error IN - php

I'm writing a script to figure out whether changes have been made to my data.
However i'm getting this error:
Error: UPDATE Workhours SET IN= '07:59' WHERE AFNumber='AF1585' AND
Date='09/07/2015' You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'IN= '07:59' WHERE AFNumber='AF1585' AND
Date='09/07/2015'' at line 1Error: UPDATE Workhours SET OUT= '14:04'
WHERE AFNumber='AF1585' AND Date='09/07/2015'
Any help please?
if (isset($_POST['submit']))
{
$sql = "SHOW COLUMNS FROM Workhours";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
$tempname = $row['Field'];
$sql2 = "UPDATE Workhours SET ".$row['Field']."= '$_POST[$tempname]' WHERE AFNumber='".$_GET["af"]."' AND Date='".$_GET["date"]."'";
$result2 = mysqli_query($con,$sql2);
if ($con->query($sql2) === TRUE) {
} else {
echo "Error: " . $sql2 . "<br>" . $con->error;
}
}
$sql3 = "SELECT * FROM Workhours WHERE AFNumber='".$_GET["af"]."' AND (".$row['Field']." NOT LIKE '".$_POST[$tempname]."')";
$result3 = mysqli_query($con,$sql3);
if (mysqli_num_rows($result3) > 0) {
// output data of each row
while($row3 = mysqli_fetch_array($result3)) {
$sql3 = "INSERT INTO `Changes` (`Table`, `AFNumber`, `Attribute`, `DateChanged`, `HRUser`, `OldValue`, `NewValue`)
VALUES ('Workhours', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '$login_session', '', '$_POST[$tempname]')";
if (mysqli_query($con,$sql3) === TRUE) {
} else {
echo "Error: " . $sql3 . "<br>" . mysqli_error($con);
}
}
}
echo '<script>swal("Success", "Changes have been saved", "success");</script>';
}

IN and OUT are keywords in MySQL. You have to escape the $row['Field'] with backticks.
$sql2 = "UPDATE Workhours SET `".$row['Field']."`= '$_POST[$tempname]' WHERE AFNumber='".$_GET["af"]."' AND Date='".$_GET["date"]."'";
Also you should use prepared statements for preventing SQL injection.

Related

Trying to transfer json from a table to anther php

I have a problem and I don't know how to solve it. I want to transfer a json to another table and I get a syntax error.
This is my output
INSERT INTO saved_cmd ('id_user','value','store','totalPrice','hour','type_payement') VALUES ('11','"{\"lenght\":0,\"produits\":[{\"id\":29,\"name\":\"Tarte au fraise\",\"count\":1,\"price\":2,\"totalPrice\":2},{\"id\":28,\"name\":\"rose des sables\",\"count\":0,\"price\":2,\"totalPrice\":0}]}"','6','2.00','13:00','caisse')
===================================================
Error: INSERT INTO saved_cmd ('id_user','value','store','totalPrice','hour','type_payement') VALUES ('11','"{\"lenght\":0,\"produits\":[{\"id\":29,\"name\":\"Tarte au fraise\",\"count\":1,\"price\":2,\"totalPrice\":2},{\"id\":28,\"name\":\"rose des sables\",\"count\":0,\"price\":2,\"totalPrice\":0}]}"','6','2.00','13:00','caisse')<br>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''id_user','value','store','totalPrice','hour','type_payement') VALUES ('11','"{\' at line 1
I tried to encode my json but i have the same problem
and this is my php
$state = $row['states'];
$id_user = $row['id_user'];
$value = ($row['value']);
$panier = json_encode($value);
$store = $row['store'];
$totalPrice = $row['totalPrice'];
$hour = $row['hour'];
$type_payement = $row['type'];
if ($row['states'] != 4) {
$states = $state + 1;
$sql = "UPDATE cmd SET states = $states WHERE id = '$id'";
if ($conn->query($sql)) {
echo "good:up";
}
} else {
$sql = "INSERT INTO saved_cmd ('id_user','value','store','totalPrice','hour','type_payement') VALUES ('$id_user','$panier','$store','$totalPrice','$hour','$type_payement')";
echo $sql . "\n\n\n===================================================\n\n\n";
if ($conn->query($sql) === true) {
echo "good:save";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

how do i solve this error " Catchable fatal error: Object of class mysqli_result could not be converted to string"?

$sql = "INSERT INTO placed_req(username,goodsauto,minitruck,largetruck,price,qty) VALUES('$user_check','$ga','$mt','$lt','$r','$qty')";
$result = mysqli_query($con,$sql);
$sql2="SELECT reqid FROM placed_req WHERE username='$user_check' AND price='$r'";
$ret=mysqli_query($con,$sql2);
$sql1 = "INSERT INTO inv_detail (inv_id,p_name,qty,price) VALUES('$ret','$user_check','$qty','$r')"; //i'm getting that error in this line
$result1 = mysqli_query($con,$sql1);
if(isset($result1))
echo "<br></br> Invoice generated successfully";
header("refresh:10,url=placeorders.php");
} else {
echo "<br></br> values not selected";
}
if you want to put req_id into insert query you must firts fetch req_id correctly
$sql2="SELECT reqid FROM placed_req WHERE username='$user_check' AND price='$r'";
$ret=mysqli_query($con,$sql2);
$row = mysqli_fetch_assoc($ret);
/* above instruction fetch record from database*/
$inv_id = $row['reqid'];
and then put $inv_id into insert query statement
$sql1 = "INSERT INTO inv_detail (inv_id,p_name,qty,price) VALUES('$inv_id','$user_check','$qty','$r')"; //i'm getting that error in this line
$result1 = mysqli_query($con,$sql1);
If you fix your query from
"SELECT reqid FROM placed_req WHERE username='$user_check' AND price='$r'";
To:
"SELECT reqid FROM placed_req WHERE username=\'" . $user_check . "\' AND price=\'" . $r . "\'";
And
$sql1 = "INSERT INTO inv_detail (inv_id,p_name,qty,price) VALUES('$ret','$user_check','$qty','$r')";
with $sql1 = "INSERT INTO inv_detail (inv_id,p_name,qty,price) VALUES(\'" . $ret . "\',\'" . $user_check . "\',\'". $qty . "\',\'" . $r . "\')";
You can finaly use the value of the variables in your query. and like #pritamakumar said, you have to fetch ret correctly

how to insert values with comma?in switch statement

i am using switch statements to insert comma values:
<?php
session_start();
include('config1.php');
$category_id = 1;
$AnswerID = $_POST['AnswerID'];
$questionid = $_POST['questionid'];
$timetaken = $_POST['timetaken'];
$limit = $_POST['limit'];
echo "$limit";
$bd = "$limit";
switch ($bd) {
case"1":
$sql = "INSERT INTO results (id, user_id, category_id, q_id, answer_id, time_taken)
VALUES (',', '".$_SESSION['id']."', '$category_id', '$questionid', '$AnswerID', '$timetaken')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$last_id = mysqli_insert_id($conn);
echo "Last inserted ID is: " . $last_id;
// Set session variables
$_SESSION["last_id"] = "$last_id";
break;
case"2":
quiz_test();
break;
case"3":
quiz_test();
break;
case"4":
quiz_test();
break;
case"5":
quiz_test();
unset($_SESSION['last_id']);
break;
default:
echo "something is wrong";
}
function quiz_test(){
$sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='" . $_SESSION["last_id"] . "'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$qid=$rows['q_id'];
$ans=$rows['answer_id'];
$time=$rows['time_taken'];
}
}
$conn->query("update results set q_id =('$questionid','$qid'),answer_id = ('$AnswerID','$ans'),time_taken=('$timetaken','$time') where id = '" . $_SESSION["last_id"] . "'");
}
?>
In case 1 insert values and get insert id,and set into session.
Case 2 select,update statement are not working.i got following errors:
Notice: Undefined variable: conn in C:\xampp\htdocs\N\exam\exam\DOCS\Insert.php on line 62
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\N\exam\exam\DOCS\Insert.php on line 62
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\N\exam\exam\DOCS\Insert.php on line 63
Notice: Undefined variable: conn in C:\xampp\htdocs\N\exam\exam\DOCS\Insert.php on line 70
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\N\exam\exam\DOCS\Insert.php on line 70
You need to add one parameter $conn in your function quiz_test() then it will works
Try below code
<?php
session_start();
?>
<?php
include('config1.php');
$category_id = 1;
$AnswerID = $_POST['AnswerID'];
$questionid = $_POST['questionid'];
$timetaken = $_POST['timetaken'];
$limit = $_POST['limit'];
echo "$limit";
$bd = "$limit";
switch ($bd) {
case"1":
$sql = "INSERT INTO results (id, user_id, category_id, q_id, answer_id, time_taken)
VALUES (',', '".$_SESSION['id']."', '$category_id', '$questionid', '$AnswerID', '$timetaken')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$last_id = mysqli_insert_id($conn);
echo "Last inserted ID is: " . $last_id;
// Set session variables
$_SESSION["last_id"] = "$last_id";
break;
case"2":
quiz_test($conn);
break;
case"3":
quiz_test($conn);
break;
case"4":
quiz_test($conn);
break;
case"5":
quiz_test($conn);
unset($_SESSION['last_id']);
break;
default:
echo "something is wrong";
}
function quiz_test($conn){
$sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='" . $_SESSION["last_id"] . "'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$qid=$rows['q_id'];
$ans=$rows['answer_id'];
$time=$rows['time_taken'];
}
}
$conn->query("update results set q_id =('$questionid','$qid'),answer_id = ('$AnswerID','$ans'),time_taken=('$timetaken','$time') where id = '" . $_SESSION["last_id"] . "'");
}
?>
You appear to be mixing together two different flavors of PHP API functions. You also, in your call to mysqli_insert_id() you should not be specifying the id if it is an autoincrement column. I believe you intended to do something along these lines:
$sql = "INSERT INTO results (user_id, category_id, q_id, answer_id, time_taken)
VALUES ('".$_SESSION['id']."', '$category_id', '$questionid', '$AnswerID', '$timetaken')";
mysqli_query($conn, $sql);
$last_id = mysqli_insert_id($conn);
echo "Last inserted ID is: " . $last_id;
And the other problem as #Krish pointed out is that you need to pass your connection variable $conn to the quiz_test() function, e.g.
function quiz_test($conn) {
...
}

if cells are null insert syntax

I'm trying to check whether major, grade and university in candidates table, are empty, if so then insert in university...Else...
Is my syntax appropriate?
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
while($row5 = mysqli_fetch_array($result5)) {
$major = $row5['Major'];
$grade = $row5['Grade'];
$university = $row5['University'];
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
Use the follwing code
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
well you are saying that if major, grade and university are empty than insert those empty values in university but the question here is why you want to enter those values if they are empty, even if you want to do so along with inserting afnumber using "$_GET["af"]" variable than you can use following code..
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`afnumber`) VALUES ('".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
its quite short and fulfill the purpose but make sure you have checked null in database for major, grade and univ fields in university table .

PHP, Mysql query different tables in one function

function getDepartmentAndCondition($dep, $userid, $cond) {
$result = mysql_query("SELECT * FROM department WHERE ID='$dep'");
while($row = mysql_fetch_array($result))
{
$DepConInfo['Department'] = $row['Department'];
}
$userName = mysql_query("SELECT * FROM users WHERE FacebookID = '$userid'") or die ("<hr>error in SQL query: " . mysql_error() . "<hr>");
while($row = mysql_fetch_array($username)) {
$DepConInfo['Name'] = $row['name'];
}
$result2 = mysql_query("SELECT * FROM condition WHERE ID= '$cond' ")
or die("<hr>error in SQL query: " . mysql_error() . "<hr>");
while($row2 = mysql_fetch_array($result2))
{
$DepConInfo['Condition'] = $row2['Condition'];
}
return $DepConInfo;
}
$dep, $userid, and $cond are all ints. the first one $DepConInfo['Department'] is returning the right string, but the other two fail with the error
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in ...
ok I rewrote the function
function getCondition($cond) {
$query = "SELECT * FROM condition WHERE ID = '$cond' ";
$sql = mysql_query($query);
if (!$sql) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row2 = mysql_fetch_array($sql))
{
$condition = $row2['Name'];
}
return $condition;
}
but I'm still getting an error:
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition WHERE id = '1'' at line 1 Whole query: SELECT * FROM condition WHERE ID = '1'
the table "condition" has two columns "ID" and "Name".
while($row = mysql_fetch_array($username)) {
PHP is case-sensitive: you have $username with wrong caps - should be $userName
Additionally, based on your naming convention in the first and third queries
$DepConInfo['Name'] = $row['name'];
is probably incorrect and should be capitalized as $row['Name']
function getDepartment($dep) {
$sql = "SELECT * FROM department WHERE ID = '$dep'";
$result = mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$department = $row['Department'];
}
return $department;
}
function getName($userid) {
$sql = "SELECT * FROM users WHERE FacebookID = '$userid'";
$result = mysql_query($sql);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$user_name = $row['Name'];
}
return $username;
}
function getCondition($cond) {
$sql = "SELECT * FROM condition WHERE id = '$cond'";
$result = mysql_query($sql);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$condition = $row['Condition'];
}
return $condition;
}
$department = getDepartment($dep);
$username = getName($userid);
$condition = getCondition($cond);
I'm writing this from my head so I did not test it, but it should work or at least get you on your way. If not let me know. Mind capitalization using caps in your dbase table and column names can make things more confusing. Use $sql to store your query, use $result to store the result. This is more descriptive. Good luck!

Categories