Using a for loop to insert into mysql - php

So I have a form with 4 array inputs. When I hit submit it only submits the first array values. ID is the current session holder to make sure that it creates multiple rows with the same ID. I'm trying to have it loop through and insert multiple products under the same ID. Any ideas?
session_start();
$conn = new mysqli("$server", "$user_name", "$password", "$database");
$productName = $_POST['productName'];
$productPrice = $_POST['productPrice'];
$productDescription = $_POST['productDescription'];
$productImage = $_POST['productImage'];
$id = $_SESSION['id'];
$productNameCount = count($productName);
if (isset($productName) && isset($productPrice) && isset($productDescription) && isset($productImage)) {
for ($i = 0; $i < $productNameCount; $i++) {
$productNumber = $i + 1;
$sql .= "INSERT INTO Products (id, productNumber, productName, productPrice, productDescription, productImage)
VALUES ('$id', '$productNumber', '$productName[$i]', '$productPrice[$i]',
'$productDescription[$i]', '$productImage[$i]');";
}
$conn->query($sql);
}
mysqli_close($conn);

First you have to find a way to get whole array.
I will write a small example:
var jsonString = JSON.stringify(array_in_javascript);
This is a in javascript.
And then in PHP:
$names = json_decode(stripslashes($_POST['jsonString']));
You must find a way related to your code.
also you can benefit from prepare statement to insert multiply records.

Related

Prevent Form from inserting data multiple times into database

