php MySql global variable - php

I'm trying to get the last order id and set it in variable so I'll be able to set this id in another Order_Items table
$generatedId=0;
if(isset($_POST['newOrder'])){
$costumerID = $_POST['CostumerID'];
$orderDateID = $_POST['orderDateID'];
$deliveryDateID = $_POST['deliveryDateID'];
$orderRemeraks = $_POST['orderRemeraks'];
$orderType = $_POST['orderType'];
echo $costumerID;
$query = "INSERT INTO `orders` (`costumerName`,`dateOfOrder`,`dateOfDelivery`,`remarks`,`type`,`status`)
VALUES ('$costumerID','$orderDateID','$deliveryDateID','$orderRemeraks','$orderType', 'open');";
$insertRow = $mysqli->query($query) or die ($mysqli->error.__LINE__);
$generatedId = $mysqli->insert_id;
if($insertRow){
$GLOBALS['generatedId'] = $mysqli->insert_id;
$msg = 'New Order was added ';
echo $msg;
echo $generatedId;
}
}
if(isset($_POST['newItem'])){
$item_Number = $_POST['item_Number'];
$itemQty = $_POST['itemQty'];
$itemKg = $_POST['itemKg'];
$itemRemarks = $_POST['itemRemarks'];
echo $generatedId;
$query = "INSERT INTO `item_number` (`order_id`, `item_number`, `quantity`,`quantity_kg`,` remarks`,`filling_status`)
VALUES('$generatedId', '$item_Number','$itemQty','$itemKg','$itemRemarks','not',);";
$insertRow = $mysqli->query($query) or die ($mysqli->error.__LINE__);
if($insertRow){
echo 'New Item was added ' ;
}
}
The problem is the $genertedId is printed with the initial 0 and there for I can't put it in the order_items table, but in the first time(right after echo $msg, when printing it it's returning the true value;
thank you

$generatedId = mysqli_insert_id($mysqli);
if($insertRow){
$GLOBALS['generatedId'] = $generatedId;
$msg = 'New Order was added ';
echo $msg;
echo $generatedId;
}

Related

form have to click submit twice before success message in php

