im developing shopping cart project , where everything works fine . i would like to ask i thing that how to insert all cart products in to database one by one
below is the code which i try but it only insert first session row not inserting all.
here is the code:
$User_Email=$_SESSION['User_Email'];
$date=date("d-m-Y");
foreach($_SESSION["shopping_cart"] as $v){
$sql = "INSERT INTO reservation (check_in,check_out,room_id,hotel_id,User_Email,date)
values
('{$v['Checkin']}','{$v['Checkout']}','{$v['room_id']}','{$v['room_id']}','$User_Email','$date')";
$update = mysqli_query($connection, $sql);
if ($update) {
$_SESSION['success'] = 'Information updated successfully';
header("location: my_account.php");
exit;
} else {
$_SESSION['errormsg'] = 'Someting is wrong in updating your Information, Please try again later.';
header("location: my_account.php");
exit;
}}
please tell me how to insert all cart values in to database.
thanks in advance.
You are using header() in your loop, this will redirect in first iteration either success of failure.
You can store success or failure status in an variable
if ($update) {
$status = 1;
} else {
$status = 0;
}
Then, move your condition outside your loop, as like:
if($status) // your success
{
header('your location');
exit;
}
else{ // failure
header('your location');
exit;
}
Make, sure $status declare as $status = 0; at top level declaration.
Note that, your code is wide open for SQL injection, for preventing SQL injection use PDO
Useful links:
How can I prevent SQL injection in PHP?
Are PDO prepared statements sufficient to prevent SQL injection?
Related
I want to delete some rows from my table. But when I click delete, this just show me a blank page. I'm sure about id value and my db connection.
This is my code:
// connect to the database
include('connect-db.php');
// confirm that the 'id' variable has been set
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// get the 'id' variable from the URL
$id = $_GET['id'];
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM my_table WHERE id = ? LIMIT 1")) {
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: Dashboard.php");
} else {
// if the 'id' variable isn't set, redirect the user
header("Location: Dashboard.php");
}
There is a similar question MySQLi Prepared Statement not executing
. Basically, you can try running the SQL directly in the database to see if you get any errors. Also confirm that the database user has delete permissions and that the id is stored as an integer in your database.
First I'd suggest you use the $_POST method, you can read more about it GET vs. POST.
Try using bindValue() instead of bindParam(), I believe something else needs to be declared for bindParam() I forget (I'm new at PHP too).
I'm a non-CIS major taking an intro programming classes for a minor through my university. I've been able to successfully code most of the PHP files I need but have been getting hung up over how to perform two functions within the same document. Hopefully you can help.
Within the website, I want to be able to first use MySQL to check a table, called User (where a user is initially registered by the site) to verify that they are in fact registered and that the credentials they provided are correct, and then execute an query to add them to another table.
I've tried mysqli_multi_query to no avail and am just generally inexperienced and unsure of my options as far as functions go.
I have included the code below but be aware that it is a mess as I've attempted several different things before I decided to get some help
<?php
session_start();
require_once("config.php");
$GroupDesc = $_GET["GroupDesc"];
$LeaderID = $_GET["LeaderID"];
$URL = $_GET["URL"];
$Email=$_GET["Email"];
$con = mysqli_connect("$SERVER","$USERID","$DBPASSWORD","$DATABASE");
$query2= "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail) VALUES ('$GroupDesc', '$LeaderID', '$URL', '$Email');";
/* Here I want to perform the first query or $query1 which checks if the
user exists in MySQL and the info submitted in form is same */
$query1= "SELECT * from USER where LeaderID = '$ID' and Email = '$Email';";
if ($status = mysqli_query($con, $query1)) {
} else {
print "Some of the data you provided didn't match our records. Please contact the webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11;
$_SESSION["ErrorMsg"]= "Database insertion failed due to inconsistent data: ".mysqli_error($con);
header("Location:../index.php");
die();
}
/* How do I tell the file to move onto the next query, which is $query2?
if ($query2) {
$query = "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail)
VALUES ('$GroupDesc', '$LeaderUID', '$URL', '$Email');";
} */
} else {
print "Membership update failed. Please contact webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11; // 0: Not Registered, 1: Register, -1: Error
$_SESSION["ErrorMsg"]= "Database Insert failed: ".mysqli_error($con);
header("Location:../index.php");
die();
}
There are a few points where your code can be rearranged to make the logic easier to follow. (Don't worry; this is just stuff that comes with experience.) I'll include some comments within the following code to explain what I've done.
<?php
session_start();
require_once("config.php");
$GroupDesc = $_GET["GroupDesc"];
$LeaderID = $_GET["LeaderID"];
$URL = $_GET["URL"];
$Email=$_GET["Email"];
// mysqli_connect is deprecated; the preferred syntax is
$con = new mysqli("$SERVER","$USERID","$DBPASSWORD","$DATABASE");
$query1= "SELECT * from USER where LeaderID = '$ID' and Email = '$Email';";
$result = mysqli_query($con, $query1);
// I personally prefer the following opening-brace style; I just find it
// easier to read. You can use the other style if you want; just do it
// consistently.
if ($result)
{
$row = mysqli_fetch_assoc($result);
if($row)
{
if (($row['ID'] != $LeaderID) or ($row['Email'] != $Email))
{
// Handle the error first, and exit immediately
print "Some of the data you provided didn't match our records. Please contact the webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11;
$_SESSION["ErrorMsg"]= "Database Insert failed due to inconsistent data: ".mysqli_error($con);
header("Location:../index.php");
die();
}
else
{
// If the query succeeded, fall through to the code that processes it
$query = "INSERT INTO FA15_1052_tuf02984.WebsiteGroups (ID, Description, LeaderID, URL, LeaderEmail)
VALUES ('$GroupDesc', '$LeaderUID', '$URL', '$Email');";
$status = mysqli_query($con, $query);
if ($status)
{
// membership has been updated
$_SESSION["RegState"]=9.5; // 0: Not Registered, 1: Register, -1: Error
$message="This is confirmation that you the group you lead has been added to our database.
Your group's ID in our database is "$GID". Please keep this in your records as you will need it to make changes.
If this was done in error, please contact the webmaster at tuf02984webmaster#website.com";
$headers = 'From: tuf02984webmaster#example.com'."\r\n".
'Reply-To: tuf02984webmaster#example.com'. "\r\n".
'X-Mailer: PHP/' . phpversion();
mail($Email, "You are a group leader!", $message, $headers);
header("Location:../index.php");
// die();
// You only use die() to return from an error state.
// Calling die() creates an entry in the server's error log file.
// For a successful completion, use
return;
}
}
}
}
// If we get here, then something has gone wrong which we haven't already handled
print "Membership update failed. Please contact webmaster.".mysqli_error($con)." <br>";
$_SESSION["RegState"]= -11; // 0: Not Registered, 1: Register, -1: Error
$_SESSION["ErrorMsg"]= "Database Insert failed: ".mysqli_error($con);
header("Location:../index.php");
die();
?>
The basic idiom is: Do something, handle the specific error, handle success, do something else, etc., and finally handle any errors that can come from multiple points. If anything is unclear, just ask and I'll edit into my answer.
I haven't covered prepared statements here. Prepared statements are the preferred way to perform non-trivial queries; they help to resist SQL injection attacks as well as simplify type-matching, quoting and escaping of special characters.
I am having no issue running a select statement but I keep having issues running this update statement, even without where criteria being specified. I have tried everything from defining the sql statement with single quotes, concatenation, calling the sql statement via mysqli and etc but I don't get any error messages that let me know what the actual problem is. The login user has privileges to select, update, and insert so as to separate from the root user and autocommit has been turned off via mysqlworkbench. The html of course is a one page app that submits the form to itself with a select element named p_game, with one of the options being Game A.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo 'Posted.';
if ( !empty($_POST['p_game'])) {
echo 'Got here';
$p_game = $conn->real_escape_string(trim($_POST['p_game']));
$sql = "UPDATE db_name.football_games set home_score = 50, away_score = 100 where name = ''$p_game''";
try{
$result = $conn->query($sql);
echo $sql;
$conn->commit();
echo 'Commit worked.';
}
catch(Exception $e) {
echo $e->getMessage();
}
}
else {
echo 'Game name not found';
}
}
I'm trying to use PHP to enter data from a form. When I try to enter duplicate data a bad message pops like
Something went wrong with this:
INSERT INTO customer VALUES('jamie9422','Jamie Lannister','sept of baelor','jamie#cersei.com',9422222222,0) Duplicate entry 'jamie9422' for key 'PRIMARY' "
Instead, I want to display a clean error message. How can I do that. Here's my code I've written so far...
<?php
include_once "dbConnect.php";
$connection=connectDB();
if(!$connection)
{
die("Couldn't connect to the database");
}
$tempEmail = strpos("{$_POST["email"]}","#");
$customer_id=substr("{$_POST["email"]}",0,$tempEmail).substr("{$_POST["phone"]}",0,4);
//$result=mysqli_query($connection,"select customer_id from customer where customer_id='$customer_id' ");
//echo "customer_id is".$result;
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( mysql_query($query)) {
echo "It seems that user is already registered";
} else {
$command = "INSERT INTO customer VALUES('{$customer_id}','{$_POST["name"]}','{$_POST["address"]}','{$_POST["email"]}',{$_POST["phone"]},0)";
$res =$connection->query($command);
if(!$res){
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
echo "Welcome ".$_POST["name"]." \nCongratulations on successful Registration. Refill your Wallet here";
//$cutomerRetrival = mysql_query("select from customer where customer_id='$customer_id'");
echo "<br>Please note your customer ID :".$customer_id;
}
/*if($result)
{
echo "Query Fired";
$dupentry = mysqli_num_rows($result);
if($dupentry==1)
{
echo "You are already Registered";
exit;
}
}*/
?>
The error code (number) is 1022.
You can e.g. define a constant for that (so that somebody else in x months has a chance to understand the code) like
define('ER_DUP_KEY', 1022);
and then do something like
if(!$res){
if ( <error code>==ER_DUP_KEY ) {
handleDuplicateEntryError();
}
else {
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
}
since I don't know how $res =$connection->query($command); works (and what $connection is I can't tell you exactly how to implement <error code>==ER_DUP_KEY, could be by using mysql_errno.
But it seems to be somehow intermingled with mysql_query($query), i.e. the old, deprecated mysql_* extension and some custom class. You might want to fix that first.... ;-)
see http://docs.php.net/manual/en/mysqlinfo.api.choosing.php
Your code doesn't check for existing record properly
Change
if (mysql_query($query)) {
echo "It seems that user is already registered";
}
to
$result = mysql_query($query);
if (mysql_num_rows($result)) {
echo "It seems that user is already registered";
}
Also, PLEASE do not use $_POST variables without escaping them first, use something like mysql_real_escape_string() to escape each variable passed from the user, otherwise your website will be hacked really fast with SQL Injection.
Make some update into your and then try to get error message 'customer already registered.'
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$res= mysql_query($query);
$customer_count = mysql_num_rows($res);
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( $customer_count > 0 ) {
echo "It seems that user is already registered";
} else {
...................................
Thank you all.
Actually I was using mysqli API in my connectDB.php file..
Hence I needed to call functions on mysqli.
Instead I was calling mysql. i.e I was creating a new connection, thus the query wasn't getting fired at all.
Changed to mysqli->query($result) that is object oriented style
and it worked fine....
Use Try Catch instead.
try{
$res =$connection->query($command);
}catch(Exception $e){
die( "Write your error appropriate message here");
}
Please help i commented off some stuff for testing purposes but nothing works
<?php
//retrieve the data sent in the POST request
$yourDateOrdered =$_POST["DateOrdered"];
$yourDueDate = $_POST["DueDate"];
if(isset($_POST["CompanyName"])){$yourCompanyName = $_POST["CompanyName"];}
//Validate the fields
if ($yourDateOrdered=="" || $yourDateOrdered==null){
$err= $err."Please enter the date the purchase order was made<br>";
}
if ($yourDueDate=="" || $yourDueDate==null){
$err= $err. "Please enter a date when the item is required<br>";
}
//if ($yourCompanyName=="" || $yourCompanyName==null){
//$err= $err."Please enter the customer name<br>";
//}
//Connect to the server and select database
include("dbConnection.php");
//define sql query to execute on the database
$Query1="INSERT INTO orders(CompanyName, DateOrdered, DueDate)
VALUES ('$yourCompanyName','$yourDateOrdered', '$yourDueDate')";
//execute query
//$result = mysql_query($Query1);
//echo("The following order has been added");
//result of the action stored in $Result
$Result = mysql_query($Query1);
if($Result){
echo 'Order entered';
echo Header ("Location:orderformitem.php");
}
//Close the connection
mysql_close($con);
//Check if query executed successfully and forward the user to an appropriate location
//if($queryResult){
//echo "Order save <br>";
//Header ("Location:../PHP/orderformitem.php");
//}
?>
You definietly need to learn how to debug. First, comment out the Header('Location ...'); row, to catch errors.
add error_reporting(E_ALL); and display_errors(1); at top of your file, to see any errors.
Let's var_dump($_POST) to see, is all the variables are correct.
Do a date validation, if you are want correct dates.
Dump your query, and try to run it in sql directly.
DO NOT use mysql functions because they are deprecated. Use mysqli or PDO instead.
Escape your data, to avoid sql injections!