how to insert values with comma?in switch statement - php

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) {
...
}

Related

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

Error in SQL syntax at line 1 php/sql

The first problem was with mysql_query which returns FALSE and mysql_num_rows expects parameter 1 to be resource not a boolean. I ve made this to get the error
if($itemsres === FALSE)
die(mysql_error());
Now i have this error " 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 '' at line 1
<?php
ob_start();
session_start();
require("header.php");
require("functions.php");
echo "<h1>Your shopping cart</h1>";
showcart();
if(isset($_SESSION['SESS_ORDERNUM']) == TRUE) {
$sql = "SELECT * FROM orderitems WHERE order_id = " .
$_SESSION['SESS_ORDERNUM'] . ";";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
if($numrows >= 1) {
echo "<h2><a href='checkout-address.php'>Go to the checkout</a></h2>";
}
}
require("footer.php");
?>
The problem started from here.
if(isset($_SESSION['SESS_LOGGEDIN']))
{
$custsql = "SELECT id, status from orders WHERE customer_id = ".
$_SESSION['SESS_USERID']. " AND status < 2;";
$custres = mysql_query($custsql);
$custrow = mysql_fetch_assoc($custres);
$itemssql = "SELECT products.*, orderitems.*, orderitems.id AS itemid FROM
products, orderitems WHERE orderitems.product_id =products.id AND order_id
= " . $custrow['id'];
$itemsres = mysql_query($itemssql);
if($itemsres === FALSE)
die(mysql_error());
$itemnumrows = mysql_num_rows($itemsres);
}
mysql_num_rows expects parameter 1 instead of boolean which is given by mysql_query and after i made that check now i have this sql error.
<?php
ob_start();
session_start();
require("config.php");
if(isset($_SESSION['SESS_LOGGEDIN']) == TRUE) {
header("Location: " . $config_basedir);
}
if(isset($_POST['submit']))
{
$loginsql = "SELECT * FROM logins WHERE username = '" . $_POST['userBox'].
"' AND password = '" . sha1($_POST['passBox']) . "'";
$loginres = mysql_query($loginsql);
$numrows = mysql_num_rows($loginres);
if($numrows == 1)
{
$loginrow = mysql_fetch_assoc($loginres);
session_start("SESS_LOGGEDIN");
session_start("SESS_USERNAME");
session_start("SESS_USERID");
$_SESSION['SESS_LOGGEDIN'] = 1;
$_SESSION['SESS_USERNAME'] = $loginrow['username'];
$_SESSION['SESS_USERID'] = $loginrow['id'];
$ordersql = "SELECT id FROM orders WHERE customer_id = " .
$_SESSION['SESS_USERID'] . " AND status < 2"; $orderres =
mysql_query($ordersql); $orderrow = mysql_fetch_assoc($orderres);
session_start("SESS_ORDERNUM"); $_SESSION['SESS_ORDERNUM'] =
$orderrow['id']; header("Location: ".$config_basedir);
}
else {
header("Location: http://" .$_SERVER['HTTP_HOST']. $_SERVER['SCRIPT_NAME'] .
"?error=1");
}
}
else {
require("header.php");
?>
You have a syntax error
Use query like this
$sql = "SELECT * FROM orderitems WHERE order_id = $_SESSION['SESS_ORDERNUM']";
Or
$sql = "SELECT * FROM orderitems WHERE order_id = ".$_SESSION['SESS_ORDERNUM'];
Or
$sql = "SELECT * FROM orderitems WHERE order_id = '$_SESSION['SESS_ORDERNUM']'";
NOTE: SQL Injection.
PS: Use prepared statements
$loginrow = mysql_fetch_assoc($loginres);
session_start();
$_SESSION['SESS_LOGGEDIN'] = 1;
$_SESSION['SESS_USERNAME'] = $loginrow['username'];
$_SESSION['SESS_USERID'] = $loginrow['id'];
$ordersql = "SELECT id FROM orders WHERE customer_id = " .
$_SESSION['SESS_USERID'] . " AND status < 2";
$orderres =
mysql_query($ordersql); $orderrow = mysql_fetch_assoc($orderres);
$_SESSION['SESS_ORDERNUM'] =
$orderrow['id']; }
First of all, you should check the value of $_SESSION['SESS_ORDERNUM'].
The error means the created query($sql) is not valid, so you should debug $sql.

