Closing connection in order to get remaining queries to run [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Perhaps I'm missing something very obvious here.
My code doesn't seem to work below the 'GET BOOK ID' annotation if I don't close and reopen the connection.
While it does work, it doesn't seem to be an efficient way at all to do this, any suggestions?
$AddBook = $conn->prepare("CALL makeBooking((SELECT CustID FROM customer WHERE UserName = '$UserName'), ?, ?, ?, ?, now())");
$AddBook->bind_param('iiis',$PerfID, $NumAdults, $NumChilds, $ColTicket);
if ($AddBook->execute())
{
//----------------DEDUCT SEATS--------------//
$SeatDeduction = $conn->prepare("CALL deductSeats($TotalSeats,?)");
$SeatDeduction->bind_param('i',$PerfID);
$SeatDeduction->execute();
mysqli_close($conn);
require ('connect.php');
//-----------------GET BOOK ID--------------//
$getBookID = "CALL getBookByUserName('$UserName')";
$result2 = mysqli_query($conn, $getBookID);
$Output2 = mysqli_fetch_assoc($result2);
$BookID = $Output2['BookID'];
mysqli_close($conn);
require ('connect.php');
//-------------------SET COST---------------//
$setCost = "CALL setBookingPrice($BookID)";
mysqli_query($conn,$setCost);
mysqli_close($conn);
require ('connect.php');
//-------------------GET COST---------------//
$getCost = "CALL getCost($BookID)";
$result6 = mysqli_query($conn,$getCost);
$Output6 = mysqli_fetch_assoc($result6);
$Cost = $Output6['TotalCost'];
mysqli_close($conn);
require ('connect.php');
//---------------BOOKING CONFIRM------------//
$ShowRef = 'Booking Completed<p>Reference Number: <b>' . $BookID . '</b><p>';
$showCost = 'Total Cost: <b><u>£' . $Cost . '<u><b><br>';
$Confirm = $ShowRef.$showCost;
}
else
{
die(mysqli_error($conn));
}
mysqli_close($conn);

You don't have to keep including the connect.php file over and over.
Assuming you already included it somewhere at the top since you run $AddBook->execute()
See this updated code:
$AddBook = $conn->prepare("CALL makeBooking((SELECT CustID FROM customer WHERE UserName = '$UserName'), ?, ?, ?, ?, now())");
$AddBook->bind_param('iiis',$PerfID, $NumAdults, $NumChilds, $ColTicket);
if ($AddBook->execute())
{
//----------------DEDUCT SEATS--------------//
$SeatDeduction = $conn->prepare("CALL deductSeats($TotalSeats,?)");
$SeatDeduction->bind_param('i',$PerfID);
$SeatDeduction->execute();
$SeatDeduction->close();
$conn->next_result();
// mysqli_close($conn); // remove this
// require ('connect.php'); // remove this
//-----------------GET BOOK ID--------------//
$getBookID = "CALL getBookByUserName('$UserName')";
$result2 = mysqli_query($conn, $getBookID);
$Output2 = mysqli_fetch_assoc($result2);
$BookID = $Output2['BookID'];
// mysqli_close($conn); remove this
// require ('connect.php'); remove this
//-------------------SET COST---------------//
// ...
//-------------------GET COST---------------//
// ...
//---------------BOOKING CONFIRM------------//
// ...
}
else
{
die(mysqli_error($conn));
}
mysqli_close($conn);

Related

Fatal error Uncaught mysqli_sql_exception you have an error with your sql syntax (line 25) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed yesterday.
Improve this question
im getting this weird error and i don't know what im doing wrong
it has something to do with this line:
$result = mysqli_query($connection,$query);
plex help me fix this
this is my code:
<?php
define("HOSTNAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "");
define("DATABASE", "courses");
$connection = mysqli_connect(HOSTNAME,USERNAME,PASSWORD,DATABASE);
if(isset($_POST['add_data'])) {
$name = $_POST['name'];
$description = $_POST['description'];
$duration = $_POST['duration'];
$price = $_POST['price'];
if($name == "" || empty($name)) {
header('location:index.php?message= you need to fill in your name');
} else {
$query = "insert into `courses` (`name,` `description`, `duration`, `price`) values
('$name', '$description', '$duration', '$price')";
$result = mysqli_query($connection,$query); ERROR line 25
if(!$result) {
die("query Failed".mysqli_error());
} else {
header('location:index.php?insert_msg= your data has been added');
}
}
}
?>
my index page:
https://pastebin.com/diNNpPWk
im trying to make a crud application but i'm unable to insert any data

PHP sql SELECT from database is working, but sql INSERT INTO database is not working even though success message is shown [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I'm trying something new and at the same time practicing PHP. I have checked all the previous posts on StackOverflow and couldn't find the solution. I'm trying to insert some data into the database using PHP and PhpMyAdmin. Now the problem I'm facing is that the data from the database can be displayed (SELECT FROM) if I enter the data manually. When I try to insert data into the database dynamically using PHP example:
$sql = "INSERT INTO apps (appName, appDescription, appLinkFacebook, appLinkInstagram, appLinkPlaystore, appLinkWeb,appGoogleGamesIcon, appFullImageNameBackground, appFullImageNameIcon) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
I get no errors and I also get a success message that is supposed to show after the INSERT command was finished. The images I'm trying to insert are also successfully created inside designated folders and their names are also displayed in the right way. I already checked all the input fields names from the form, all the links and spelling a just can't seem to find the problem. I also tried using INSERT command while using the database on localhost and on a remote server and still nothing. If anyone has an idea on what to do please tell. Thanks
Here is the full source code of my upload.php file.
<?php
if (isset($_POST['btnUpload'])) {
$newFileNameCardBackground = $_POST['imgNameCardBackground'];
if (empty($newFileNameCardBackground)) {
$newFileNameCardBackground = "card_background";
} else {
$newFileNameCardBackground = strtolower(str_replace(" ", "-", $newFileNameCardBackground));
}
$newFileNameCardIcon = $_POST['imgNameCardIcon'];
if (empty($newFileNameCardIcon)) {
$newFileNameCardIcon = "card_icon";
} else {
$newFileNameCardIcon = strtolower(str_replace(" ", "-", $newFileNameCardIcon));
}
$appName = $_POST['appName'];
$appDescription = $_POST['appDescription'];
$appLinkFacebook = $_POST['appLinkFacebook'];
$appLinkInstagram = $_POST['appLinkInstagram'];
$appLinkPlaystore = $_POST['appLinkPlaystore'];
$appLinkWeb = $_POST['appLinkWeb'];
$appGoogleGamesIcon = $_POST['appGoogleGamesIcon'];
$fileCardBackground = $_FILES['fileCardBackground'];
$fileNameCardBackground = $fileCardBackground["name"];
$fileTypeCardBackground = $fileCardBackground["type"];
$fileTempNameCardBackground = $fileCardBackground["tmp_name"];
$fileErrorCardBackground = $fileCardBackground["error"];
$fileSizeCardBackground = $fileCardBackground["size"];
$fileCardBackgroundExtension = explode(".", $fileNameCardBackground);
$fileCardBackgroundActualExtension = strtolower(end($fileCardBackgroundExtension));
$fileCardIcon = $_FILES['fileCardIcon'];
$fileNameCardIcon = $fileCardIcon["name"];
$fileTypeCardIcon = $fileCardIcon["type"];
$fileTempNameCardIcon = $fileCardIcon["tmp_name"];
$fileErrorCardIcon = $fileCardIcon["error"];
$fileSizeCardIcon = $fileCardIcon["size"];
$fileCardIconExtension = explode(".", $fileNameCardIcon);
$fileCardIconActualExtension = strtolower(end($fileCardIconExtension));
$allowed = array("jpeg", "jpg", "png", "JPEG", "JPG", "PNG");
if (in_array($fileCardBackgroundActualExtension, $allowed) && in_array($fileCardIconActualExtension, $allowed)) {
if ($fileErrorCardBackground === 0 && $fileErrorCardIcon === 0) {
$imageFullNameCardBackground = $newFileNameCardBackground . "." . uniqid("", true) . "." . $fileCardBackgroundActualExtension;
$fileDestinationCardBackground = "../../img/card_background/" . $imageFullNameCardBackground;
$imageFullNameCardIcon = $newFileNameCardIcon . "." . uniqid("", true) . "." . $fileCardIconActualExtension;
$fileDestinationCardIcon = "../../img/card_logo/" . $imageFullNameCardIcon;
include 'connection.php';
if (empty($appName) && empty($appDescription) && empty($appGoogleGamesIcon)) {
header("Location: ../../admin/admin-main.php?upload=SelectedFields-MUST-NOT-BeEmpty");
exit();
} else {
$sql = "SELECT * FROM apps;";
$statement = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($statement, $sql)) {
echo "SQL statment failed";
} else {
mysqli_stmt_execute($statement);
$result = mysqli_stmt_get_result($statement);
$rowCount = mysqli_num_rows($result);
$sql = "INSERT INTO apps (appName, appDescription, appLinkFacebook, appLinkInstagram, appLinkPlaystore, appLinkWeb,
appGoogleGamesIcon, appFullImageNameBackground, appFullImageNameIcon) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
if (!mysqli_stmt_prepare($statement, $sql)) {
echo "SQL statment failed";
} else {
mysqli_stmt_bind_param(
$statement,
"sssssssss",
$appName,
$appDescription,
$appLinkFacebook,
$appLinkInstagram,
$appLinkPlaystore,
$appLinkWeb,
$appGoogleGamesIcon,
$appFullImageNameBackground,
$appFullImageNameIcon
);
mysqli_stmt_execute($statement);
move_uploaded_file($fileTempNameCardBackground, $fileDestinationCardBackground);
move_uploaded_file($fileTempNameCardIcon, $fileDestinationCardIcon);
header("Location: ../../admin/admin-main.php?upload=success");
}
}
}
} else {
echo "You have an error";
exit();
}
} else {
echo "Yopu need to upload a proper file type";
exit();
}
}
So to sum it up sql SELECT is working when I enter the data manually, images are where they are supposed to be under the right name and there are no errors.
Thanks :D
Found the problem by using this command above my sql statement. Everything works now.
Thanks for your help.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

Json after json_encode showing wrong value after insert in database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to save multidimensional array in database using json_encode. if i echo json string its showing right output but in database string is changed after insert.
here is my code:
$email=$_POST['email'];
$watchlist=$_POST['watchlist'];
$watchshow=$_POST['watchshow'];
$yearshow=$_POST['yearshow'];
$quer = "SELECT email FROM users WHERE email = '$email'";
$q = mysqli_query($conn, $quer);
$count=0;
while($row = mysqli_fetch_array($q)){
$email = $row['email'];
$count++;
}
if($count==1) //if user already exist change greeting text to "Welcome Back"
{
$quer = "SELECT watchlist FROM users WHERE email = '$email'";
$q = mysqli_query($conn, $quer);
while($row = mysqli_fetch_array($q)){
$watch = $row['watchlist'];
}
$data = json_decode($watch, TRUE);
array_push($data,$watchlist);
$add=array();
array_push($add,$watchshow);
array_push($add,$yearshow);
$data[] = $add;
$t = json_encode($data , JSON_FORCE_OBJECT);
$sql = "update users set watchlist='$t' WHERE email='$email'";
if ($conn->query($sql) === TRUE) {
echo'updated';
} else {
echo'error';
}
}
else {
$new=array();
array_push($new,$watchlist);
$add=array();
array_push($add,$watchshow);
array_push($add,$yearshow);
$new[] = $add;
$name = json_encode($new);
$sql1 = "INSERT INTO users (email,watchlist)
VALUES ('$email','$name')";
if ($conn->query($sql1) === TRUE) {
echo 'success';
} else {
echo "Error: " . $sql1 . "<br>" . $conn->error;
}
}
if i echo $name output is
{"0":{"0":"Stranger Things","1":2017}}
but after insert it's showing this in database
{"0":"Stranger Things","1":{"0":"Stranger Things","1":"2017"}}
what i am doing wrong here?
You placed echo to unnecessary variable somewhere in your code thats why it prints name 2 times.. check it properly and remove it.
{"0":"Stranger Things","1":{"0":"Stranger Things","1":"2017"}}
This is happening most probably due to $new[] = $add; when you are using Loop and passing some value inside $new[i].
In first Loop its proper {"0":"Stranger Things","1":2017}
Now in second loop when i will be 1.
So, in position of 1 , {"0":"Stranger Things","1":2017} this is getting inserted again and making final array as {"0":"Stranger Things","1":{"0":"Stranger Things","1":"2017"}}
Show the complete code as it is, to identify the error.
As per the code you have provided, output must be correct.
$email= "abc#gmail.com";
$watchshow="Stranger Things";
$yearshow= 2017;
$new=array();
$add=array();
array_push($add,$watchshow);
array_push($add,$yearshow);
$new[] = $add;
$add=array();
array_push($add,$watchshow);
array_push($add,$yearshow);
$new[] = $add;
echo $name = json_encode($new, true);

I am getting syntax error, unexpected 'header' (T_STRING) in http://localhost:80/opt/lampp/htdocs/user_control.php [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying for user login and registration forms in Android. From past 5 days, I am trying it. I am not able to get it. Can anyone help me please? This is my code user_control.php. I am including the connection.php in user_control.php.
<? php
class user {
private $db;
private $connection;
/* The below one is the consttructor*/
function __construct() {
header('Content-Type: application/json'); /* used for including json format*/
require_once 'connection.php';
$this->db = new DB_Connection();
$this->connection = $this->db->get_connection();
}
public function does_user_exist($email,$password) {
$query = "Select * from userss where email ='$email' and password = '$password'";
$result = mysqli_query($this->connection,$query);
if(mysqli_num_rows($result) > 0){
$json['success'] = 'welcome'.$email;
echo json_encode($json);
mysqli_close($this->connection);
} else {
$query = " Insert into userss(email,password) values ('$email','$password')";
$is_inserted = mysqli_query($this->connection, $query);
if($is_inserted == 1) {
$json['success'] = 'Account created, welcome '.$email;
} else {
$json['error'] = 'Wrong password';
}
echo json_encode($json);
mysqli_close($this->connection);
}
}
}
$user = new user();
if(isset($_POST['email'],$_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
if(!empty($email) && !empty($password)) {
$encrypted_password = md5($password);
$user -> does_user_exist($email,$encrypted_password);
} else {
echo json_encode("You must fill both fields");
}
}
While I am running with postman software by Chrome I am getting the error as I am getting syntax error:
unexpected 'header' (T_STRING) in http://localhost:80/opt/lampp/htdocs/user_control.php
Remove the space in your line 1. Should looks like:
<?php
Try to comment:
//header('Content-Type: application/json'); /* used for including json format*/
Source: https://stackoverflow.com/a/20620606/2381906

How to see if result of SQL query is empty before performing other queries in PHP

I have the following PHP code which is for a voting system of an app.
Its a Q&A app, and the user can vote for questions and answers that are posted.
In my php code, I first check if the user has voted for a specific question.
This would exist in the QVOTES table, with the email and the id of the question being voted for.
When performing this check, I am not sure of how to see if $result is an empty set, so as to submit the user's vote if they have not voted for the question yet.
How can i get this working? All help is greatly appreciated.
<?php
$con=mysqli_connect("127.2.1.1","S837","887","D887");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qid = $_POST['qid'];
$email = $_POST['email'];
$result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = '$email'");
if (!mysqli_num_rows($result) ){
if ($result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, '$email')")) {
mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid");
echo "Update successful";
} else{
echo "Update unsuccessful";
}
} else{
echo "null";
}
mysqli_close($con);
Actually you are doing in a wrong way. Please try to do like this:-
<?php
$con=mysqli_connect("127.2.1.1","S837","887","D887");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qid = $_POST['qid'];
$email = $_POST['email'];
$result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = $email") or die(mysqli_error($con)); // no need of extra quote
if ($result->num_rows == 0 ){ // means no vote-up done till now
$result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, $email)")or die(mysqli_error($con)); // insert
if($result){
echo "Vote Added successfully.";
} else{
echo "Error occur while adding vote.Please try again.";
}
} else{
$result = mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid AND EMAIL = $email")or die(mysqli_error($con)); // upddate
if($result){
echo "Vote updated successfully.";
} else{
echo "Error occur while updating vote.Please try again.";
}
}
mysqli_close($con);
Note:- I change message for better understanding. You can change according to your wish. thanks.
How to see if $result is an empty set?
From the docs:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE (Ref)
Use $result->num_rows if $result is not FALSE;

Categories