Divide array contents on multiple lines MySQL table with PHP - php

I almost managed to split the different arrays and to prepare them in the table in the MySQL database, I'll explain the situation:
On the main page, the user has the ability to add and remove rows in a table. The table for each line carries with it these inputs:
input1.name = "product[]";
input2.name = "seller[]";
input3.name = "description[]";
input4.name = "quantity[]";
input5.name = "priece[]";
so if the user inserts two rows in each array will be included descriptions of two products, for example:
product: "PS3", "PS4";
seller: "AMAZON", "SONY";
description: "100Gb", "200Gb";
quantity: "1", "2";
price: "100", "200";
This is the layout table:
http://www.mediafire.com/view/ux0su8ssdixfmgc/Cattura2.JPG
The problem arises. I capture the data entered via a post, but I can't distribute these data on several lines. I want you to PS3 both into the first row of MySQL table, and PS4 in the second row of the table. Until now arrays are instantiated only on the first line, in this way, however, there is only one product. It is therefore necessary to prepare each box in the appropriate row of the array. I do not know if I was clear, but I would like to achieve something like this:
http://www.mediafire.com/view/d6f6ahy834jv0p2/Cattura.JPG
Obviously, the data in table I've entered manually and not through code. Was it right for you to understand.
This is the code that I currently use to send multiple arrays on different lines, but it doesn't work.
if(isset($_POST['sending']))
{
if($_POST['sending'] == "save")
{
$row_data = array();
foreach($_POST['sending'] as $key => $value)
{
$product=mysqli_real_escape_string($con,($_POST['product'][$row]));
$seller=mysqli_real_escape_string($con,($_POST['seller'][$row]));
$description=mysqli_real_escape_string($con,($_POST['description'][$row]));
$quantity=mysqli_real_escape_string($con,($_POST['quantity'][$row]));
$priece=mysqli_real_escape_string($con,($_POST['priece'][$row]));
$user=mysqli_real_escape_string($con,($_POST['user'][$row]));
$row_data[] = "('$product', '$seller', '$description','$quantity', '$priece', '$user')";
}
if (!empty($row_data))
{
$sql = 'INSERT INTO test(product,seller,description,quantity,priece,user) VALUES '.implode(',', $row_data);
$result = mysqli_query($con, $sql );
if ($result)
echo 'ADD COMPLETE!: ' . mysqli_affected_rows($con);
else
echo 'ERROR' ;
}
} // if ($_POST['sending'] == "save")
} // if (isset($_POST['sending']))
}//close method

if I understood it well this is how it should work
if(isset($_POST['sending']))
{
if($_POST['sending'] == "save")
{
$row_data = array();
foreach($_POST['sending'] as $key => $value)
{
$product=mysqli_real_escape_string($con,($_POST['product'][$row]));
$seller=mysqli_real_escape_string($con,($_POST['seller'][$row]));
$description=mysqli_real_escape_string($con,($_POST['description'][$row]));
$quantity=mysqli_real_escape_string($con,($_POST['quantity'][$row]));
$priece=mysqli_real_escape_string($con,($_POST['priece'][$row]));
$user=mysqli_real_escape_string($con,($_POST['user'][$row]));
array_push($row_data, "('$product', '$seller', '$description','$quantity', '$priece', '$user')");
}
foreach($row_data as $value){
if (!empty($value))
{
$sql = 'INSERT INTO test(product,seller,description,quantity,priece,user) VALUES '.$value;
$result = mysqli_query($con, $sql );
if ($result)
echo 'ADD COMPLETE!: ' . mysqli_affected_rows($con);
else
echo 'ERROR' ;
}
} // if ($_POST['sending'] == "save")
} // if (isset($_POST['sending']))
}//close method

Related

fetch and check cart data with php mysql