inserting record into mysql table if column count value is 2

Below is code for count record for today's date and inserting into database if value is not more than two per day.now problem is I want to insert into database if count for today is below 2.
$user_ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
$city = $geo["geoplugin_city"];
$region = $geo["geoplugin_regionName"];
$img = $_POST['img'];
$amount = 5;
$sql = "SELECT COUNT(*) FROM `daily_uploads` WHERE DATE_FORMAT(`date`, '%Y-%m-%d') = CURDATE()";
$result = $conn->query($sql);
if ($result->num_rows > 2) {
echo"already exist";
echo "Error: " . $sql . "<br>" . $conn->error;
} else {
$sql = "INSERT INTO `daily_uploads` (img, geoplugin_city, geoplugin_regionName, amount)
VALUES ('$img', '$city', '$region','$amount')";
// echo "success";
}
You have forgotten to execute the insert $sql string, you can do it this way:
if ($conn->query($sql)) {
echo ('success');
} else {
echo ('error');
}

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 .

Selecting an auto_increment field returns blank In php

I am working on a php script that stores message ids (Msg_ID, Ref_ID) in their corresponding user account tables.
What I've is, the Msg_ID is properly written, but the Ref_ID is always blank.
How ever when I run the query separately it works, but doesn't work in the script for some odd reason.
Here is the code :
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
The $ref_id is always blank and as a result, the blank value is written to the respective database.
Some help with what is wrong will be helpful.
Here is the full code :
<?php
function PostMainThread($Heading, $Message, $Author, $MarkedList){
$con=mysqli_connect("mysql.serversfree.com", "u521497173_root", "123456", "u521497123_mydb");
$Array = explode(',', $MarkedList);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = "Connection Failed.";
echo json_encode($response);
}else{
here:$MsgID = rand(1, 9999999);
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $MsgID . "," . "'" . $Heading . "' ," .
"'" . $Message . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if (!$result){
goto here;
}else{
//Put the MsgID in the respective user tables.
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
$response["success"] = 1;
$response["message"] = "Submission successful.";
mysqli_close($con);
echo json_encode($response);
}
}
}
function PostReplyToThread($PostID, $Author, $Reply){
$con=mysqli_connect("mysql.serversfree.com", "u521497123_root", "123456", "u521497123_mydb");
if (mysqli_connect_errno()){
echo 2;
}else{
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $PostID . "," . "'" . " " . "' ," .
"'" . $Reply . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if ($result){
echo 3;
}else{
echo 4;
}
mysqli_close($con);
}
}
if (isset($_POST['what_to_do'])){
if ($_POST['what_to_do'] == 0){
if ((isset($_POST['Title'])) &&(isset($_POST['Body']))&&(isset($_POST['Marked']))&&(isset($_POST['_Author']))){
PostMainThread($_POST['Title'], $_POST['Body'], $_POST['_Author'], $_POST['Marked']);
}
}else if ($_POST['what_to_do'] == 1){
if ((isset($_POST['Thread_ID'])) &&(isset($_POST['Answer']))&&(isset($_POST['_Author']))){
PostReplyToThread($_POST['Thread_ID'], $_POST['_Author'], $_POST['Answer']);
}
}
}else{
$response["success"] = 0;
$response["message"] = "Unspecified action";
echo json_encode($response);
}
Definition of the Chat table :
Create table Chat(Ref_ID INT Auto_Increment, Msg_ID INT, Header varchar(50), MsgBody varchar(500
), Author varchar(30), Primary Key(Ref_ID, Msg_ID));
$xx = mysqli_fetch_array($resp);
Will only return a numerically indexed array, as in $xx[0], $xx[1].
To use the column names, you need to use:
$xx = mysqli_fetch_array($resp, MYSQLI_ASSOC);
Or the shorter version:
$xx = mysqli_fetch_assoc($resp);
As a side note, don't forget security, when inserting data that comes from outside the function and could possibly have a quotes or SQL, it needs to be escaped!
$Heading = mysqli_real_escape_string($con, $Heading);
Otherwise it will come back to bite you.

Categories