How to make efficient INSERT query in php - php

I am using php to insert element values of a form in MYSQL. My form contains 20 different elements, that means
count($_POST)
returns 20. How can I make an INSERT query efficiently in PHP.

I will extract 20 values one by one then concatenate them again one by
one. I do not want to follow this method. Do you have some better
method?
Yes, you can use foreach. Example below assumes 3 thigs:
all of your form fields are text fields,
form fields are in the same order as columns in your table
form elements (<input>) have the same name attribute as columns names in your table
It can go like this:
$sql = 'INSERT INTO table_name VALUES (';
foreach ($_POST as $key => $value)
$sql .= mysqli_real_escape_string($value);
$sql .= ')';

Related

MySQL - Insert intro if exist update

I have unknown keys and values to import to database from CSV.
My code is
while($data = fgetcsv($handle,1000,",",'"'))
{
$data=array_map('addslashes',$data); // apply addslashes() to all values
$data=array_combine($csv_fields,$data); // csv fields assoc (key=>value)
$data=array_intersect_key($data,$tbl_fields); // discard redundant
$tbl_fields_str=implode("`,`",array_keys($data));
$tbl_vals_str=implode("','",array_values($data));
$q="INSERT INTO `cmid` (`cmid`,`$tbl_fields_str`) VALUES ('$cmidtrenutni','$tbl_vals_str') ON DUPLICATE KEY UPDATE (`$tbl_fields_str`) VALUES ('$tbl_vals_str')";
$conn->query($q);
}
I need to insert and if exist, update.
I try this code above but doesnt work.
I find something like http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html
But this doesnt help in my way cause my table doesnt have defined fields. Keys and values are different on every input.
Any solution how to do this?
This is your query:
INSERT INTO `cmid` (`cmid`, `$tbl_fields_str`)
VALUES ('$cmidtrenutni', '$tbl_vals_str')
ON DUPLICATE KEY UPDATE (`$tbl_fields_str`) VALUES ('$tbl_vals_str');
The problem is the UPDATE part. You need to split the values so it looks like:
INSERT INTO `cmid` (`cmid`, `$tbl_fields_str`)
VALUES ('$cmidtrenutni', '$tbl_vals_str')
ON DUPLICATE KEY UPDATE
col1 = newcol1val,
col2 = newcol2val,
. . .
The short-hand that you are using is not valid syntax.
To import from a csv file, take a look at the LOAD DATA INFILE statement or the mysqlimport utility.
Try this one:
$q="INSERT INTO `cmid` (`cmid`,`$tbl_fields_str`) VALUES ('$cmidtrenutni','$tbl_vals_str') ON DUPLICATE KEY UPDATE cmid=cmid";
But I prefer using INSERT IGNORE for your problem:
$q="INSERT IGNORE INTO `cmid` (`cmid`,`$tbl_fields_str`) VALUES ('$cmidtrenutni','$tbl_vals_str')";
You cannot have "unknown" columns in mysql DB. if you want to store pairs of key-value in a mysql table, you should have a table with two columns : one would be named "key" and the other one "value". Add an extra column "cmid" to group your pairs.
This table should have a primary index on "cmid" and "key" columns.
Then you should insert values with a query like:
$sqlVals = "";
foreach ($data as $key => $val) {
$sqlVals .= "($cmidtrenutni, $key, $val),";
}
$sqlVals = substr($sqlVals, 0, -1); //remove last comma.
$query = "REPLACE INTO `myTable` (`cmid`, `key`,`value`) VALUES $sqlVals";

PDO json insert multiple tags

