PHP INSERT INTO - Can I use an array to populate field names? - php

What I am wondering is how you can use INSERT INTO if you don't know how many fields there will be in advance. My project involves adding columns if required. Therefore my code will look like this:
$query = "INSERT INTO table (could be any amount) VALUES (could be any amount)";
Is it possible to populate the 'could be any amount' parts from arrays? These could be as follows:
$array1 = (fieldname, fieldname, fieldname);
$array2 = (value, value, value);
Thanks in advance for any help you can give.

$array2 = array_map('mysql_real_escape_string', $array2);
$query = "INSERT INTO table (`".implode("`,`", $array1)."`)"
." VALUES ('".implode("','", $array2)."')";
But You should not use such bad practices.

Related

Pad array values with parentheses to perform insert

I want to have each array value inside a paranthesis
$id = $_POST['id'];
$test2 = array($id);
$id_list = implode(',', $test2);
$sql .= "INSERT INTO tmp (id) VALUES ({$id_list});";
for example: I'm performing an insert so the output of the list should be (5),(10),(15) not '5','10','15'
Any suggestions on how I can insert using an array?
MySQL's extended insert syntax is
INSERT INTO sometable (...fields...) VALUES (value set #1), (value set #2), (value set #3), etc...
Note how each value set is in its own (). You're not doing that. you're just passing a bunch of values in a SINGLE () set, which means you're providing values for fields that are NOT present in the field list.
You need to do
$id_list = '(' . implode('),(', $_POST['id']) . ')';
producing
(5),(10),(15)
instead of
(5, 10, 15)
You also need to realize that you're vulnerable to sql injection attacks.

Syntax of inserting array elements to database with PHP

This isn't anything overly complicated (I assume), I'm just not sure of the syntax for doing what I want. I'm trying to insert a value from an array into the database. Below achieves what I want to do, however I was wondering if it could be reformatted to the code below that.
Current code which does what I want:
$name = explode(" ",$fullName);
$firstName = $name[0];
$lastName = $name[count($name) - 1];
mysql_query("INSERT INTO `person` VALUES(NULL, '$firstName', '$lastName',0)"));
What I want to know is if it can be formatted like this:
$name = explode(" ",$fullName);
mysql_query("INSERT INTO `person` VALUES(NULL, '$name[0]', '$name[count($name) - 1]',0)"));
I tried this earlier a few different ways and got an error, is it just an issue with syntax or is it something a bit deeper?
Oh, and I should add that the only time I actually got the insert to run fully, I ended up with Array[0] and Array[2] - 1 in the first_name and last_name columns respectively.
Thanks all, hopefully I've been clear enough. Need any more info, let me know.
You may try this:
mysql_query("INSERT INTO `person` VALUES(NULL, '$name[0]', '".$name[count($name) - 1]."' ");
Try this:
$name = explode(" ",$fullName);
$query="INSERT INTO person VALUES(NULL,'". $name[0]."','".$name[count($name) - 1]."'";
mysql_query($query);
Try this:
mysql_query("INSERT INTO `person` VALUES(NULL, '{$name[0]}', '{$name[count($name) - 1]}',0)");

PHP - Select & Update statement to return and update a multi dimensional array