I had cart data in session like product_id, product_name, product_price..... so there is multiple data in session with array it's not fixed..sometime single data and sometime morethan one..... but when customer check out.... I need to check each product with customers entered pincode …..and products have multiple or single pincode in table....so we can get them by session product_id ..... then want to check if those pin match with client/user pincode then store in new session and those products which are not match yet....also move in another new session..... or just want to display product like allowed or not allowed product for this pin
is there any way to make it simple ? i think it's work with foreach inside condtions and all..but still confused.....sorry for bad english !
i had just wrote little code but confused what to next ?
if (!empty($_SESSION["shopping_cart"])){
foreach ($_SESSION["shopping_cart"] as $keys => $value){
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
$select_price_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
}
}
if (!empty($_SESSION["shopping_cart"])) {
foreach ($_SESSION["shopping_cart"] as $keys => $value) {
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
// echo $pro_session_id;
// echo "<br>";
// $select_pin_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
$select_pin_query = "SELECT * FROM product_pincode WHERE product_ID = '$pro_session_id'";
$selected = mysql_query($select_pin_query, $con) or die(mysql_error($con));
$pin_val = array();
while ($get_pin_data = mysql_fetch_assoc($selected)) {
$pin_val[] = $get_pin_data;
}
foreach ($pin_val as $get_pin_data) {
if ($get_pin_data['pincode_number'] == $_SESSION["order_placement_details"][0]['user_pincode']) {
echo "Complete " . $get_pin_data['pincode_number'];
echo "<br>";
} else {
echo "unallowed" . $get_pin_data['pincode_number'];
echo "<br>";
}
}
}

PHP recursive creation of db queries after multidimensional form submission: fk field sometimes "omitted", but why and how to fix?

NOTE: SOLUTION FOUND
I am trying to build a (my first!) PHP/JQuery/MySQL web app able to work with multidimensional data. In current state, almost everything works fine but one strange bug occurs when submitting data (see title) and I haven't found any explanation. Can anyone open my eyes?
When working my test form with 5 dimensional data (table names - one, two, three, four, five - all joined in chain):
if I submit completely new entry with all dimensions then all 5 INSERT INTO queries are generated correctly
but if I add to the existing entry (under 2nd dim) new 3rd dimension with corresponding child data (4th and 5th) - that means tables three, four and five - then foreign key field in table five (four_id) is omitted from the insertion query
all the rest options (two, three, four and five or new four and five) have no issues
There are 3 functions in php that are doing the work (first for main table, second for next 2 dimensions and third (recursive) for next n dimensions). As tables four and five in this example are "belonging" to the recursive one I am quite sure that the issue and key for solution should be there.
Each function is using both form data and existing data that is already submitted. Pk value of parent row is passed to the child in two possible ways:
After each INSERT INTO query a MySQL variable for new pk value is created: SET #last_id_tablename = LAST_INSERT_ID() to be used in child query when needed. If data submitted to parent and child (say four and five) is new for both tables then child table's query should be (and normally is)
INSERT INTO five (four_id, title) VALUES (#last_id_four, 'Some text')
If parent data is already existing and we add new related child row then the existing parent pk value (say 1) is passed to the child and query is
INSERT INTO five (four_id, title) VALUES (1, 'Some text')
So the issue is that when I have an entry with first 2 dimensions and I add 3 dimensions under existing 2nd (IOW I have parent row in one with its child row in two and under this I add new data starting from table three the generated queries are:
INSERT INTO three (two_id, title) values (1, 'Some text');
INSERT INTO four (three_id, title) values (#last_id_three, 'Some text')
INSERT INTO five (title) values ('Some text')
As you see, four_id and #last_id_four are missing in third line.
All other combinations including fully new data submmission for all dimensions are generating a correct query for five. Fully new data submission query list looks like this one (first table's last id is returned before the rest continues, passed to the next function and therefore it's in use already as a real number, let's say 10)
INSERT INTO one (title) values ('Some text');
INSERT INTO two (one_id, title) values (10, 'Some text');
SET #last_id_two = LAST_INSERT_ID();
INSERT INTO three (two_id, title) values (#last_id_two, 'Some text');
SET #last_id_three = LAST_INSERT_ID();
INSERT INTO four (three_id, title) values (#last_id_three, 'Some text')
SET #last_id_four = LAST_INSERT_ID();
INSERT INTO five (four_id, title) values (#last_id_four, 'Some text')
The only one explanation I thought about was that it's somehow related to the variable names in the recursive function and therefore I renamed all of vars but it didn't resolve the issue.
Below I show the full code of this recursive function
/*
Recursive function for inserting or editing nested data (since 4th until nth level)
$subTable - current table where we insert new or edit existing data
$subData - current table's data in form view
$existingSubJoin - current table data that is already in database (submitted earlier)
$existing... - corresponding variables for existing data
$parentTable - current table's parent table (where current tables FK is pointing)
$existingParentJoin - parent table data that already exists
$parentPkField, $parentPkValue - the names are self-explanatory
$parentPkValue can be a real number from existing row or #last_id_$parentTable
#last_id_$subTable - a MySQL variable that passes the last_insert_id() value from newly submitted parent row to the child row's FK
$subSingle - a new array of db field values for one row
$subSet - array for UPDATE statements (SET field = 'value', field2 = 'value2' etc)
$subFields - array of fields for INSERT INTO
$nextLastId = pk value or #last_id_$subTable to be passed as a last argument for next recursion
*/
public function buildQueryListChild($subTable, $subData, $existingSubJoin, $parentTable, $existingParentJoin, $parentPkField, $parentPkValue)
{
if (isset($subData))
{
foreach($subData as $sKey => $subRow)
{
$subSingle = array();
if (!isset($existingSubJoin['rows'][$sKey]))
{
$existingSubRow = $existingSubJoin['rows'][0];
}
else
{
$existingSubRow = $existingSubJoin['rows'][$sKey];
}
$subSet = array();
$subParentId = $parentTable . '_' . $parentPkField;
foreach ($subRow as $subField => $subValue)
{
if (isset($existingSubJoin['properties']['fields']))
{
foreach ($existingSubJoin['properties']['fields'] as $existingSubField)
{
if ($existingSubField['name'] == $subField)
{
if ($existingSubField['key'] == 'PRI')
{
$subRowPkField = $existingSubField['name'];
$subRowPkAlias = $existingSubField['alias'];
}
else
{
$subRowField = $existingSubField['name'];
$subRowAlias = $existingSubField['alias'];
$subRowType = $existingSubField['type'];
}
$sNumTypes = array('int', 'float', 'decimal', 'numeric', 'double', 'bit');
foreach ($sNumTypes as $sType)
{
$sNumber = strpos($existingSubField['type'], $sType) === true ? true : null;
}
$sString = $sNumber ? false : true;
}
}
}
if (empty($subRow[$subRowPkField]))
{
$newSub = true;
$updateSub = false;
}
else
{
$updateSub = true;
$newSub = false;
}
if (!is_array($subValue))
{
if ($subField != $subRowPkField && strpos($subRowType, 'timestamp') === false)
{
if ($subField == $subParentId)
{
$subSingle[$subParentId] = $parentPkValue;
}
else
{
if (!empty($subValue)) $subSingle[$subField] = $subValue;
}
if ($updateSub && $subField == $subRowField && $subSingle[$subField] != $existingSubRow['data'][$subRowAlias])
{
$uSubField = $subField;
$uSubValue = $subValue;
if (!$sNumber)
{
$uSubValue = "'$subValue'";
}
$subSet[$uSubField] = "$uSubField = $uSubValue";
}
}
}
}
if (!empty($subSet))
{
$subSets = implode(', ', $subSet);
$subRowPkValue = $subRow[$subRowPkField];
$current = "UPDATE $subTable SET $subSets WHERE $subRowPkField = $subRowPkValue;\n";
$sql .= $current;
}
if ($newSub)
{
$subRowPkValue = $subRow[$subRowPkField];
if (!empty($subSingle))
{
$subFields = implode(', ', array_keys($subSingle));
$subValues = "'" . implode("', '", array_values($subSingle)) . "'";
$subValues = str_replace("'$parentPkValue'", "$parentPkValue", $subValues);
$current = "INSERT INTO $subTable ($subFields) VALUES ($subValues);\n";
$sql .= $current;
$sql .= "SET #last_id_$subTable = LAST_INSERT_ID();\n";
}
}
foreach ($subRow as $sTable => $sData)
{
if (is_array($sData))
{
if (isset($existingSubJoin['rows'][$sKey]) && $sKey > 0)
{
$nextLastId = $sKey;
}
else
{
$nextLastId = "#last_id_$subTable";
}
$existingSData = $existingSubRow['joins']->$sTable;
$sql .= $this->buildQueryListChild($sTable, $sData, $existingSData, $subTable, $existingSubJoin, $subRowPkField, $nextLastId);
}
}
}
}
return $sql;
}
You see there a line
$current = "INSERT INTO $subTable ($subFields) VALUES ($subValues);\n";
where both $subFields and $subValues are imploded from corresponding submission array (array_keys and array_values) that is created in
if ($subField == $subParentId)
{
$subSingle[$subParentId] = $parentPkValue;
}
else
{
if (!empty($subValue)) $subSingle[$subField] = $subValue;
}
And as said, ($subFields) should always contain parenttable_id and ($subValues) its existing value or #last_id_parenttable
Sorry for this amount of information and thanks in advance for help!
SOLUTION FOUND - see ANSWER
There were also other issues that occurred in my code but, like changes I made in parent function, this is outside of this issue's scope. I hope all my explanations are clear :)
The (main?) cause was that the parent pk field name was not always passed to child. I discovered this when I got idea that the way how the fk value was set was not the best one and that this should be done at very beginning, before creating a new array. So the first thing I did was that I moved it right before iterating the fields
$subParentId = $parentTable . '_' . $parentPkField;
$subRow[$subParentId] = $parentPkValue;
foreach ($subRow as $subField => $subValue)
{ ... }
But it wasn't enough. Yes, I got the needed value but without $parentPkField so I got a nonexisting field name (parenttablename_). Therefore it was clear what I should really look for.
And I got it. Some time ago I built among others a "blank row" feature to be used in some cases when there is no real db row. In this case I just forgot to use it where needed :D
Therefore I had to make some corrections also to the parent function and pass an additional $blank array from there to the child. And of course corresponding changes to the current function. This way the existence of $parentPkField was ensured.
The diffs in this function are here (old commented, new below or otherwise explained)
/*
public function buildQueryListChild($subTable, $subData, $existingSubJoin, $parentTable, $existingParentJoin, $parentPkField, $parentPkValue)
*/
public function buildQueryListChild($subTable, $subData, $existingSubJoin, $blank, $parentTable, $existingParentJoin, $parentPkField, $parentPkValue)
{
.....
if (!isset($existingSubJoin['rows'][$sKey]))
{
// $existingSubRow = $existingSubJoin['rows'][0];
$existingSubRow = $blank['rows'][0];
}
......
// Added
$subRow[$subParentId] = $parentPkValue;
......
foreach ($subRow as $subField => $subValue)
{
// Added
if (!$existingSubJoin) $existingSubJoin = $blank;
......
if ($subField != $subRowPkField && strpos($subRowType, 'timestamp') === false)
{
/*
if ($subField == $subParentId)
{
$subSingle[$subParentId] = $parentPkValue;
}
else
{
if (!empty($subValue)) $subSingle[$subField] = $subValue;
}
*/
if (!empty($subValue)) $subSingle[$subField] = $subValue;
.......
if ($newSub)
{
// Removed as unneeded
//$subRowPkValue = $subRow[$subRowPkField];
if (!empty($subSingle))
{
........
// if / else moved here, see below foreach
if (isset($existingSubJoin['rows'][$sKey]) && $sKey > 0)
{
$nextLastId = $sKey;
}
else
{
$nextLastId = "#last_id_$subTable";
}
foreach ($subRow as $sTable => $sData)
{
if (is_array($sData))
{
/*
if (isset($existingSubJoin['rows'][$sKey]) && $sKey > 0)
{
$nextLastId = $sKey;
}
else
{
$nextLastId = "#last_id_$subTable";
}
*/
// The commented lines above: moved them before foreach but actually not sure if it had any impact
//Added
$nextBlank = $blank['rows'][0]['joins']->$sTable;
/*
$sql .= $this->buildQueryListChild($sTable, $sData, $existingSData, $subTable, $existingSubJoin, $subRowPkField, $nextLastId);
*/
$sql .= $this->buildQueryListChild($sTable, $sData, $existingNextData, $nextBlank, $subTable, $existingSubJoin, $subRowPkField, $nextLastId);

updating each row with previous values plus current values

sorry for the complicated heading.i am doing learning php and got stuck.i have a database table table_name
id(primary key) name ip
1 a 192.168.0.1,192.168.0.5,171.87.65 //separated by comma's
2 b 192.168.0.1,175.172.2.6,164.77.42
now i want to add an array of values ip[0] and ip[1] coming from a two different text-area to the end of the ip's of each name and just updating the ip column of each row.so it will just append new values with previous one.
name a<textarea rows="4" cols="40" name="ip[]"></textarea>
name b<textarea rows="4" cols="40" name="ip[]"></textarea>
<input type="submit" />
this is how its inserted
if(isset($_POST['submit'])) {
$ip_details = $_POST['ip'];
$values = array(
array('id' => '"1"', 'name' => '"a"', ip => '"'.$ip_details[0].'"'),
array('id' => '"2"','name' => '"b"', ip => '"'.$ip_details[1].'"'),
);
$columns = implode(', ', array_keys($values[0]));
foreach($values as $value) {
$value = implode(', ', $value);
$statement = "INSERT INTO `center_listt` (id,name,ip) VALUES ($value)";
$res=mysql_query($statement);
echo "success";
}
}
i need to update each rows of namea and b with new values coming from text-area with previous values.
i am thinking of array_push after fetching ip from table in while loop but could not really do it.warning: array_push expects parameter 1 to be array integer given its because the $row['ip'] fetched in while loop is not valid array which array_push expects.
and it will only add new values in different new rows each time which i don't want.can someone please help what to do.
<?php
if(isset($_POST['submit'])) {
//print_r($ips); die;
$i = 0;
foreach($_POST['ip_details'] as $ipaddr) {
$ips[$i] = $ips[$i].$ipaddr;
$i++;
}
$r = 1;
foreach($ips as $ip){
//echo "UPDATE center_listt SET ipdetails = '$ip' WHERE `id_center` = '$r'"; die;
if(mysql_query("UPDATE center_listt SET ipdetails = '$ip' WHERE `id_center` = '$r'")) echo "IP Address Updated <br />";
else echo 'error occurred';
$r++;
}
}
$sql="select * from center_listt";
$res=mysql_query($sql);
if(!$res) {
die('could not connect'.mysql_error());
}
while($row=mysql_fetch_assoc($res))
{
echo $row['ipdetails']; }
?>
its a bad practise to insert form values from array.you can fetch it from db bcoz if in future you want to add new form values you need to rewrite again with array values while fetching from db will only need you to insert new values in db.
my query will add ip's in your specific column in a single row only updating the ip with new values.
You could do this:
$values = array(...); // WARNING: escape `$ip_details` here!!
$to_insert = array();
foreach($values as $row) {
$to_insert[] = "(".implode(", ",$row).")";
}
$statement = "insert into `center_listt` (`id`, `name`, `ip`)
values ".implode(", ",$to_insert)."
ON DUPLICATE KEY UPDATE `ip`=concat(`ip`,',',values(`ip`))
";
mysql_query($statement);
This will perform a multi-insert (far more efficient than individual queries), and when you try to insert the same ID twice it will instead concatenate the values.
It should be noted that this is bad database design, though :p

(PHP+MySQL) How can I echo the column name on a specific condition?

I am using PHP 5.4 with a MySQL database.
This database represents a media library. The table I'm dealing with has one column, "Title", with obvious contents, and then a series of boolean columns, representing the availability of that title on a given platform. So a row looks like
TITLE: "Curb Your Enthusiasm: The Game"
PS4: 0
Atari 2600: 1
Dreamcast: 0
And so on.
The PHP code I would like to write be, in pseudocode,
Echo row[0] (title)
Cycle through other cells in the row
If the cell is '0' or NULL, do nothing
But if the cell is '1', echo the name of that column
So the result would be the echoing of
Curb Your Enthusiasm: The Game (Atari 2600, WonderSwan, Saturn)
It's the fourth statement that I can't quite work out. It seems to require the function mysqli_fetch_field, but I'm not sure of the syntax, and nothing I try after googling quite works.
I'd really appreciate any advice or examples someone could offer!
$database = mysqli_connect(SERVER,USERNAME,PASSWORD,'games');
$query = mysqli_query($database,"SELECT * FROM games` WHERE NAME LIKE '%ZELDA%'");
while ($row = mysqli_fetch_row($query)) {
echo $row[0]; // Echo title
for ($i=0;$i<sizeof($row);$i++) {
if ($row[$i] === '1') {
// ???????
}
}
}
Here is some rough untested code that should hopefully get you going.
while ($row = mysqli_fetch_assoc($query)) {
$columns = array(); // this will track the additional columns we need to display
foreach($row AS $column => $value) {
if($column == "title") {
echo $value; // this is the title, just spit it out
continue;
}
if($value == 1) {
// We have a column to display!
$columns[] = $column;
}
}
if(count($columns)) {
// We have one or more column names to display
echo " (" . implode(", ",$columns) . ")";
}
}
Some things to point out:
Using mysqli_fetch_assoc will allow you access to column names along with the values, which is useful here.
Keep track of the columns you want to display in an array first, this makes it easier at the end of each loop to format the output.
Sounds like you can do something like this:
// Simulates DB fetch
$titles = array(
array(
'TITLE'=>'Curb Your Enthusiasm: The Game',
'PS4'=>0,
'Atari 2600'=>1,
'Dreamcast'=>0
),
array(
'TITLE'=>'Curb Your Enthusiasm: The Book',
'PS4'=>1,
'Atari 2600'=>1,
'Dreamcast'=>0
)
);
foreach($titles as $title){
// get supported platforms
$supportedPlatforms = array();
foreach($title as $titleAttribute=>$titleValue){
if($titleAttribute != 'TITLE' && $titleValue == 1)
$supportedPlatforms[] = $titleAttribute;
}
echo $title['TITLE'] . ' (' . implode(', ', $supportedPlatforms) . ')' . "<br>";
}
Try running it here: http://phpfiddle.org/lite/code/pr6-fwt

Inserting a variable with multiple values into a mysql database

I thought I would edit my question as by the comment it seems this is a very insecure way of doing what I am trying to acheive.
What I want to do is allow the user to import a .csv file but I want them to be able to set the fields they import.
Is there a way of doing this apart from the way I tried to demonstrate in my original question?
Thank you
Daniel
This problem I am having has been driving me mad for weeks now, everything I try that to me should work fails.
Basically I have a database with a bunch of fields in.
In one of my pages I have the following code
$result = mysql_query("SHOW FIELDS FROM my_database.products");
while ($row = mysql_fetch_array($result)) {
$field = $row['Field'];
if ($field == 'product_id' || $field == 'product_name' || $field == 'product_description' || $field == 'product_slug' || $field == 'product_layout') {
} else {
echo '<label class="label_small">'.$field.'</label>
<input type="text" name="'.$field.'" id="input_text_small" />';
}
}
This then echos a list of fields that have the label of the database fields and also includes the database field in the name of the text box.
I then post the results with the following code
$result = mysql_query("SHOW FIELDS FROM affilifeed_1000.products");
$i = 0;
while ($row = mysql_fetch_array($result)) {
$field = $row['Field'];
if ($field == 'product_name' || $field == 'product_description' || $field == 'product_slug' || $field == 'product_layout') {
} else {
$input_field = $field;
$output_field = mysql_real_escape_string($_POST[''.$field.'']);
}
if ($errorcount == 0) {
$insert = "INSERT INTO my_database.products ($input_field)
VALUES ('$output_field')";
$result_insert = mysql_query($insert) or die ("<br>Error in database<b> ".mysql_error()."</b><br>$result_insert");
}
}
if ($result_insert) {
echo '<div class="notification_success">Well done you have sucessfully created your product, you can view it by clicking here</div>';
} else {
echo '<div class="notification_fail">There was a problem creating your product, please try again later...</div>';
}
It posts sucessfully but the problem is that it creates a new "row" for every insert.
For example in row 1 it will post the first value and then the rest will be empty, in row 2 it will post the second value but the rest will be empty, row 3 the third value and so on...
I have tried many many many things to get this working and have researched the foreach loop which I haven't been familiar with before, binding the variable, imploding, exploding but none of them seem to do the trick.
I can kind of understand why it is doing it as it is wrapped in the while loop but if I put it outside of this it only inserts the last value.
Can anyone shed any light as to why this is happening?
If you need any more info please let me know.
Thank you
Daniel
You're treating each field you're displaying as its own record to be inserted. Since you're trying to create a SINGLE record with MULTIPLE fields, you need to build the query dynamically, e.g.
foreach ($_POST as $key => $value);
$fields[] = mysql_real_escape_string($key);
$values[] = "'" . msyql_real_escape_string($value) . "'";
} // build arrays of the form's field/value pairs
$field_str = implode(',', $fields); // turn those arrays into comma-separated strings
$values_str = implode(',', $values);
$sql = "INSERT INTO yourtable ($field_str) VALUES ($value_str);"
// insert those strings into the query
$result = mysql_query($sql) or die(mysql_error());
which will give you
INSERT INTO youtable (field1, field2, ...) VALUES ('value1', 'value2', ...)
Note that I'm using the mysql library here, but you should avoid it. It's deprecated and obsolete. Consider switching to PDO or mysqli before you build any more code that could be totally useless in short order.
On a security basis, you should not be passing the field values directly through the database. Consider the case where you might be doing a user permissions management system. You probably wouldn't want to expose a "is_superuser" field, but your form would allow anyone to give themselves superuser privileges by hacking up their html form and putting a new field saying is_superuser=yes.
This kind of code is downright dangerous, and you should not be using it in a production system, no matter how much sql injection protect you build into it.
Alright....I can't say that I know exactly whats going on but lets try this...
First off....
$result = mysql_query("SHOW FIELDS FROM my_database.products");
$hideArray = array("product_id","product_name","product_description", "product_slug","product_layout");
while ($row = mysql_fetch_array($result)) {
if (!in_array($row['Field'], $hideArray)){
echo '<label class="label_small">'.$field.'</label>
<input type="text" name="'.$field.'" id="input_text_small" />';
}
}
Now, why you would want to post this data makes not sense to me but I am going to ignore that.....whats really strange is you aren't even using the post data...maybe I'm not getting something....I would recommend using a db wrapper class...that way you can just through the post var into....ie. $db->insert($_POST) ....but if you ware doing it long way...
$fields = "";
$values = "";
$query = "INSERT INTO table ";
foreach ($_POST as $key => $data){
$values .= $data.",";
$fields .= $fields.",";
}
substr($values, 0, -1);
substr($fields, 0, -1);
$query .= "(".$fields.") VALUES (".$values.");";
This is untested....you can also look into http://php.net/manual/en/function.implode.php so you don't have to do the loop.
Basically you don't seem to understand what is going on in your script...if you echo the sql statements and you can a better idea of whats going....learn what is happening with your code and then try to understand what the correct approach is. Don't just copy and paste my code.

Categories