I've been trying to insert some tags into a table using pdo but to no avail.
I have a php array called Tag.
Sample data in tag array is as follows
tag[] = [[a,b,c,d,e],[f,g,h,i,j]]
using a for loop below I'm able to convert it to (1,'a','b','c','e',0), (1,'f','g','h','i',0)
$value="";
$value .= "($postid,";
for($i=0;$i<sizeof($tag);$i++)
{
$value .="'$tag[$i]'";
if($i + 1 == $sizeof($tag){
$value .=")";
}else{
$value .="),";
}
}
And prepare and insert into the table as follows
$inserttagquery = "insert Into tagtable ( postid, desc, b, u, toppos,leftpos ,ver) values :value";
$queryinserttag = $conn->prepare($inserttagquery);
$queryinserttag->execute(array('value'=>$value));
$insertedtag = $queryinserttag->rowCount();
However, this does not seem to work. $insertedtag does not return any value.
Your SQL is outright wrong. You're lising 6 fields AND a constant value in your field list, then providing only a SINGLE placeholder to provide values for those fields.
you cannot use numbers as a field name. 0 is a flat out syntax error and an invalid field name.
Placeholders have a 1:1 relation between a field and a value. You CANNOT shove multiple values into a single variable and try to use that value with a placeholder to fill in OTHER fields.
Your query should be:
INSERT INTO tagtable (postid, desc, b, u, etc...)
VALUES (:postid, :desc, :b, :u, etc...)
and then you provide INDIVIDUAL values for each placehodler:
$stmt->execute(array($postid, $desc, $b, $u, etc...));
As written, and ignoring all the other problems, your query would try shove your (1, 'f', 'g', etc..) string into JUST the postid field.

On duplicate key update all new data PHP MySQL

I have a 2 part html / php form, and one of the $_POST values is the session_id(); m which will be the unique ID in the database table.
On the first part of the form, the user eneters their contact information and it is inserted into a MySQL database.
INSERT INTO $table ($columns) VALUES ($values)
On the 2nd part of the form where they enter extra information, if the session_id() is the same, I just want to update all the columns that are being submitted, which will always be different from the columns in the first part of the form. How do I just update all columns being submitted while leaving previously submitted data intact.
In this example, $columns and $values are CSV string, i.e.
Submission 1
$columns = "'SSID', 'Name', 'Email'";
$values = "'65464s4468fff9864wef68d', 'John Doe', 'someone#something.com'";
Submission 2
$columns = "'SSID', 'Product', 'Comments'";
$Values = "'65464s4468fff9864wef68d', 'Apple', 'some comments'";
So I would just need to update the columns 'Product' and 'Comments'. I need to do this dynamically with many different forms so I would rather not have to specify which columns to update since they are already the only ones being inserted.
I'm attempting something like:
INSERT INTO $table ($columns) VALUES ($values) ON DUPLICATE KEY UPDATE $columns = $columns
What would be the proper syntax? Currently this gives me a syntax error
Edit: Added last line
You could also do:
REPLACE INTO $table ($columns) VALUES ($values);

Using arrays and loops with SELECT AS syntax in SQL

I am generating a table in HTML from a MySQL database, so that stored data can be displayed on a web page, and ultimately downloaded as a spread sheet.
I have a large set of SQL headers (probably the wrong name for this), that is to say the 'Title' of any given column.
I am using SELECT to get the data from MySQL via PDO:
$sql ="
SELECT
`sv_20` AS `Name`,
`sv_21` AS `Age`,
`sv_22` AS `Height`,
`sv_23` AS `Weight`,
...
...
`sv_999` AS `Something`
FROM
database.table";
In PHP I would define two arrays (the database headers and the titles I'd like them to have) and then write a foreach loop saying:
foreach(array_combine($headers, $titles) as $header => $title)
{
echo "`$header` AS `$title`,";
}
Which would give me the complete set of calls, is there a way to do this in SQL when querying a database? Thank you
It's basic string manipulation, instead of echo, you want to append this to the string with $sql .=
You'll have some problems with the extra comma after the last item, it's better to
$sql = array();
foreach(....)
$sql[] = "`$header` AS `$title`";
and then do a join(',', $sql);

How do i insert arrays into mysql using PHP?

I have a complex form that has 11 columns. As for rows they will vary from about 20 to 50 depending on number of students. I am capturing data via a php script as arrays. Each column produces an array. Example, from the form I have fname[], lname[], exam_no[] etc so when the form is submitted with say, 10 rows, I end up with 11 arrays each with 10 entries, which I pass through some php function to remove empty elements. The arrays are being generated with no issues.
I want to insert data from these arrays into mysql using a loop. Basically, lname array will have all first_name for the first name column, lname array will feed the last_name column of the db and so on.
I am just unable to even start constructing the MySQL query to insert the data, I am well conversant with the 'ordinary' insert where you have columns and values and you already know how many rows will insert, mostly one row per insert.
Is is even possible to populate a MySQL Database Table with an insert using a PHP loop and with this many number of columns and making it flexible to insert any number of rows as that will vary each time a user enters student data?
UPDATE
This is what I came up with. It works but NOT as desired!
Arrays are coming like $fname[], lname[] etc
Then I built the master array to be $master_array=array['$fname, $lname];
$sql = "INSERT INTO testing (date, fname, lname) VALUES ";
foreach($master_array as $subarray) {
$sql .= "(NOW( )";
echo 'A nested array: '.$subarray.'<br />';
foreach($subarray as $value) {
$sql .= ", '$value'";
echo 'A Name: '.$value.'<br />';
}
$sql.= "), ";
}
$sql = substr($sql,0,-2); //removes extraneous , at end.
echo $sql;
$result=mysqli_query($dbc, $sql)
or die('Query Failed!');
?>
Since my query involves conactinating small pieces of code, I was printing it after its built to see what is to be inserted. It looked like so;
INSERT INTO table (date, fname, lname) VALUES (NOW( ), 'Andrew', 'Alex'), (NOW( ), 'Peterson', 'Marlon')
As I suspected, it inserts all first names in the first row, and all last names in the second row. The desired result is to insert first names in the first-name column and second names in the second name column. So now I need a way to insert all elements of one array into a single column and then move to the second array and insert it in the next column. That sounds complex, and I wonder if it's doable! Let me be educated by the masters of the php language as I am an intermediate or may be brand new newbie!
Isn't it better to group the information by student?
Example:
<form...>
<? foreach ($students as $id => $info) : ?>
<input type="text" name="fname;<=$id;?>" value="<?=$info['fname'];?>" />
<input type="text" name="lname;<=$id;?>" value="<?=$info['lname'];?>" />
etc
<? endforeach ?>
</form>
(I'm using PHP short tags here)
Then, when you process the form:
$update = array();
foreach ($_POST as $key => $value) {
// key will look like: fname;1, fname;2, etc
// so, split it on the ; sign to separate the field name from the student's id
$data = explode(';',$key);
// result:
// $data[0] = fname, lname, etc
// $data[1] = 1, 2, etc
// you can add some checks to make sure that this field is valid
// and that the id is in fact a valid id (number, > 0, etc)
// sanitize data (however you want, just an example)
$value = mysql_real_escape_string(trim($value));
// now add it to the update array, grouped by student id
$update[$data[1]][$data[0]] = $value;
// result:
// $update[1]['fname'] = 'First name student 1';
// $update[1]['lname'] = 'Last name student 1';
// $update[2]['fname'] = 'First name student 2';
// $update[2]['lname'] = 'Last name student 2';
// etc
}
After that, go through the update array:
foreach ($update as $id => $info) {
$sql = "UPDATE students
SET fname = '".$info['fname']."', lname = '".$info['lname']."'
WHERE id = $id";
mysql_query($sql);
}

Categories