I have a database that looks like the following
In my database both id & fb_user_id are unique. Id is an auto incremented number.
First i would like to insert a new row for arguments say with the following
$new_first_name = "John";
$new_last_name = "Nolan";
$new_email = "John#Nolan.com";
$new_link_url = "Johns_Link";
$new_signups = 0;
$new_order = $num_rows;
$referred_by = 2;
$new_fb_user_id = 4;
I use this insert statement
$New_Member = mysql_query("INSERT INTO `rotator`.`rotator` (`id`, `fb_user_id`, `first_name`, `last_name`, `email`, `link_url`, `referred_by`, `signups`, `order`) VALUES (NULL, '$new_fb_user_id', '$new_first_name', '$new_last_name', '$new_email', '$new_link_url', '$referred_by', '$new_signups', '$new_order');");
And because the person was referred by fb_user_id number 2 i want to update signups as follows
$update_sponsor_order = mysql_query("UPDATE `rotator`.`signups` = `rotator`.`signups` + 1 WHERE `rotator`.`fb_user_id` = $referred_by;");
This is where i am stuck. Maybe there is a better way to do it than inserting and updating the table as abovee.
What i would like to do now is something like the following select statement but assigning the returned values to a multi dimensional array. Basically i return columns fb_user_id and order where signups is less than 2
$get_link = mysql_query("SELECT `rotator`.`fb_user_id`, `rotator`.`order` FROM `rotator`.`rotator` WHERE `rotator`.`signups` < 2);
Now with my array i want to rotate everything that is in the column order and update the database of what entry is next in line....
Check the following question and replys to see what i am trying to do
Original Question
You're new best friend the pdo class. I know this doesn't exactly answer your question, but if you start using it now, you will thank me later.
Overview here http://www.php.net/manual/en/class.pdostatement.php
And to retreive results: http://php.net/manual/en/pdostatement.fetch.php

MYSQL - INSERT INTO from left

First of all thanks for your help, I'm asking how can I insert data into fields starting from the left? Depending on the entity sometimes several fields at the end are left blank but I need to insert the filled fields into the table. If I try to do this, I obviously get a column-values mismatch error.
Thanks!
The column count you use and the number of values you try to insert have to match. You can specify what you want to insert, so you don't have to pass the columns which aren't needed (and so you don't need to pass "blanks").
INSERT INTO Store_Information (store_name, Sales, Date)
VALUES ('Los Angeles', 900, 'Jan-10-1999')
More information:
http://www.1keydata.com/sql/sqlinsert.html
Just specify only fields names you gonna insert at the moment:
INSERT INTO table (field1, field2, field3) VALUES (value1, value2, value3)
or this way
INSERT INTO table SET field1=value1, field2=value2, field3=value3
no matter is it from left, right or checkered
as SQL query is just a string, you could use some PHP code to build this string in the way you want.
hereis an example code in the form of very simple helper function to produce SET statement dynamically:
function dbSet($fields) {
$set='';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
return substr($set, 0, -2);
}
it can be controlled by $fields array.
used like this
//if we have full set of data
$fields = explode(" ","name surname lastname address zip fax phone");
$query = "INSERT INTO $table SET ".dbSet($fields);
//if we have only three fields ready
$fields = explode(" ","name surname lastname");
$query = "INSERT INTO $table SET ".dbSet($fields);
but you desperately need to learn basic PHP string operations to be able to do such things yourself.
string operations are most important in PHP, as almost every task for PHP is just string manipulation like in your case.
Use querys like
insert into table set col1=val1, col2=val2;
or
insert into table(col1, col2) values(val1, val2);
That is the only way around it. I think method 2 is the most commonly used.
If there is any way you can supply default values for each column use them for the columns you don't have values for.
if all the data can be "NULL", you can setup your query with variables that, if not set, are NULL, example:
$col1 = null;
$col2 = null;
$col3 = null;
$col4 = null;
$col5 = null;
then populate the columns you need
$col1 = 'val1';
$col2 = 'val2';
$query = "INSERT INTO (col1, col2, col3, col4, col5) VALUES ($col1, $col2, $col3, $col4)";
Sincerely I'll never use something like this... but you asked for it...
mysql_query("INSERT INTO People (First_Name, Last_Name, Age)
VALUES ('Marcus', 'Porter', '28')");
mysql_query("INSERT INTO People (First_Name, Last_Name, Email)
VALUES ('Marcin', 'Kruk', 'marcin.kruk#gmail.com')");

how to add multiple records in mysql using php

how to add multiple records in mysql using php. Is using array the only solution to this problem. Because I tried using array but the record that would be added in the database would look like this:
array
You can use a multivalue insert statement (INSERT... VALUES (record1), (record2) etc)
(see http://dev.mysql.com/doc/refman/5.1/en/insert.html)
This is how you can construct such a statement from array of records
$values = array();
foreach($records_array as $record)
$values[] = sprintf("( '%s' , '%s' )", addslashes($record['name']), addslashes($record['email']));
$sql = "INSERT INTO users(name, email) VALUES " . implode(",", $values);
mysql_query($sql);
You need to go through each member of the array:
foreach($array as $record)
{ ... }
and perform an INSERT query for each member or - better for performance - insert all records in one statement as outlined in user187291's answer.

Categories