Insert into makes new row for every value - php

I have a problem with MySQL. I use PHP with mysqli to write data into prepared table. But if I submit the form, which values have to be written into table, each value makes new row in the table. Here is my code:
session_start();
$_SESSION["Field"]=array("Name1","Name2","Name3",...);
if(!empty($_POST)){
foreach($_SESSION["Field"] as $Variable){
if(!empty($_POST[$Variable])){
$_SESSION[$Variable]=$_POST[$Variable];
}}}
if(array_key_exists("Database",$Collection)){
$Database=mysqli_connect("localhost","dbadmin","password","mydatabase");
mysqli_query($Database,"insert into Table1 (PHPSESSID) values ('".session_id()."')");
foreach($_SESSION["Field"] as $Variable){
if(!empty($_POST[$Variable])){
$_SESSION[$Variable]=mysqli_real_escape_string($Database,$_SESSION[$Variable]);
mysqli_query($Database,"insert into Table1 ($Variable) values ('{$_SESSION[$Variable]}')");
}}
mysqli_close($Database);
}
Update: I think, that the problem is, because all variables should(?) be in one mysqli task. But I didn't find anything about it. Am I right? Should it be somethink like this mysqli_query($Database,"insert into Table1 (Variable1,Variable2,Variable3) values ('Value1','Value2','Value3')");?
Update 2: I think, that it could be also caused by not committing the insert tasks, but it isn't necessary to commit it, so I don't think, it is the problem. But I am a beginner in MySQL and SQL, so maybe I am wrong.
It both looks as a solution of my problem, but I don't know, how to make it in foreach loop with variables from an array. Can anyone help me?

I think you need to understand what foreach and INSERT do before you try using them! Use the foreach loop to build the SQL query string, not commit to the database. After the loop has finished, you will have a complete SQL query that you can execute.
EDIT: Forgot the obligatory "Don't forget to escape your values before inserting them into the database!"
EDIT 2: Here's one answer. Certainly not elegant and not tested but could do the job:
session_start();
if(empty($_POST) || !array_key_exists("Database", $Collection)){
exit;
}
$checklist = array("Name1", "Name2", "Name3");
$query = "INSERT INTO Table1 SET ";
$db = mysqli_connect("localhost", "dbadmin", "password", "mydatabase");
foreach($checklist as $v){
if(!empty($_POST[$v])){
$_SESSION[$v] = $_POST[$v];
$_POST[$v] = mysqli_real_escape_string($db, $_POST[$v]);
$query .= "$v='$_POST[$v]',"
}
}
$query .= "PHPSESSID='" . session_id() . "'";
mysqli_query($db, $query);
mysqli_close($db);

Related

Proper way to manipulate database

My entry form I have an inventory database with tables like aluminium, iron etc... Each table contains a subcategory of items like aluminium_pala, iron_1.5inch and so on. The entry code is like this:
include("dbConnect.php");
$orderNo = $_POST["number"];
if(isset($_POST["mat1"])&&$_POST["mat1"]!=NULL)
{
$mat1 = $_POST["mat1"];
$selmat1 = $_POST["selmat1"];
$amtmat1 = $_POST["amtmat1"];
$query = "INSERT INTO $mat1 ($selmat1,orderNo) VALUES (-$amtmat1,$orderNo);";
if(!($result = $mysqli->query($query)))
print "<div class='error'>insertion failed. Check your data</div>";
}
if(isset($_POST["mat2"])&&$_POST["mat2"]!=NULL)
{
$mat2 = $_POST["mat2"];
$selmat2 = $_POST["selmat2"];
$amtmat2 = $_POST["amtmat2"];
$query = "INSERT INTO $mat2 ($selmat2,orderNo) VALUES (-$amtmat1,$orderNo);";
if(!($result = $mysqli->query($query)))
print "<div class='error'>insertion failed. Check your data</div>";
}... and it goes on till mat11
I am trying to collect each similar table (mat1, mat2..) and their corresponding item (selmat1, selmat2...) and bunch the all in one query. That is, instead of going
INSERT INTO al_openable (zPala,orderNo) VALUES (23,14);
INSERT INTO al_openable (outer,orderNo) VALUES (50,14);
I am trying to execute it like
INSERT INTO al_openable (zPala,outer,orderNo) VALUES (23,50,14);
I need this to avoid duplicate foreign key entry(for $orderNo). One idea I've been considering is to use UPDATE if the order number is pre-existing. Do you guys think this is a good idea? And if so, what will be the best way to execute it? If not, how would a more experienced programmer solve this conundrum?
I think this question is related to your query: Multiple Updates in MySQL
You may use ON DUPLICATE KEY UPDATE in combination with INSERT statement.

Seemingly identical sql queries in php, but one inserts an extra row

