Prevent Form from inserting data multiple times into database - php

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){
/**********************/

Related

How to select all rows, and update field in row within the same while loop?

I'm trying to query all data, manipulate 2 of the fields to create a new value, and then update an existing field (woocat) within the same row with this new value. It runs without error, but no updating happens. What am I missing?
# Get all data
$query = "SELECT * FROM cities";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($result))
{
$cityid = $row['id'];
$city = $row['city'];
$state_abr = $row['state_abr'];
$state = $row['state'];
$gstate = ucwords($state); // HELLO WORLD!
$gstate = ucwords(strtolower($gstate)); // Hello World!
$gcity = ucwords($city); // HELLO WORLD!
$gcity = ucwords(strtolower($gcity)); // Hello World!
$woocat = ("Towns>$gstate>$gcity");
// FIX THIS to make it work
$query = "UPDATE cities SET woo_cat = '$woocat' WHERE id = '$cityid'";
mysqli_query($con, $query);
}
mysqli_close($con);
You are modifying the loop variable inside the loop. When you do mysqli_query($con, $query); you are modifying the values of $row = mysqli_fetch_assoc($result) to the values of the new query inside the same loop, so it won't work,you can do three things:
Use a different connection for the first query ('select') and the second query ('update')
Use two loops, one to fetch the results of the select and another one to update the rows
Use mysqli_fetch_all($result,MYSQLI_ASSOC) and then loop over the results to make the update

Getting data from POST [id] form in PHP

On a table that displays data from a database, I have a form that has a text area on which a user can type a receipt number and submit to save in a database for a specif row. The PHP code below is what updates the database after the form is submitted.
I want to pick the rest of the details for the specific row so I used the $_POST['id'] on which the receipt has been submitted. The id is the primary key. I'm however having a challenge since I can't fetch data from the database using $id = $_POST['id'];I created before outside the function The update statement works perfectly but the SELECT STATEMENTdoesn't . How do I go about it? Any one?
if(isset($_POST['submit'])) {
$rec = $_POST['receipt'];
$id = $_POST['id'];
//reate connection
$sql = "UPDATE customer SET `receipt` = '".$_POST['receipt']."', `date_entered` = NOW(), `receipt_lock` = 1 WHERE `id` = '".$_POST['tid']."' AND receipt_lock = 0";
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit();
$conn->close();
}
function wall(){
global $recp;
global $id;
// Create con
$sql = "SELECT * FROM customer WHERE id ='$id'";
$result1 = mysqli_query($conn, $sql);
$resultarr = mysqli_fetch_assoc($result1); // fetch data
$name = $resultarr['name'];
echo "$name"; //Does not display
$amount = $resultarr['amount'];
$transaction_id = $resultarr['trans_id'];
$date = $resultarr['time_paid'];
}
else {
echo "this is not right!;
}
wall();
Ignoring all the (valid) questions about SQL security and just addressing your problem - how about passing the $id variable as a parameter to your wall function.?
wall($id);
function wall($id){
$sql = "SELECT * FROM customer WHERE id ='$id'";
// ... use prepared statements for security...
...
}
Looks like you are using $_POST['tid'] instead of $_POST['id'] or $id in your SQL-query.
What you are doing there is a big nono, in terms of security. Make sure you escape your POST parameters before adding them inside your query.
$id = $_POST['id'];
$id = mysqli_real_escape_string($conn, $id);
http://php.net/manual/ro/mysqli.real-escape-string.php
Think about sending data as parameters of a function function wall($id) instead of a global parameter.

select a single value from table into a field from while loop

I have a select option to get data from a table by using while loop
$select_material_code = "SELECT material FROM tbl_material";
$get_material_code = mysqli_query ($con, $select_material_code);
$options_material_Code = "--Select material Code--";
while ($result_material_code = mysqli_fetch_array($get_material_code))
{
$options_material_Code = $options_material_Code."<option>$result_material_code[0]</option>";
}
All data is coming into the list as expected, so, i want to continue selection data from selection option and fetch a value into next textbox, but i cannot get it.
please help....
$select_material_code = "SELECT material FROM tbl_material";
$get_material_code = mysqli_query ($con, $select_material_code);
$options_material_Code = "--Select material Code--";
while ($result_material_code = mysqli_fetch_array($get_material_code))
{
$options_material_Code =
$result_material_Code."<option>$result_material_code[0]</option>";
}

mysql insert statement inside a while statement adds only 1 record

I have this code (refer below)
$sql = "SELECT * FROM records";
$result = mysqli_query($this->db,$sql);
while($row = mysqli_fetch_assoc($result)){
$itemid = $row['id'];
$itemname = $row['itemname'];
$itemdesc = $row['itemdesc'];
$brand = $row['brand'];
$serialno = $row['serialno'];
$nostock = $row['nostock'];
$price = $row['price'];
$onsale = $row['onsale'];
$poster = $row['poster'];
$thedate = $row['thedate'];
$sql = "INSERT INTO backupp SET id='$itemid', itemname='$itemname', itemdesc='$itemdesc', brand='$brand', serialno='$serialno', nostock='$nostock', price='$price', onsale='$onsale', poster='$poster', thedate='$thedate'";
$result = mysqli_query($this->db,$sql) or die(mysqli_error($this->db));
return $result;
}
as you can see from the above codes, it will first pull all the data from db table named "records" and then put each row into there corresponding variable and then insert the stored data (those data that has been pulled from db table name "records" and stored on there corresponding variable) to db table named "backupp". Now, the problem is, it only add one record to backup (the record that has been pulled first) which supposedly it should add all the pulled record from db table named records to db table named backup. why?? any suggestions, recommendations, clues and ideas would be greatly appreciated. Thank you!
PS: its like export and import to other table with same structure but I have my own reason why I want to do it this way and assume I already successfully connected to a database ($this->db) called "inventory" and there is db table name there such as "records" and "backupp" with same structure.
And you can easily backup same table this way: INSERT INTO backupp SELECT * FROM records
You have a return statement inside the while loop causing it to exit after one iteration.
Remove the return $result; line and it should work.
change your code into this (see below).
$sql = "SELECT * FROM records";
$result = mysqli_query($this->db,$sql);
$x = 0;
while($row = mysqli_fetch_assoc($result)){
$itemid = $row['id'];
$itemname = $row['itemname'];
$itemdesc = $row['itemdesc'];
$brand = $row['brand'];
$serialno = $row['serialno'];
$nostock = $row['nostock'];
$price = $row['price'];
$onsale = $row['onsale'];
$poster = $row['poster'];
$thedate = $row['thedate'];
$sql = "INSERT INTO backupp SET id='$itemid', itemname='$itemname', itemdesc='$itemdesc', brand='$brand', serialno='$serialno', nostock='$nostock', price='$price', onsale='$onsale', poster='$poster', thedate='$thedate'";
$result = mysqli_query($this->db,$sql) or die(mysqli_error($this->db));
$x++;
}

Multiple SELECT Statements and INSERTS in 1 file

I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}

Categories