I am trying to do a reservation/booking page, so I have a form that gets information from the user and details about the services that they would like and add it to the database. I can insert records with no problems, like the record gets recorded only once and a success message if the data get inserted successfully and a fail message if otherwise should follow. The problem is the message would display after clicking the submit button twice or after the page refreshes.
This is how the code of the message looks:
if ($res_bookings){
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
And for the whole php code
<?php
//to get data from form
if(isset($_POST['submit'])){
//assign values
$customer_name = mysqli_real_escape_string($conn, $_POST['customer_name']);
$customer_number = mysqli_real_escape_string($conn ,$_POST['customer_number']);
$customer_email = mysqli_real_escape_string($conn, $_POST['customer_email']);
$event_type = mysqli_real_escape_string($conn, $_POST['event']);
$start = mysqli_real_escape_string($conn, $_POST['event_start']);
$end = mysqli_real_escape_string($conn, $_POST['event_end']);
$address = mysqli_real_escape_string($conn, $_POST['event_address']);
$menus = $_POST['menu'];
$extras = $_POST['extra'];
$booking_id = rand(000, 999);
$event_id = rand(000, 999);
$payment_id = rand(000, 999);
//no empty values to be inserted in database
if($customer_name == ""){
$_SESSION['name'] = "<p class='failed'>PLEASE FILL NAME</p>";
die();
}
if($customer_number == "" && $customer_email == ""){
$_SESSION['contacts'] = "<p class='failed'>PLEASE FILL CONTACTS</p>";
die();
}
if(empty($menus) || empty($extras)){
$_SESSION['menu'] = "<p class='failed'>PLEASE PICK YOUR MENU OR EXTRAS</p>";
die();
}
////for storing event details to event_details table
$query = "INSERT INTO event_details
SET id = ?,
startTime = ?,
endTime = ?,
eventAddress = ?,
event_type = (
SELECT id
FROM events
WHERE id = ?);";
$stmt = $conn->prepare($query);
$stmt->bind_param("isssi", $event_id, $start, $end, $address, $event_type);
$res_event = $stmt->execute();
if (!$res_event){
echo $conn->error;
}
//create booking record
$query_2 = "INSERT INTO bookings
SET id = ?,
customer_name = ?,
customer_contact_no = ?,
customer_email = ?,
eventID = (
SELECT id
FROM event_details
WHERE id = ?);";
$stmt_2 = $conn->prepare($query_2);
$stmt_2->bind_param("isssi", $booking_id, $customer_name, $customer_number, $customer_email, $event_id);
$res_book = $stmt_2->execute();
if (!$res_book){
echo $conn->error;
}
//create menu record
$menu_query = "INSERT INTO menus_bookings
SET
bookingID = (
SELECT id
FROM bookings
WHERE id = ?),
type = (
SELECT id
FROM menus_types
WHERE id = ?);";
$menu_stmt = $conn->prepare($menu_query);
$menu_stmt->bind_param("ii", $booking_id, $menu);
foreach ($menus as $menu){
$res_menu = $menu_stmt->execute();
}
if(!$res_menu){
echo $conn->error;
}
///create extras record
$extras_query = "INSERT INTO extras_bookings
SET
bookingID = (
SELECT id
FROM bookings
WHERE id = ?),
type = (
SELECT id
FROM extras_types
WHERE id = ?);";
$extras_stmt = $conn->prepare($extras_query);
$extras_stmt->bind_param("ii", $booking_id, $extra);
foreach ($extras as $extra){
$res_extras = $extras_stmt->execute();
}
if(!$res_extras){
echo $conn->error;
}
//calculate fees
$menu_sql = "SELECT SUM(mt.price) as 'menu total'
FROM menus_types mt, menus_bookings mb
WHERE mt.id = mb.type
AND mb.bookingID = ?;";
$stmt_menu = $conn->prepare($menu_sql);
$stmt_menu->bind_param("i", $booking_id);
$stmt_menu->execute();
$result_menu = $stmt_menu->get_result();
$row_menu = $result_menu->fetch_assoc();
$menu_total = $row_menu['menu total'];
$extras_sql = "SELECT SUM(et.price) as 'extras total'
FROM extras_types et, extras_bookings eb
WHERE et.id = eb.type
AND eb.bookingID = ?;";
$stmt_extras = $conn->prepare($extras_sql);
$stmt_extras->bind_param("i", $booking_id);
$stmt_extras->execute();
$result_extras = $stmt_extras->get_result();
$row_extras = $result_extras->fetch_assoc();
$extras_total = $row_extras['extras total'];
$total = $menu_total + $extras_total;
$min = $total * .50;
//create payment details
$query_pay = "INSERT INTO payment_details
SET id = ?,
extras_total = ?,
menus_total = ?,
total = ?,
minPayment = ?;
";
$stmt_pay = $conn->prepare($query_pay);
$stmt_pay->bind_param("iiiii", $payment_id, $extras_total, $menu_total, $total, $min);
$res_pay = $stmt_pay->execute();
if(!$res_pay){
echo $conn->error;
}
//add receipt to booking record
$query_booking = "UPDATE bookings
SET receiptID = (
SELECT id
FROM payment_details
WHERE id = ?)
WHERE id = ?;
";
$stmt_bookings = $conn->prepare($query_booking);
$stmt_bookings->bind_param("ii", $payment_id, $booking_id);
$res_bookings = $stmt_bookings->execute();
if ($res_bookings){
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
}
?>
I am not used to using PHP at all, but I think the issue is in the PHP part and not in the HTML.
You are writing this data to the $_SESSION variable and not actually outputting it to the page.
If you wish to show the success message after the form is submitted just use:
if ($res_bookings) {
echo "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
echo "<h2 class='failed'>BOOKING FAILED</h2>";
}
change this last part of your code:
$stmt_bookings = $conn->prepare($query_booking);
$stmt_bookings->bind_param("ii", $payment_id, $booking_id);
$res_bookings = $stmt_bookings->execute();
if ($res_bookings){
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
}
to this :
$stmt_bookings = $conn->prepare($query_booking);
$stmt_bookings->bind_param("ii", $payment_id, $booking_id);
$res_bookings = $stmt_bookings->execute();
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
which means immediately after code execution, success message will be displayed else failed message appears.

Having error when inserting my item name to my phpmyadmin table

SO i want to insert my item id and together with my item name into a distribution_item,it only insert item id but not the name because of the array
i use item[$i] whenever there is a item in the table row, so it get the data and insert.
#$recipient = $_POST['recipient'];
#$address = $_POST['address'];
#$contact = $_POST['contact'];
#$date = $_POST['in_date'];
#$itemID = $_POST['id'];
#$remark = $_POST['remark'];
#$spec_remark = $_POST['spec_remark'];
$itemBalance = $_POST["count"];
$count = count($itemID);
// authentication to the database
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "hopeplace";
//Create connection
$Conndb = mysqli_connect($servername, $username, $password, $dbName);
// Check connection
if (!$Conndb) {
die("Connection failed: " . $Conndb->connect_error);
}
else {
// select database
mysqli_select_db($Conndb, $dbName);
$full_name = "SELECT * FROM recipient WHERE `FULL_NAME` = '$recipient'";
$result = mysqli_query($Conndb, $full_name);
$rec = mysqli_fetch_array($result);
$recipient_id = $rec['HP_ID'];
$item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'";
$result2 = mysqli_query($Conndb, $item_id);
$rec2 = mysqli_fetch_array($result2);
$item_name = $rec2["ITEM_NAME"];
$string = implode(',',$item_id);
$sql = "SHOW TABLE STATUS WHERE `Name` = 'distribution';";
$result = mysqli_query($Conndb, $sql);
$data = mysqli_fetch_assoc($result);
$DISTRIBUTION_ID = $data['Auto_increment'];
// Add into distribution table
$sql = "INSERT INTO distribution(DISTRIBUTION_ID,HP_ID,FULL_NAME, ADDRESS, CONTACT, DISTRIBUTION_DATE, SPEC_REMARK) VALUES ('$DISTRIBUTION_ID','$recipient_id','$recipient', '$address', '$contact', '$date', '$spec_remark')";
if (mysqli_query($Conndb, $sql)) {
//Add item into distribution_item table
$item_count = 0;
for ($i=0; $i<$count; $i++){
$sql = "INSERT INTO distribution_item (DISTRIBUTION_ID, ITEM_ID,ITEM_NAME,OUT_QUANTITY,REMARK) VALUES ('$DISTRIBUTION_ID', '$itemID[$i]','$string[$i]','$itemBalance[$i]', '$remark[$i]')";
if (mysqli_query($Conndb, $sql)){
$out = "UPDATE inventory set QUANTITY = QUANTITY - '$itemBalance[$i]' where ITEM_ID= '$itemID[$i]'";
mysqli_query($Conndb, $out);
//echo "<p>Item $itemID[$i] has been added to $DISTRIBUTION_ID</p>";
$item_count++;
} else {
echo "Error: $sql <br />" . mysqli_error($Conndb);
}
}
if ($item_count == $count){
echo "<div>
<script>
window.alert('Record added successfully!');
</script>
</div>";
}
} else {
echo "Error: $sql <br />" . mysqli_error($Conndb);
}
}
mysqli_close($Conndb);
?>
it pop out an error like this
Notice: Array to string conversion in C:\xampp\htdocs\hopeplace\distribution\add_distribution.php on line 55
Warning: implode(): Invalid arguments passed in C:\xampp\htdocs\hopeplace\distribution\add_distribution.php on line 56
it seems like i have to convert my array to string so i can pass the value into table. my database table is something like this
DISTRIBUTION_ID | ITEM_NAME | ITEM_NAME|
1 1 APPLE
1 2 ORANGE
The problem here is that $string[$i] cannot be found because no $string array exists, since $string = implode(', ',$item_id) can only work if $item_id is an array.
In the question, $item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'"; gives $item_id as a string. That is why the warning error indicates that the implode function cannot work. The notice error shows that you cannot get an array element from the $string variable, and this is because that variable is not an array.
To get $string as an array, you would have to correct the following code:
$item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'";
$result2 = mysqli_query($Conndb, $item_id);
$rec2 = mysqli_fetch_array($result2);
$item_name = $rec2["ITEM_NAME"];
$string = implode(',',$item_id);
For example, the above code could be changed to the following:
$string = [];
$item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'";
$result2 = mysqli_query($Conndb, $item_id);
while($rec2 = mysqli_fetch_array($result2){
$string[] = $rec2["ITEM_NAME"];
}
Then in the sql query for inserting the item name you would first define the counting variable as $count = count($string);

perform two computation in two column and the answer will be save in another column

How can I perform a autocompute in my database ex. the value of Stock and Quantity(Quantity-Stock) the answer will be save in CarryO column
create.php
<?php
require_once 'dbconfig.php';
$con = mysql_connect("localhost","root","");
if($con)
{
mysql_select_db("testproduct",$con);
}
if($_POST)
{
$sql = mysql_query("SELECT * FROM tblproduct WHERE id = '".$_POST['pid']."'");
$prod = mysql_fetch_array($sql);
$pname = $prod['name'];
$actualprice = $prod['actualprice'];
$sellprice = $prod['sellprice'];
$stock = $prod['Stock'];
$gname = $_POST['gname'];
$saledate = $_POST['saledate'];
$quantity = $_POST['quantity'];
$profit = $_POST['profit'];
$carryO = $_POST['carryO'];
$sells = $_POST['sells'];
$expense = $_POST['expense'];
try{
$stmt = $db_con->prepare("INSERT INTO tblsales(pname,gname,saledate,quantity,actualprice,sellprice,carryO,sells,expense,profit,stock)
VALUES(:upname,:ugname,:usaledate,:uquantity,:uactualprice,:usellprice,:ucarryO,:usells,:uexpense,:uprofit,:ustock)");
$stmt->bindParam(":upname", $pname);
$stmt->bindParam(":ugname", $gname);
$stmt->bindParam(":usaledate", $saledate);
$stmt->bindParam(":uquantity", $quantity);
$stmt->bindParam(":uactualprice", $actualprice);
$stmt->bindParam(":usellprice", $sellprice);
$stmt->bindParam(":ucarryO", $carryO);
$stmt->bindParam(":usells", $sells);
$stmt->bindParam(":uexpense", $expense);
$stmt->bindParam(":uprofit", $profit);
$stmt->bindParam(":ustock", $stock);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
thanks for your help just new in php and please let me know if I can use your code or its only a example
Change this part:
$prod = mysql_query("SELECT * FROM tblproduct WHERE id = ".$_POST['pid']);
echo $prod;
$pname = [$prod['name']];
Into:
$sql = mysql_query("SELECT * FROM tblproduct WHERE id = '".$_POST['pid']."'");
$prod = mysql_fetch_array($sql);
$pname = $prod['name'];
You may want to try this.
$prod = mysql_query("SELECT * FROM tblproduct WHERE id = ".$_POST['pid'],$db_con); //$db_con must be your database connection
if(!$prod) { die("Database query failed: " . mysql_error()); } //always check if your query is properly done.
$pname = "";
while ($row = mysql_fetch_array($prod)) {
$pname = $row["name"]; }
also if you are fetching only one column which is the name then be specific to your query for fastest result. e.g. "SELECT name FROM tblproduct WHERE id = ".$_POST['pid']

How to make cart not duplicate items?

I need to know How to not make item duplicate and add quantity from showitem.php to quantity
but I made update to table in sql but nothing happen to the table I don't know why ?
This is addtocart.php
<?php
session_start();
function addtocart($id,$qty){
if (isset($id)){
//connect to database
$mysqli = mysqli_connect("localhost", "root", "", "e-com");
//create safe values for use
$safe_sel_item_id = mysqli_real_escape_string($mysqli,
$id);
$safe_sel_item_qty = mysqli_real_escape_string($mysqli,$qty);
//validate item and get title and price
$get_iteminfo_sql = "SELECT itemname FROM items WHERE itemid = '".$safe_sel_item_id."'";
$get_iteminfo_res = mysqli_query($mysqli, $get_iteminfo_sql)
or die(mysqli_error($mysqli));
if (mysqli_num_rows($get_iteminfo_res) < 1) {
//free result
mysqli_free_result($get_iteminfo_res);
//close connection to MySQL
mysqli_close($mysqli);
//invalid id, send away
header("Location: seestore.php");
exit;
} else {
//get info
while ($item_info = mysqli_fetch_array($get_iteminfo_res)) {
$item_title = stripslashes($item_info['itemname']);
}
//free result
mysqli_free_result($get_iteminfo_res);
$sql = "select sel_item_qty from shooppertrack where sel_item_id = '" .
$safe_sel_item_id . "'";
$res = mysqli_query($mysqli, $sql);
while ($res_info = mysqli_fetch_array($get_iteminfo_res)){
$update_qty = $res['sel_item_qty'];
}
// does quantity exist?
if (mysqli_num_rows($res) > 0 ) {
// get sel_item_qty, add 1, run update query
"UPDATE shooppertrack SET sel_item_qty = sel_item_qty + $update_qty
WHERE sel_item_id = '" .$safe_sel_item_id . "'" ;
} else {
//add info to cart table
$addtocart_sql = "INSERT INTO shooppertrack
(session_id, sel_item_id, sel_item_qty,
date_added)
VALUES ('".$_COOKIE['PHPSESSID']."',
'".$safe_sel_item_id."',
'".$safe_sel_item_qty."',
now())";
$addtocart_res = mysqli_query($mysqli, $addtocart_sql)
or die(mysqli_error($mysqli));
}
//close connection to MySQL
mysqli_close($mysqli);
//redirect to showcart page
header("Location: showcart.php");
exit;
}
} else {
//send them somewhere else
header("Location: seestore.php");
exit;
}
}
addtocart($_POST['sel_item_id'],$_POST['sel_item_qty']);
?>
This is showitem.php
<?php
function show($x){
//connect to database
$mysqli = mysqli_connect("localhost", "root", "", "e-com");
$display_block = "<h1>My Store - Item Detail</h1>";
//create safe values for use
$safe_item_id = mysqli_real_escape_string($mysqli, $x);
//validate item
$get_item_sql = "SELECT c.cat_id , c.cat_name, si.itemid, si.itemname,
si.price, si.descripition, si.photo FROM items
AS si LEFT JOIN categories AS c on c.cat_id = si.cat_id
WHERE si.itemid = '".$safe_item_id."'";
$get_item_res = mysqli_query($mysqli, $get_item_sql)
or die(mysqli_error($mysqli));
if (mysqli_num_rows($get_item_res) < 1) {
//invalid item
$display_block .= "<p><em>Invalid item selection.</em></p>";
} else {
//valid item, get info
while ($item_info = mysqli_fetch_array($get_item_res)) {
$cat_id = $item_info['cat_id'];
$cat_title = strtoupper(stripslashes($item_info['cat_name']));
$item_title = stripslashes($item_info['itemname']);
$item_price = $item_info['price'];
$item_desc = stripslashes($item_info['descripition']);
$item_image = $item_info['photo'];
}
//make breadcrumb trail & display of item
$display_block .= <<<END_OF_TEXT
<p><em>You are viewing:</em><br/>
<strong>$cat_title > $item_title</strong></p>
<div style="float: left;"><img src="$item_image" alt="$item_title" /></div>
<div style="float: left; padding-left: 12px">
<p><strong>Description:</strong><br/>$item_desc</p>
<p><strong>Price:</strong> \$$item_price</p>
<form method="POST" action="addtocart.php">
END_OF_TEXT;
//free result
mysqli_free_result($get_item_res);
$display_block .= "
<p><label for=\"sel_item_qty\">Select Quantity:</label>
<select id=\"sel_item_qty\" name=\"sel_item_qty\">";
for($i=1; $i<11; $i++) {
$display_block .= "<option value=\"".$i."\">".$i."</option>";
}
$display_block .=<<<ENDOFTEXT
</select><p>
<input type="hidden" name="sel_item_id" value="$_GET[itemid]" />
<button type="submit" name="submit" value="submit">Add to Cart</button>
</form>
</div>
ENDOFTEXT;
}
return $display_block;
//close connection to MySQL
mysqli_close($mysqli);
}
?>
You need to query your cart for that item and session before inserting. If it exists, you should update the quantity instead.
$sql = 'select sel_item_qty from shooppertrack where sel_item_id = ' .
$safe_sel_item_id . ' and session_id = ' $_COOKIE['PHPSESSID'];
$res = mysqli_query($mysqli, $sql);
// does quantity exist?
if (mysqli_num_rows($res) > 0 ) {
// get sel_item_qty, add 1, run update query
} else {
// run your insert query
}
Try this
//add info to cart table
$sql = "Select session_id, sel_item_id from shooppertrack where session_id = $sid and sel_item_id = $si_id";
$res = mysqli_query($mysqli, $sql);
if(mysqli_num_rows($res) == 1)
{
// update with qty +1;
}else{
$addtocart_sql = "INSERT INTO shooppertrack
(session_id, sel_item_id, sel_item_qty,
date_added)
VALUES ('".$_COOKIE['PHPSESSID']."',
'".$safe_sel_item_id."',
'".$safe_sel_item_qty."',
now())";
$addtocart_res = mysqli_query($mysqli, $addtocart_sql)
or die(mysqli_error($mysqli));
}

How can I print to table?

I would appreciate it if anyone willing to tell how to echoing /print.
Below is the process of entering data into the database, before inserting it how can I echoing it to the table?
<?php
session_start();
if(isset($_POST['submit']))
{
include('class/stock_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
$from = mysql_real_escape_string(stripslashes($_POST['from']));
$value = floatval($_POST['amount']);
$date = date('Y-m-d H:i:s');
$_SESSION['selected'] = $from;
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
$st->convert($from,$key,$date);
$stc_price = $st->price($value);
$stock = mysql_real_escape_string(stripslashes($stock));
$count = "SELECT * FROM oc_stock WHERE stock = '$key'";
$result = mysql_query($count) or die(mysql_error());
$sql = '';
if(mysql_num_rows($result) == 1)
{
$sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
}
else
{
$sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
}
$result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
}
header("Location: index.php");
exit();
}
?>
Insert this:
echo "<table><tr><th>".implode(array_keys($stocks), '</th><th>')."</th></tr>";
foreach($stocks as $row) echo "<tr><td>".implode('</td><td>', $row)."</tr>";
echo "</table>";
Edit: If printing the data is the goal and the table-view is not important, I recommend print_r($stocks) instead.

Categories