how to use the isset() command in code below for $_SESSION - php

I have a basic question asking how to use the isset(); command and how it should be written in the example below. I am trying to insert values into query, then retrive the last ImageId inserted and insert that into another table
session_start();
$imagesql = "INSERT INTO Image (ImageFile)
VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$img);
//Assign the variable
$img = 'ImageFiles/'.$_FILES['fileImage']['name'];
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
$lastImageID = $mysqli->insert_id;
$_SESSION['lastImageID'] = $lastImageID;
$imagequestionsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionId)
VALUES (?, ?, ?)";
if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err imagequestion";
}
$qnum = (int)$_POST['numimage'];
$insertimagequestion->bind_param("iii",$lastImageID, $sessionid, $qnum);
$insertimagequestion->execute();
if ($insertimagequestion->errno) {
// Handle query error here
}
$insertimagequestion->close();

Not exactly sure what your asking for, but guessing wildly:
session_start();
...... //PDO code and commands
$lastImageID = $mysqli->insert_id;
$_SESSION['lastImageID'] = $lastImageID;
if (isset($_SESSION['lastImageID'])) {
// do this
} else {
// do that
}

You only need to call isset if you are reading a variable that may not be defined.
In this situation, you are writing to $_SESSION['lastImageID'], so you don't need to check.
An example of where isset would be needed:
if (isset($_SESSION['lastImageID']))
{
$lastImageID = $_SESSION['lastImageID'];
}
else
{
$lastImageID = get_this_from_db_or_something();
}

Related

inserting multiple rows in mysql from json string/array using php?

"i am trying to develop an script which allows me to insert multiple rows from an jsonarray in mysql database, but upon testing only one rows is being inserted and here is my code:
<?php
$con = mysqli_connect($host,$user,$password,$database) or die('Unable to Connect');
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$jsonData=file_get_contents("sampledata.json");
$jsonString=json_decode($jsonData,true);
foreach($jsonString['Order Summary'] as $cart)
{
$name=$cart['ProductName'];
$price=$cart['ProductPrice'];
$quantity=$cart['ProductQuantity'];
$cost=$cart['ProductCost'];
$seller=$cart['SellerId'];
$stmt=$con->prepare("INSERT INTO sProducts(Name,Price,Quantity,Cost,Sellerid)VALUES(?,?,?,?,?)");
$stmt->bind_param("sssss",$name,$price,$quantity,$cost,$seller);
if($stmt->execute())
return json_encode("data inserted");
return json_encode("error");
}
}
can anyone tell me where is the mistake or could guide me into this direction ?
For one, you are reutrning in the first iteration of the loop - which means that the script stops. return should only be used to return from a function.
If you remove both returns, that will make the loop continue until its done.
And you should not prepare the query inside the loop, its not needed - and much more efficient to prepare it before you start looping (it can be used multiple times with different values when you bind and execute in a loop). I've also added some spaces in the code to make it easier to read
$con = mysqli_connect($host,$user,$password,$database) or die('Unable to Connect');
$msg = "data inserted";
if ($_SERVER["REQUEST_METHOD"]=="POST") {
$jsonData = file_get_contents("sampledata.json");
$jsonString = json_decode($jsonData,true);
$stmt = $con->prepare("INSERT INTO sProducts (Name, Price, Quantity, Cost, Sellerid) VALUES (?, ?, ?, ?, ?)");
foreach($jsonString['Order Summary'] as $cart) {
$name = $cart['ProductName'];
$price = $cart['ProductPrice'];
$quantity = $cart['ProductQuantity'];
$cost = $cart['ProductCost'];
$seller = $cart['SellerId'];
$stmt->bind_param("sssss", $name, $price, $quantity, $cost, $seller);
if (!$stmt->execute())
$msg = "Something went wrong";
}
}
return json_encode($msg);

mysql insert inside foreach loop, cron not working