I generate the below query in two ways, but use the same function to insert into the database:
INSERT INTO person VALUES('','john', 'smith','new york', 'NY', '123456');
The below method results in CORRECT inserts, with no extra blank row in the sql database
foreach($_POST as $item)
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
The code below should be generating an identical query to the one above (they echo identically), but when I use it, an extra blank row (with an id) is inserted into the database, after the correct row with data. so two rows are inserted each time.
$mytest = "INSERT INTO person VALUES('','$_POST[name]', '$_POST[address]','$_POST[city]', '$_POST[state]', '$_POST[zip]');";
Because I need to run validations on posted items from the form, and need to do some manipulations before storing it into the database, I need to be able to use the second query method.
I can't understand how the two could be different. I'm using the exact same functions to connect and insert into the database, so the problem can't be there.
below is my insert function for reference:
function do_insertion($query) {
$db = get_db_connection();
if(!($result = mysqli_query($db, $query))) {
#die('SQL ERROR: '. mysqli_error($db));
write_error_page(mysqli_error($db));
} #end if
}
Thank you for any insite/help on this.
Using your $_POST directly in your query is opening you up to a lot of bad things, it's just bad practice. You should at least do something to clean your data before going to your database.
The $_POST variable often times can contain additional values depending on the browser, form submit. Have you tried doing a null/empty check in your foreach?
!~ Pseudo Code DO NOT USE IN PRODUCTION ~!
foreach($_POST as $item)
{
if(isset($item) && $item != "")
{
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
}
}
Please read #tadman's comment about using bind_param and protecting yourself against SQL injection. For the sake of answering your question it's likely your $_POST contains empty data that is being put into your query and resulting in the added row.
as #yycdev stated, you are in risk of SQL injection. Start by reading this and rewrite your code by proper use of protecting your database. SQL injection is not fun and will produce many bugs.

PHP INSERT into creates Database error