Trying to insert form data into mysql database, my issues is as the user submits the form the data gets inserted twice into database. I know that I am doing something wrong with my 2nd query $query_file = "INSERT INTO upperbit_files... statment as when I remove the whole if loop if(mysqli_query($dbc, $query_info)){...} the form gets submitted once as expected.
Basically I need to insert data into 2 tables. One is for general product info and the other one is to store photos relating to that product both the table are connected via a global variable $advert_id. I am using 2 separate queries
Table1: advert_sell_category1, is for general product info
Table2: upperbit_files, is to store details of the images uploaded
But for some reason the 1st query relating to general product info is getting inserted twice into database and the irony is both the time the $advert_id is the same. Below is my code and a screenshot of the database for your understanding,
if(isset($_POST['postad'])){
$adtype = $_POST['offering_type'];
$manufacturer = mysqli_real_escape_string($dbc, $_POST['manufaturer']);
$mediafile = mysqli_real_escape_string($dbc,$_POST['mediafile']);
$GLOBALS['advrt_post_id'] = crypto_rand_secure(10, 100000);
$query_info = "INSERT INTO advert_sell_category1(advert_id,manufacturer,image_file)
VALUES('$advrt_post_id','$manufacturer','$mediafile')";
$result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));
if(mysqli_query($dbc, $query_info)){
$last_id = mysqli_insert_id($dbc);
$query_link_id = "SELECT advert_id FROM advert_sell_category1 WHERE id = '$last_id' ";
$result_id = mysqli_query($dbc, $query_link_id);
while ($row = mysqli_fetch_assoc($result_id)) {
$link_id = $row['advert_id'];
if(!empty($mediafile)){
$media_file = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafile']));
$media_file = array_filter($media_file);
$media_file_size = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafilesize']));
$media_file_size = array_filter($media_file_size);
$media_file_type = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafiletype']));
$media_file_type = array_filter($media_file_type);
for ($var = 0; $var < sizeof($media_file); $var++){
$query_file = "INSERT INTO upperbit_files(file,size,type,link_id) VALUES ('$media_file[$var]','$media_file_size[$var]','$media_file_type[$var]','$link_id')";
$result_file = mysqli_query($dbc, $query_file) or die(mysqli_error($dbc));
}
}
}
}
/********** Your Code ************/
$result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));
if(mysqli_query($dbc, $query_info)){
/**********************/
See here in if statement you are calling mysqli_query() second time so same data is inserted twice. Use following code to solve your problem
/********** Suggested Code ************/
$result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));
if(mysqli_affected_rows()>0){
/**********************/

MySQL Update Database Where Post Values is in Array

I have a site where users can input multiple values in the text fields, so I created an array for the post values and have successfully inserted the values of the array into the database.
I have a problem updating these values that I have stored in the database. I tried this but it's not working.
<?php
if (!empty($_POST['sub_cat'])) {
$cat_id = $_GET['c_id'];
$subcat_title_array = $_POST['sub_cat'];
for ($i = 0; $i < count($subcat_title_array); $i++) {
$subcat_title = mysqli_real_escape_string($connection, $subcat_title_array[$i]);
$query = "UPDATE sub_categories SET subcat_title = '{$subcat_title}' WHERE subcat_id = $cat_id";
$update_sub_category = mysqli_query($connection, $query);
if (!$update_sub_category) {
die("Query Failed " . mysqli_error($connection));
}
}
}
?>
Is there anything am doing wrong?
Any help will be appreciated.

Trying to randomize where a name is inserted into a table using PHP and SQL

What I'm trying to accomplish is randomize elements of an array which contain column names. Then use those randomized columns names to insert a name into a table.
Here is the code I have and its causing a Internal Server Error.
$sql3 = "SELECT * FROM players";
$result3 = $con->query($sql3);
while ($row3 = $result3->fetch_assoc()) {
$num_bracket1 = $row3["num_bracket"];
$name = $row3["name"];
$y = 1;
while ($y <= $num_bracket1) {
shuffle($bracket_array);
shuffle($player_array);
$sql4 = "UPDATE brackets SET ".$player_array[0]."='".$name."' WHERE bracket_num='".$bracket_array[0]"'";
$result4 = $con->query($sql4);
}
}
It's an obvious infinite loop, you forgot to increment $y inside the while and it never ends.

Not able to extract all values of a column in mysql

I am having problem extracting values from a mysql table:
I need to get all values of picname column from a table where uid condition is satisfied.
Now i have two rows where this condition is satisfied but i am getting output only for 1st case. I am not able to get the second row's value. 1st rows value repeats again for second time.
$i = 0;
for($i;$i<2;$i++)
{
$s = "SELECT picname FROM uploaded_data WHERE uid='$uid'";
$que = mysql_query($s,$db);
while($num = mysql_fetch_array($que))
{
echo $name ['picname'];
}
}
Thank You
it should not give you any result you do not have
$name
should be:
$i = 0;
for($i;$i<2;$i++)
{
$s = "SELECT picname FROM uploaded_data WHERE uid='$uid'";
$que = mysql_query($s,$db);
while($num = mysql_fetch_array($que))
{
echo $num['picname'];
}
mysql_free_result($que);
}

Checking to see if a MySQL row is populated

I have a page that writes to a MySQL table. The table has a set amount of rows (24).
I have an $id variable that's set by a rand() function. I basically want to pull the row at that $id, so if $id was 3, I want to pull the third row. Then, I want to check if there is a price set at that row (indicating that the row is being used). If there is no price, I want to keep $id at the value it has been set at and proceed with the query. If there is a price, I want to re-randomize the $id variable, and check again if that row is used up. When it finds an empty row, proceed with the query.
My solution semi-works, but it seems to have a <10% chance of overwriting a used row, for some reason. I want it to never overwrite a used row.
Here's my code:
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet WHERE id = '$id'";
$res = mysql_query($query,$con);
$newId = $id;
while($row = mysql_fetch_array($res))
{
if($row['price'] != 0)
{
do{
$newId = rand(1, 24);
}while($newId == $id);
}
}
$id = $newId;
mysql_query("UPDATE booklet SET price = '$price', advertiser = '$advertiser', image = '$image', monthsRemaining = '$monthsRemaining', availability = 1 WHERE id = '$id'");
Edit
I had the idea to do this. I loop through the table and I put the 'id' of each unfilled spot into an array. Then I pick randomly from that array. However, there seems to be a bug that I can't find, since the array keeps showing as having nothing in it, even after the loop is run, and $i is the correct figure.
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet";
$res = mysql_query($query,$con);
$i = 0;
$isEmpty = array();
while($row = mysql_fetch_array($res))
{
if($row['price'] == 0)
{
$isEmpty[i] = $row['id'];
$i = $i + 1;
}
}
echo $i . " unfilled spots.";
$n = 0;
while($n<$i)
{
echo $isEmpty[$n];
$n = $n + 1;
}
if($i > 0)
{
$id = $isEmpty[rand(0, $i)];
}
if($i == 0)
{
echo 'All spots have been filled.';
}
I think it is a top level logic problem. Because you populate with random ids, you can get duplicate ids, and so when you update "WHERE id = '$id'" you may be picking up rows already populated.
I don't know your goal, but perhaps using an auto-increment id, and dropping rows that you want to get rid of, is the way to go. A rolling set of rows (24 at a time) but with ever increasing ids, would prevent mistaking one for the other.
If I understand the problem correct, this should work:
SELECT *
FROM booklet
WHERE price = 0 OR price IS NULL
ORDER BY RAND()

Categories