This code works if i run in a browser. When i run the script via a cron, it doesn't get through the array and stops halfway? Why is this?
$url_array = array("eur-gbp","eur-aud","usd-chf","eur-usd","eur-jpy","gbp-jpy","eur-cad","eur-chf","usd-cad","usd-jpy","cad-chf","cad-jpy","gbp-usd","aud-usd","gbp-chf","chf-jpy","gbp-cad","aud-cad","aud-chf","aud-jpy","aud-nzd","eur-nzd","gbp-aud","gbp-nzd","nzd-chf","nzd-usd","nzd-cad","nzd-jpy");
$option_array = array(1,2,3,4,5,6,7);
$type_array = array(1,2,3,4,5,6);
foreach($url_array as $url_type) {
//code
foreach($option_array as $option) {
//code
foreach($duration_array as $duration) {
//code
foreach($type_array as $type) {
//mysql insert
$sql = "SELECT * FROM `data_analysis` WHERE date_time='".$date."' AND type='".$url_type."' LIMIT 1";
$query = $this->db->query($sql);
$result = $query->fetch_assoc();
if($result){
$sql = "UPDATE `data_analysis` SET value='".$percentage."', price_change='".$price."', parent='1' WHERE date_time='".$date."' AND type='".$url_type."'";
} else {
$sql = "INSERT IGNORE INTO `data_analysis` (date_time,value,price_change,type,parent) VALUES ('".$date."','".$percentage."','".$price."','".$url_type."','1')";
}
}
}
}
}
This isn't the exact code as it is too long to post but similar. The code works perfectly in the browser?? running via cron it stops at gbp-jpy? Why is this?
Is there a mysql query limit?
Add a unique index on (type, date_time) to the table. Then combine your two queries into 1. Also, use a prepared statement.
$stmt = $this->db->prepare("
INSERT INTO data_analysis (date_time, value, price_change, type, parent)
VALUES (?, ?, ?, ?, '1')
ON DUPLICATE KEY UPDATE value = VALUES(value), price_change = VALUES(price_change), parent = VALUES(parent)");
$stmt->bind_param("ssss", $date, $percentage, $price, $url_type);
foreach($url_array as $url_type) {
//code
foreach($option_array as $option) {
//code
foreach($duration_array as $duration) {
//code
foreach($type_array as $type) {
//mysql insert
$stmt->execute();
}
}
}
}

Using isset for correction?

I'm new to PHP,I got error in my web page.It said:
Notice: Undefined index: itemid in /home/tz005/public_html/COMP1687/edit.php on line 103
Can I use isset to fix this problem? If yes, how to do so? Here is my script:
<?php
//include database connection
include 'dbconnect.php';
// if the form was submitted/posted, update the item
if($_POST){
//write query
$sql = "UPDATE
item_information
SET
itemtitle = ?,
itemdescription = ?,
date = ?,
WHERE
itemid= ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param(
'sssi',
$_POST['itemtitle'],
$_POST['itemdescription'],
$_POST['date'],
$_POST['itemid']
);
// execute the update statement
if($stmt->execute()){
echo "Item was updated.";
// close the prepared statement
$stmt->close();
}else{
die("Unable to update.");
}
}
$sql = "SELECT
itemid, itemtitle, itemdescription, date
FROM
item_information
WHERE
id = \"" . $mysqli->real_escape_string($_GET['itemid']) . "\"
LIMIT
0,1";
// execute the sql query
$result = $mysqli->query( $sql );
//get the result
if ($result = $mysqli->query( $sql )) {
if ($row = $result->fetch_assoc()) {
// $row contains data
}
}
//disconnect from database
$result->free();
$mysqli->close();
?>
change
$mysqli->real_escape_string($_GET['itemid'])
to
$mysqli->real_escape_string($_POST['itemid'])
or use empty() or isset() to check values exist
Yes you can do it with isset() function
Create conditions for it
if(isset($_GET['itemid'])){
//execute your code
}
else{
//header them back to page or show error that itemid not set or something else whatever suits you
}

Is order of my code displaying the mysqli errors?

I am receiving two errors in mysqli:
Warning: mysqli_stmt::execute(): (HY000/2014): Commands out of sync;
you can't run this command now in /.../ on line 235 240:
Commands out of sync; you can't run this command now Fatal error:
Cannot break/continue 2 levels in /.../ on line 241
I want to know that is the errors appearing because of the order of my queries and inserts below:
<?php
//connect to db
var_dump($_POST);
$optionquery = "SELECT OptionId FROM Option_Table WHERE (OptionType = ?)";
if (!$optionstmt = $mysqli->prepare($optionquery)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
$replyquery = "SELECT ReplyId FROM Reply WHERE (ReplyType = ?)";
if (!$replystmt = $mysqli->prepare($replyquery)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
// Prepare your statements ahead of time
$questionsql = "INSERT INTO Question (SessionId, QuestionId, QuestionContent, NoofAnswers, ReplyId, QuestionMarks, OptionId)
VALUES (?, ?, ?, ?, ?, ?, ?)";
if (!$insert = $mysqli->prepare($questionsql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
$answersql = "INSERT INTO Answer (SessionId, QuestionId, Answer)
VALUES (?, ?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
//make sure both prepared statements succeeded before proceeding
if( $insert && $insertanswer)
{
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$c = count($_POST['numQuestion']);
for($i = 0; $i < $c; $i++ )
{
$selected_option = "A-C";
$selected_reply = "Single";
// Bind parameter for statement
$optionstmt->bind_param("s", $selected_option);
// Execute the statement
$optionstmt->execute();
if ($optionstmt->errno)
{
// Handle query error here
echo __LINE__.': '.$optionstmt->error;
break 1;
}
// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$optionstmt->bind_result($optionid);
// This populates $optionid
$optionstmt->fetch();
// Bind parameter for statement
$replystmt->bind_param("s", $selected_reply);
// Execute the statement
$replystmt->execute();
if ($replystmt->errno)
{
// Handle query error here
echo __LINE__.': '.$replystmt->error;
break 2;
}
// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$replystmt->bind_result($replyid);
// This populates $optionid
$replystmt->fetch();
$results = $_POST['value'];
foreach($results as $id => $value)
{
$answer = $value;
$insert->bind_param("sisiiii", $sessid, $id, $_POST['questionText'][$i],
$_POST['numberAnswer'][$i], $replyid, $_POST['textWeight'][$i],
$optionid);
$insert->execute();
if ($insert->errno)
{
// Handle query error here
echo __LINE__.': '.$insert->error;
break 3;
}
$lastID = $insert->insert_id;
foreach($value as $answer)
{
$insertanswer->bind_param("sis", $sessid, $lastID, $answer);
$insertanswer->execute();
if ($insertanswer->errno) {
// Handle query error here
echo __LINE__.': '.$insertanswer->error;
break 4;
}
}
}
}
//close your statements at the end
$insertanswer->close();
$insert->close();
$replystmt->close();
$optionstmt->close();
}
?>
This is because you are closing the statement at proper time
Close the statement $insertanswer->close(); at the proper place or before another query

Adding 2 SELECT queries in mysqli/php code is causing errors

I have a working php/mysqli code below where it inserts questions and answers successfully:
$i = 0;
$c = count($_POST['numQuestion']);
$questionsql = "INSERT INTO Question (SessionId, QuestionId, QuestionContent)
VALUES (?, ?, ?)";
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
if (!$insert = $mysqli->prepare($questionsql)) {
// Handle errors with prepare operation here
} else{
for($i = 0; $i < $c; $i++ ){
$results = $_POST['value'];
foreach($results as $id => $value) {
$answer = $value;
$insert->bind_param("sis", $sessid, $id, $_POST['questionText'][$i]);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$lastID = $insert->insert_id;
$insert->close();
foreach($value as $answer) {
$answersql = "INSERT INTO Answer (SessionId, QuestionId, Answer)
VALUES (?, ?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
}
$insertanswer->bind_param("sis", $sessid, $lastID, $answer);
$insertanswer->execute();
if ($insertanswer->errno) {
// Handle query error here
}
$insertanswer->close();
}
}
}
}
But a trouble I have been having even before getting the above code to work is that I have 2 additional SELECT queries which I need include in the code above. The queries are known as $replystmt and $optionstmt. The problem though is that if I include those queries in the php/mysqli code above, I keep receiving these errors:
Warning: mysqli_stmt::execute(): (HY000/2014): Commands out of sync;
you can't run this command now in /insertQuestion.php on line 236 241:
Commands out of sync; you can't run this command now Fatal error:
Cannot break/continue 2 levels in /insertQuestion.php on line 242
Now the full code is below, my question is that what do I need to change in my code in order for the errors to be removed and the code to work?
Below is the full php/mysqli code:
$replyquery = "SELECT ReplyId FROM Reply WHERE (ReplyType = ?)";
if (!$replystmt = $mysqli->prepare($replyquery)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
$optionquery = "SELECT OptionId FROM Option_Table WHERE (OptionType = ?)";
if (!$optionstmt = $mysqli->prepare($optionquery)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
// Prepare your statements ahead of time
$questionsql = "INSERT INTO Question (SessionId, QuestionId, QuestionContent, NoofAnswers, ReplyId, QuestionMarks, OptionId)
VALUES (?, ?, ?, ?, ?, ?, ?)";
if (!$insert = $mysqli->prepare($questionsql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
$answersql = "INSERT INTO Answer (SessionId, QuestionId, Answer)
VALUES (?, ?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
//make sure both prepared statements succeeded before proceeding
if( $insert && $insertanswer)
{
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$c = count($_POST['numQuestion']);
for($i = 0; $i < $c; $i++ )
{
$selected_option = "A-C";
$selected_reply = "Single";
// Bind parameter for statement
$optionstmt->bind_param("s", $selected_option);
// Execute the statement
$optionstmt->execute();
if ($optionstmt->errno)
{
// Handle query error here
echo __LINE__.': '.$optionstmt->error;
break 1;
}
// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$optionstmt->bind_result($optionid);
// This populates $optionid
$optionstmt->fetch();
// Bind parameter for statement
$replystmt->bind_param("s", $selected_reply);
// Execute the statement
$replystmt->execute(); //Line 236
if ($replystmt->errno)
{
// Handle query error here
echo __LINE__.': '.$replystmt->error; //Line 241
break 2;
}
// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$replystmt->bind_result($replyid);
// This populates $optionid
$replystmt->fetch();
$insert->bind_param("sisiiii", $sessid, $_POST['numQuestion'][$i], $_POST['questionText'][$i],
$_POST['numberAnswer'][$i], $replyid, $_POST['textWeight'][$i],
$optionid);
$insert->execute();
if ($insert->errno)
{
// Handle query error here
echo __LINE__.': '.$insert->error;
break 3;
}
}
$results = $_POST['value'];
foreach($results as $id => $value)
{
$answer = $value;
$lastID = $id;
foreach($value as $answer)
{
$insertanswer->bind_param("sis", $sessid, $lastID, $answer);
$insertanswer->execute();
if ($insertanswer->errno) {
// Handle query error here
echo __LINE__.': '.$insertanswer->error;
break 4;
}
}
}
//close your statements at the end
$insertanswer->close();
$insert->close();
$replystmt->close();
$optionstmt->close();
}
There's two different problems happening here. Firstly, the Commands out of sync warning is happening because you are trying to initiate new queries before actually finishing the previous ones. See this answer for more information about that. Basically, you have to close each of the queries you are preparing before preparing the next one.
As for the Cannot break/continue error, that is happening because you are calling break 2 when you are only 1 level deep. The optional number after break (or continue) is the number of 'levels' to break out of.
<?php
for($i = 0; $i < 10; $i++){
// 1 level
for($j = 0; $j < 10; $j++){
// 2 levels
break; // Break of the $j loop
break 1; // Equivalent to above
break 2; // Break out of both the $j and $i loops
break 3; // Causes an error - there is no third level
}
}
Of course, in that example it would never reach the other breaks after hitting the first one, but it should illustrate the concept. See also the documentation for break.

Categories