I am attempting to create a function that will insert items (and will do the same to edit) items in a database through a form. I have the form and the PHP - and when I run the function, I get the correct database name to pull and the variable names to pull along with the values I input, but I then see a database error? Any help would be great (I'm still newer to PHP really and pulling out some hair)
Config File:
$hostname = 'localhost';
$username = 'DEFINED';
$password = 'DEFINED';
$database = 'DEFINED';
$table = 'recipes';
require('../config.php');
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($database,$link);
/* Get values and submit */
$rid = mysql_real_escape_string($_POST['rid']);
$name = mysql_real_escape_string($_POST['name']);
$category = mysql_real_escape_string($_POST['category']);
$tags = mysql_real_escape_string($_POST['tags']);
$search_tags = mysql_real_escape_string($_POST['search_tags']);
$description = mysql_real_escape_string($_POST['description']);
$description2 = mysql_real_escape_string($_POST['description2']);
$recipeAbout = mysql_real_escape_string($_POST['recipeAbout']);
$ingredients_1 = mysql_real_escape_string($_POST['ingredients_1']);
$directions_1 = mysql_real_escape_string($_POST['directions_1']);
$query = "INSERT INTO $table (name, category, tags, search_tags, description,description2, recipeAbout, ingredients_1,directions_1) VALUES ('$name','$category','$description','$description2' $tags','$search_tags','$description','$recipeAbout','$ingredients_1','$directions_1')";
echo $query;
Besides the missing comma in '$description2' $tags' => '$description2', $tags' which you said had been added afterwards, and signaled by Ryan: there's also a missing quote, so change it to '$description2', '$tags' and having 2x '$description' variables, remove one.
VALUES
('$name','$category','$tags','$description','$description2', '$search_tags','$recipeAbout','$ingredients_1','$directions_1')";
However, the most important part to querying, is that you must use mysql_query() which you are not using => mysql_query() which is why data isn't being inserted, once you've fixed the syntax errors.
mysql_query() is the essential part.
Add the following to your code:
if(mysql_query($sql,$link)){
echo "Success";
}
else{
echo "Error" . mysql_error();
}
Plus, use prepared statements, or PDO with prepared statements.
You're using a deprecated library and open to SQL injection..
Plus make sure you have assigned $table to the table you wish to enter data into. It's not shown in your question.
You also did not show what your HTML form contains. Make sure that you are using a POST method and that all elements are named with no typos.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Sidenote: Error reporting should only be done in staging, and never production.
EDIT: and using mysqli_
As a quick test, try the following and replacing the values in the line below with your own.
<?php
$link = mysqli_connect("host","username","password","database")
or die("Error " . mysqli_error($link));
$table = "recipes";
$name = mysqli_real_escape_string($link,$_POST['name']);
mysqli_query($link,"INSERT INTO `$table` (`name`) VALUES ('".$name."')")
or die(mysqli_error($link));
?>
If that still does not work, then you need to check your database, table, column name(s), including types and column lengths.
Lot's of stuff wrong here...
You're missing a quote on the second of these two items, as well as either a string concat or a comma: '$description2' $tags'
You've also got your order messed up for tags, search tags, and description 1/2.
$description is in there twice (you have 9 columns defined and 10 values in your statement)
You don't seem to have declared a value for $table
As Fred -ii- has pointed out in his answer, you're missing mysql_query() to actually run it. I assumed you have it further down in your code, but it's missing from the post, which is causing some confusion...
Also, consider updating to use mysqli instead of mysql functions.
what are you echoing $query for?
You do not have any reason to do that except if you just want to use it as a string variable.
it should be mysql_query($query);
What is the exact "database error" error you are getting?
I suggest reading this article about PDO
If you can't insert the data correctly, this might be your problem too.

ON DUPLICATE KEY UPDATE creating new records

I am having problems with the following code, it seems to work and creates the records just fine, the problem is each time I hit submit, instead of it updating the record it just creates a new one. If I turn off auto incremental for the primary key it updates the record just fine but then doesn't create any new ones, it seems either one or the other :-S
<?php
$query = mysql_query("
INSERT INTO hqfjt_chronoforms_data_emailform
(cf_id,cf_uid,emailformname,datesent)
VALUES
('$_POST[cf_id]','$_POST[cf_uid]','$_POST[emailformname]','$_POST[datesent]')
ON DUPLICATE KEY UPDATE
datesent='$_POST[datesent]';
") or die(mysql_error());
?>
did you already try to echo your query string? guess the variable replacement inside it is wrong. try something like that for debugging:
<?php
$sql = "INSERT INTO hqfjt_chronoforms_data_emailform
(cf_id,cf_uid,emailformname,datesent)
VALUES
('{$_POST['cf_id']}','{$_POST['cf_uid']}','{$_POST['emailformname']}','{$_POST['datesent']}')
ON DUPLICATE KEY UPDATE
datesent='{$_POST['datesent']}'";
echo $sql; // for debugging
$query = mysql_query($sql) or die(mysql_error());
?>
Note the corrected variable names above. (curly braces around it, quotes around the array index)
I can't imagine it's the problem, but does the same thing happen when you cast the ID to an int and leave out the quotes?
<?php
$query = mysql_query("
INSERT INTO hqfjt_chronoforms_data_emailform
(cf_id,cf_uid,emailformname,datesent)
VALUES
(" . (int) $_POST['cf_id'] . ",'$_POST[cf_uid]','$_POST[emailformname]','$_POST[datesent]')
ON DUPLICATE KEY UPDATE
datesent='$_POST[datesent]';
") or die(mysql_error());
?>
By the way, you really shouldn't use your $_POST variables in your query without mysql_real_escape_string or better yet, use prepared statements (PDO or mysqli).

PHP foreach insert statement issue with arrays

Hey guys, i'm currently learning php and I need to do this
$connection = mysql_open();
$likes= array();
foreach($likes as $like)
{
$insert3 = "insert into ProfileInterests " .
"values ('$id', '$like', null)";
$result3 = # mysql_query ($insert3, $connection)
or showerror();
}
mysql_close($connection)
or showerror();
For some reason this does not work =/ I don't know why. $likes is an array which was a user input. I need it to insert into the table it multiple times until all of the things in the array are in.
EDIT I fixed the issue where I was closing it in my foreach loop. mysql_open is my own function btw.
Any ideas?
For one $likes is an empty array in your example, I am assuming you fix that in the code you run.
The second is you close the MySQL connection the first the time the loop would run, which would prevent subsequent MySQL queries from running.
there's no such function as mysql_open
you may need mysql_connect
also $likes variable is empty. so no foreach iterations will execute.
You close the connection within the foreach loop.
Here is the proper formatted code to insert data...You can use this.
// DATABASE CONNECTION
$conn=mysql_connect(HOST,USER,PASS);
$link=mysql_select_db(DATABASE_NAME,$conn);
// function to insert data ..here $tableName is name of table and $valuesArray array of user input
function insertData($tableName,$valuesArray) {
$sqlInsert="";
$sqlValues="";
$arrayKeys = array_keys($valuesArray);
for($i=0;$i < count($arrayKeys);$i++)
{
$sqlInsert .= $arrayKeys[$i].",";
$sqlValues .= '"'.$valuesArray[$arrayKeys[$i]].'",';
}
if($sqlInsert != "")
{
$sqlInsert = substr($sqlInsert,0,strlen($sqlInsert)-1);
$sqlValues = substr($sqlValues,0,strlen($sqlValues)-1);
}
$sSql = "INSERT INTO $tableName ($sqlInsert) VALUES ($sqlValues)";
$inser_general_result=mysql_query($sSql) or die(mysql_error());
$lastID=mysql_insert_id();
$_false="0";
$_true="1";
if(mysql_affected_rows()=='0')
{
return $_false;
}
else
{
return $lastID;
}
}
// End Of Function
While many PHP newbies (myself included) begin working with databases from good ole' mysql_connect/query/etc., I can't help suggest that you look into PDO, PHP Data Objects. Depending on your prior knowledge and programming background, there may be a steeper learning curve. However, it's much more powerful, extensible, etc.; I use PDO in all my production code database wheelings-and-dealings now.

Categories