INSERT only first row and ignore New entries - php

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);
}
}
}
?>

Related

I need to fetch the data from mysql database using the employee id from the table

I need to fetch the data from the table using the employee id,
there are two tables
1."user_info" which contains id, name,password,email,ScheduleDate,etc!
2."fetch" which contains id,ScheduleDate,starttime,endtime,hours,employeeid.
if i give the name and the password it takes the id of the particular user from "user_info" and it should send the id as the employee id to the table "fetch" and it should fetch the data from that employee id.
User_info database
fetch database
for example if i give the input as name :rajesh password:1995 in user_info,it should take the id of this user and it should send the id as employee id as 15 to the "fetch" table.
when i tried to send the id as employee id it doesn't print anything,and didn't show any error.
<?php
require "init.php";
$name = "surya";
$password = "1995";
$Sql = "SELECT * FROM `user_info`
WHERE `name`='".$name."' AND
`password`='".$password."';";
$result = mysqli_query($con, $Sql);
$retrive = array();
while($row = mysqli_fetch_array($result))
{
$user_id = $row['id'];
$sql = "SELECT id, ScheduleDate, StartTime,Endtime, Hours,Employeeid
FROM empdet WHERE Employeeid ='".$user_id."' ";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$id=$row["id"].
$date=$row["ScheduleDate"];
$start=$row["StartTime"];
$end=$row["Endtime"];
$hour=$row["Hours"];
$Employeeid=$row["Employeeid"];
list($year,$month,$day) = split("-",$date);
$data[] = array("year"=>$year,
"month"=>$month,
"day"=>$day,
"StartTime"=>$start,
"Endtime"=>$end,
"Hours"=>$hour );
}
$response = $data;
} else
{
echo "0 results";
}
}
echo json_encode(array("user_data"=> $response));
?>
i need to fetch all the 3 data from the "fetch" table using the employee id 15.can anyone help to find it out this?
From my understanding your code is correct till second query. In that query execution, you will get multiple records. So you need to use loop for that.
See below example code:
while ($rows = $result->fetch_assoc()) {
$date=$rows["ScheduleDate"];
$start=$rows["StartTime"];
$end=$rows["Endtime"];
$hour=$rows["Hours"];
list($year,$month,$day) = split("-",$date);
$data[] = array("year"=>$year,
"month"=>$month,
"day"=>$day,
"StartTime"=>$start,
"Endtime"=>$end,
"Hours"=>$hour );
}
$response = $data;
Let me know if it helps.
I would use 'INNER JOIN' to achieve what you want:
$sql = "SELECT fetch.ScheduleDate, fetch.StartTime, fetch.Endtime, fetch.Hours"
." FROM fetch INNER JOIN user_info ON fetch.id = user_info.id"
." WHERE user_info.name = ? AND user_info.password = ? ";
//Prepare statement
$stmt = $mysqli_prepare($con, $sql);
//Bind parameter (id)
mysqli_stmt_bind_param($stmt, ss, $name, $password);
//Execute statement
mysqli_stmt_execute($stmt);
//Bind results
mysqli_stmt_bind_result($stmt, $date, $start, $end, $hour);
//Fetch values (puts the values into the variables)
mysqli_stmt_fetch($stmt);

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

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

PHP / MySQL : Insert if doesnt exist else update [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
create a mysql record if it doesnt exist, else update it
I have created a bit of PHP that gets data from a CSV and updates a Database Table to match the CSV's data.
My next task is, To check if the record exists, based on the unique column (sku). If it does exist update the database table dependant on the change.
Otherwise if that SKU column doesnt match do the INSERT.
The code I've got at the moment runs, However the issue I have is that if a new item is created it seems to run the update through the already existing records.
My code can be found on Pastebin
Or also here...
<?php
$con = mysql_connect("localhost", "root", "");
if(!$con)
{
die('Could not connect' . mysql_error());
}
mysql_select_db("db_lemonstand", $con);
class csvIterator extends LimitIterator
{
public function __construct($path)
{
$csv = new SplFileObject($path);
$csv->setFlags(SplFileObject::READ_CSV);
parent::__construct($csv, 1);
}
}
foreach (new csvIterator('data/catalogue.csv') as $entry) {
$name = $entry[23];
/* Replace Strings To Make URL Name */
$search_array = array(" ", "/", "+");
$replace_array = array("-");
$url_name = strtolower($name);
$url_name = str_replace($search_array, $replace_array, $url_name);
$long_desc = $entry[9];
$short_desc = $entry[23];
$manufacturer = $entry[11];
$price = $entry[15];
$sku = $entry[2];
$weight = $entry[29];
$width = $entry[30];
$height = $entry[5];
$enabled = '1';
$created_at = date('Y-m-d H:i:s');
$product_type_id = '1';
$tax_class_id = '1';
echo '<pre>';
print_r($entry);
echo '</pre>';
// Check see if products' SLU already exists or not
$product_exists = "SELECT sku FROM shop_products WHERE sku = '$sku'";
$result = mysql_query($product_exists, $con);
$exists = mysql_num_rows($result);
if($exists == 0 )
{
$insert = "INSERT INTO shop_products (name, description, short_description, url_name, price, sku, weight, width, height, enabled, created_at, tax_class_id, product_type_id) VALUES ('$name', '$long_desc', '$short_desc', '$url_name', '$price', '$sku', '$weight', '$width', '$height', '$enabled', '$created_at', '$tax_class_id', '$product_type_id')";
$insert_data = mysql_query($insert, $con);
}
else
{
$update = "UPDATE shop_products SET name = '$name', description = '$long_desc', short_description = '$short_desc', url_name = '$url_name', price = '$price', sku = '$sku', weight = '$weight', height = '$height', enabled = '$enabled', created_at = '$created_at', tax_class_id = '$tax_class_id', product_type_id = '$product_type_id'";
$update_data = mysql_query($update, $con);
if (!mysql_query($update,$con))
{
die('Error: ' . mysql_error());
}
}
}
You can use
INSERT INTO mytable on DUPLICATE KEY UPDATE...
You must set unique key for your table (one or more fields) and than you can use this ability.
In my example I have unique key (template, date)
$sql = 'INSERT INTO myTable
(`template`,`date`,`count`) VALUES
("' . $template . '","' . $curDate . '", 1)
ON DUPLICATE KEY UPDATE count = count + 1';
Store store you fields in a var as $fields or anything else that you want and execute this query for that you need a single field as reference that's why i included $Id
INSERT INTO table_name SET id = '$Id', $fields ON DUPLICATE KEY UPDATE $fields

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

Categories