Insert query echo success but not updating in mysql database table - php

I am trying to fetch a cart array through foreach loop. I can fetch array items successfully and when i echo them it shows the correct values. But when i apply insert query for each item to enter in my database table, It does not insert any thing but it shows success. I have 4 tables named:
customers-->serial primary,name,email,password,address,phone,city
products-->productid primary,name,description,image,price
orders-->serial primary,date,customerid foreign key
order_detail-->orderid,productid,quantity,price,color,size
order_detail and orders table should be updated when i click on button.
Here is my code. Any suggestions will be appreciated.
Code
if (isset($_SESSION['login_email'])) {
$email = $_SESSION['login_email'];
//Insert values in order table. This works correctly!!
$query = mysqli_query($con, "SELECT serial FROM customers WHERE email = '$email'");
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$cust_id = $row['serial'];
$date = date('Y-m-d');
$que = mysqli_query($con, "INSERT INTO orders VALUES('', '$date', '$cust_id')");
}
// Fetching serial from orders table. This also works correct.
$q = mysqli_query($con, "SELECT serial FROM orders WHERE customerid = '$cust_id'");
while ($row1 = mysqli_fetch_array($q, MYSQLI_ASSOC)) {
$serial = $row1['serial'];
echo $serial ."\n";
}
//Problem comes here. Here i am trying to insert values in order_details
foreach ($_SESSION['cart'] as $id => $value) {
$subtotal = $value['price'] * $value['quantity'];
$pid = $value['id'];
$quantity = $value['quantity'];
$color = $value['color'];
$size = $value['size'];
}
mysqli_query($con, "INSERT INTO order_detail VALUES ($serial, $pid, $quantity, $subtotal, $color, $size)");
if (true) {
echo "success";
} else {
echo"not success";
}
}

Did you already try this?
if( mysqli_query($con, "INSERT INTO order_detail VALUES ($serial, $pid, $quantity, $subtotal, $color, $size)") ){
echo "success";
} else {
echo"not success";
}
I Think you better can do the insert in this way:
INSERT INTO order_detail (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

Related

INSERT only first row and ignore New entries

I made a form for pharma products where user select the manufacturers name and write the details of the project. Everything is up and running fine except only this issue. Its been hours and i cant figure it out.
The problem is Its only selects the first row and ignore new entries. What i want is it will select every row or every new entry and insert into second database here the code is working with no errors but update only the first row.
//Select Everything from database
$perm = "SELECT * FROM test";
$result34 = mysqli_query($dbc, $perm);
if ($perm) {
//How many rows
$count = mysqli_num_rows($result34);
//Retrieve data
if($count>=1) {
$rows = mysqli_fetch_array($result34);
$namex= $rows['name'];
$categoryx = $rows['category'];
//takeout the spaces and strip tags
$namey = strip_tags($namex);
$category = str_replace(' ', '', $category);
//INSERT INTO TABLES
$sql34 = "INSERT INTO final1 (Name, Category) VALUES ($namey, $category);";
$result55 = mysqli_query($dbc, $sql34);
}
}
With prepared statement:
$sql2 = "INSERT INTO final1 (Name, Category) VALUES (?, ?);";
$stmt1 = mysqli_stmt_init($dbc);
if (!mysqli_stmt_prepare($stmt1, $sql2)) {
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt1, "ss", $namey, $category);
mysqli_stmt_execute($stmt1);
}
you need while loop
//Select Everything from database
$perm = "SELECT * FROM test";
$result34 = mysqli_query($dbc, $perm);
if ($result34) {
//How many rows
$count = mysqli_num_rows($result34);
//Retrieve data
if($count>=1) {
while($rows = mysqli_fetch_array($result34) ){
$namex= $rows['name'];
$categoryx = $rows['category'];
//takeout the spaces and strip tags
$namey = strip_tags($namex);
$category = str_replace(' ', '', $category);
//INSERT INTO TABLES
$sql34 = "INSERT INTO final1 (Name, Category) VALUES ($namey, $category);";
$result55 = mysqli_query($dbc, $sql34);
}
}
}
?>

php - why the id automatically turn into 0?

it just set my id into 0 after i inserted some data into the table
then, I get this kind of error:
Duplicate entry '0' for key 'PRIMARY'.
can someone help me identify the problem?
$query = mysql_query("INSERT INTO customer VALUES('', '$name', '$phone', '$address', '$email_add')") or die(mysql_error());
$i=1;
foreach($_SESSION as $namee => $value)
{
if($value > 0)
{
if(substr($namee, 0, 5) == 'cart_')
{
$id = substr($namee, 5, (strlen($namee)-5));
$get = mysql_query("SELECT * FROM product WHERE code='$id'");
while($get_row = mysql_fetch_assoc($get)){
$sub = $get_row['price'] * $value;
echo '<p>'.$i.' '.$get_row['code'].' '.$get_row['name_nl'].' '.$value.' SubTotal : RM '.$sub.'</p> ';
$getCustomer = mysql_query("SELECT customer.id_customer, customer.name, customer.address, product.code, product.name_nl FROM customer, product WHERE name='$name' AND address='$address'" ) or die(mysql_error());
$data = mysql_fetch_array($getCustomer);
$pemb = $data['id_customer'];
$na = $data['name'];
$al = $data['address'];
$ib = $get_row['code'];
$nb = $get_row['name_nl'];
$i++;
}
}
mysql_query("INSERT INTO book VALUES('', '$pemb', '$na', '$al', '$ib', '$nb', '$value', '$sub', now()) ") or die(mysql_error());
}
}
Primary key fields must have different values.
To resolve this, you must set this field to AUTO_INCREMENT, so each time a new record is entered, the primary key field is incremented automatically.

