php - why the id automatically turn into 0? - php

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.

Related

Insert query echo success but not updating in mysql database table

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,...)

How to update if exist, otherwise insert in php?

I want to check whether the data is existing or not. If data exists, update the table called "user_star_rate", otherwise insert the data into the table. Inserting is working properly, but the updating is not working.
Here is my code.
$jsqla7 = mysql_query("select * from user_star_rate where product_id='$product_id' and email='$visit_email'") or die(mysql_error());
$jfeta7 = mysql_fetch_assoc($jsqla7);
if($jfeta7 != null) {
$rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ;
} else {
$rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ;
}
If I understand what your saying, you should really be using a replace into and it would also decrease your code significantly.
Your code would become:
$query = "REPLACE INTO user_star_rate(product_id, email) VALUES('$product_id', '$visit_email')";
mysql_query($query) or die(mysql_error());
If it already exists then it will update it, else it will insert it. You should pay special attention to the docs in regards to foreign keys and auto incrementing ids.
Try this :
$tot = mysql_num_rows($jfeta7);
if($tot > 0){
$rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ;
} else {
$rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ;
}
Try:
$jsqla7 = mysql_query("select count(*) from user_star_rate where product_id='$product_id' and email='$visit_email'") or die(mysql_error());
$count = mysql_num_rows();
if($count) {
$rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ;
} else {
$rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ;
}

Solve with only one query?

I have the following table:
CREATE TABLE list(
country TINYINT UNSIGNED NOT NULL,
name VARCHAR(10) CHARACTER SET latin1 NOT NULL,
name_index INT UNSIGNED NOT NULL,
UNIQUE KEY(country, name), PRIMARY KEY(country, name_index)) ENGINE = INNODB
I want to:
Given: ($country, $name, $new_index)
Check if a row with country = $country && name = $name exists.
If the row exists, get the index $index = name_index.
If the row doesn't exist, add it and then get the index.
I can do the following using many queries, but I am looking for an efficient way to do it, using only one query. Is this possible?
It's not possible with only one query.
You CAN do this:
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
$sql = "INSERT INTO (your table) (country, name)
VALUES('$country','$name')";
$query = mysql_query($sql);
$check = mysql_num_rows($query);
if($check > 0) {
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
echo "Error occured while trying to insert new row";
}
}
Hope this helps :).

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