Sending information from a newly created record to a different MySQL table

I'm making a form that submits a story into a MySQL table called 'work'. I want to later take the id of the newly created record and put the information into a different table.
But when I submit the story, it says:
$workid is undefined.
I can't see the problem though because I believe I've defined it?
<?php
if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) {
$title = strip_tags($_POST['title']);
$story = strip_tags($_POST['story']);
$title = mysqli_real_escape_string($db, $title);
$story = mysqli_real_escape_string($db, $story);
$genre = $_POST['genre'];
$rating = $_POST['rating'];
$query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
$result = $db->query($query);
$data = $result->fetch_assoc();
if ($data['count'] > 0) {
echo "<p>Story already exists!</p>";
} else {
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc())
$workid = $row["id"]; //workid is written here but still considered undefined
}
$query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
$result = $db->query($query);
$query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
$result = $db->query($query);
if ($result) {
echo "<p>Story submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
}
?>
You never did a $db->query() on your INSERT INTO... query string, so it was never inserted, and was overwritten by your SELECT id ... query.
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$db->query($query); // Missing this $db->query()
$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc())
$workid = $row["id"];}
Your $workid might not be initialized, depending on your condition and the result of your SQL query: so try to avoid next operations that will causes warnings/errors by using continue or else

Check to Insert or Update table

See the code below, it check if the data exist in the table, if not exist then insert it or else update the table.
As you can see it look a bit messy - is there anyway to improve the code logic or something smaller? I have a few tables that need doing same thing.
foreach ($sheet as $data) {
// Get Phone ID
$dataPhoneID = mysql_escape_string($data['handset']['phone_id']);
if (isset($stocks[$dataPhoneID])) {
$stockPhone = $stocks[$dataPhoneID ];
$phoneName = mysql_escape_string($stockPhone['description']);
$stock = mysql_escape_string($stockPhone['stock']);
$SQL = "SELECT * FROM phone_affiliate WHERE affiliate_id = 1 AND affiliate_phone_id = '$dataPhoneID'";
$q = mysql_query($SQL);
if (mysql_num_rows($q) == 0) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
if (mysql_query($SQLInsert)) {
$phone_id = mysql_insert_id();
$SQLInsert = "INSERT INTO phone_affiliate (phone_id, affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUE('$phone_id', '1', '$dataPhoneID', '$stock')";
mysql_query($SQLInsert) or die(mysql_error());
}
} else {
$row = mysql_fetch_assoc($q);
$phone_id = $row['phone_id'];
$SQLUpdate = "UPDATE phone_affiliate set stock = '$stock' WHERE affiliate_id = 1 AND phone_id = $phone_id";
mysql_query($SQLUpdate) or die(mysql_error());
}
// Similar code block above for other tables.
}
}
Note: I am aware about PDO but I don't have time to replace it on existing system.
Use mysql's REPLACE INTO or INSERT... ON DUPLICATE KEY UPDATE. For example:
foreach ($sheet as $data) {
// Get Phone ID
$dataPhoneID = mysql_escape_string($data['handset']['phone_id']);
if (isset($stocks[$dataPhoneID])) {
$stockPhone = $stocks[$dataPhoneID ];
$phoneName = mysql_escape_string($stockPhone['description']);
$stock = mysql_escape_string($stockPhone['stock']);
$SQLInsert = "INSERT INTO phone_affiliate (affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUES ('1', '$dataPhoneID', '$stock') ";
$SQLInsert .= "ON DUPLICATE KEY UPDATE stock = '$stock'";
mysql_query($SQLInsert);
if (mysql_insert_id()) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
mysql_query($SQLInsert);
$phone_id = mysql_insert_id();
$SQLUpdate = "UPDATE phone_affiliate set phone_id = $phone_id WHERE affiliate_id = 1 AND affiliate_phone_id = $dataPhoneID_id";
}
}
}
Also you can use INSERT IGNORE construction

Data is not being stored in the database

My code is getting the ID from another, after I get that ID I will insert it to another table. The thing is it's not working, any idea why?
<?php
session_start();
include("Connection.php");
if (isset($_POST['submit'])){
$name = $_POST['customerName'];
mysql_query("INSERT INTO `starbucks`.`orders` (
`ID` ,
`NAME` ,
`TOTAL_PRICE` ,
`TOTAL_ITEMS` ,
`TIME`
)
VALUES (
'' , '$name', '', '',NOW())");
$_SESSION['user'] = $name;
}
$dTime = time();
$myValue = isset($_REQUEST['dValue']) ?$_REQUEST['dValue'] : '';
echo "The time is: {$dTime}<br/>
The choice is {$myValue} ";
$sql = "Select * from product where NAME = '{$myValue}'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)){
$price = $row['PRICE'];
$id = $row['ID'];
echo $id;
$sql2 ="INSERT INTO starbucks`.order_details (ID, ORDER_ID, PRODUCT_ID, QTY) VALUES ('', '', '$id', '1')";
$result2 = mysql_query($sql2);
}
?>
extra back tick in the INSERT, either add another or remove

Categories