I am still learning PHP and MYSQL and trying to make a program to list all tables and data in database (that's done), edit selected row (that's done) and now add new record on selected table. Now the problem is with variable number of fields. Table could be with 3 fields, could be 4 and so on. On my code here $getValue is an array. I am printing it out only for testing. It could look like "Array ( [name] => Tomas [lastName] => Timas )" or "Array ( [stufName] => Phone [stufPrice] => 58 [comments] => My new phone )"
$getTable returns name of a table to insert into.
This has to be a new record on the table, so stufID or nameID or what ever ID will be NULL
How do I use "INSERT INTO table VALUES (value1, value2, value3,...)" if I do not know the number of values?
<?php
include "conf.ini"; //connection to the db
$getValue=$_REQUEST['value'];
$getTable=$_REQUEST['table'];
// test********************
print_r($getValue);
print '<br>';
print $getTable;
// test********************
if (!$_POST['submit']) {
print 'Please input data';
} else {
mysql_query ("INSERT INTO $getTable VALUES (?????)");
}
?>
I hope you know this is very dangerous, so do this only if you're sure there are no potentional attackers!
$all_keys = array_keys($getValue);
$getValue = array_map('mysql_real_Escape_string', $getValues);
mysql_query ("INSERT INTO $getTable (`".implode('`,`', $all_keys)."`) VALUES ('".(implode(",", $getValue))."')");
$values = array_map('mysql_real_escape_string', array_values($getValue));
$keys = array_keys($getValue);
mysql_query("INSERT INTO $getTable (".implode(',', $keys).") VALUES ('".implode('\',\'', $values)."')");
Perhaps you should create an include file to execute the values for $gettables and then it include that where you want $gettables values to be picked up.
Related
I have 17 columns in my DB
I'm inserting values from different sources. Somewhere I haven't, for example, company/company_info values (I'm setting in PHP FALSE values for relevant variables).
So, I need some kind of PHP INSERT query to insert only not empty variables and columns of certain list.
For example, I could do:
$q = "INSERT INTO `$tname` (`phone`,`location`, `pagelang`, `company`, `company_url`, `phone_no_cc`, `phone_type`, `operator`, `pageviews`, `rating`, `comments_number`, `activity_by_days`, `activity_by_hours`) VALUES (
'$main_number', '$number_advanced_info[location]', '$pagelang', '$company[name]', '$company[site]', '$number_advanced_info[number_no_countrycode]', '$number_advanced_info[phone_type]', '$number_advanced_info[operator]', '$searches_comments[searches]', '$rating', '$searches_comments[comments]', '$history_search', '$daily_history'
);";
With insert of 14 columns and their values.
But sometimes I need to insert less columns/values and let MYSQL set default values for not listed columns. For Example, I want to insert only 5 columns.
$q = "INSERT INTO `$tname` (`phone`,`location`, `pageviews`, `rating`) VALUES (
'$main_number', '$number_advanced_info[location]', '$searches_comments[searches]', '$rating'
);";
Is there some CLASS or any solution like binding values which will automatically build query depending which values are not NULL?
I need some kind of code:
if (!$phone) {
$columns .= "`column_name`," ;
$values .= "value";
}
I am currently new to programming over all and I have all sorts of questions when it comes to PHP, but my first question is how to add multiple data to a table only using one variable. For example:
<?php
$mysqli = mysqli_connect('localhost', 'root', 'testpass', 'testdatabase')
or die (mysqli_error());
$test = "INSERT INTO test (test1, test2) VALUES ('test1', 'test2')";
$test .= "INSERT INTO test (test1, test2) VALUES ('test3', 'test4')";
if (!$test){
echo "Sorry but you information could not be added...";
}
else {
$test_result = mysqli_query($mysqli, $test);
echo "Your data has been entered!";
}
When I use this code when trying to add multiple data into my table it doesn't work. I can only add in 1 row at a time. I can never add in 2, 3, or more rows in at a time. Is there an error in my code? When I look at other example, people user mysql and not mysqli. The people using mysql use that same code as I have above. I prefer using mysqli and not having to switch because of something that is so small. Back to my question, how do I add multiple rows of data into a table? Thanks!
To insert multiple rows use this:
INSERT INTO test (test1, test2) VALUES ('test1', 'test2'), ('test3', 'test4'), ('test5', 'test6')
which would insert 3 rows.
I am trying to write a query to insert an array of many values (say 1000) in a effective way using 'implode'. Here is the code.
$sql = array();
foreach( $return as $key=>$row ) {
$sql[] = '("'.mysql_real_escape_string($row['fullname']).'", '.$row['age'].','.$row['since'].','.'"'.mysql_real_escape_string($row['description']).'")';
}
mysql_query('INSERT INTO data (name, age, since, description) VALUES '.implode(',', $sql));
My query inserts the record array into the data table. I want to change the query so that it will update the record if it exists, and otherwise it will insert the record.
What you probably want is a version of the "ON DUPLICATE KEY" that actually allows you to reference the data being input.
INSERT INTO data (name, age, since, description) VALUES
("Bob", 23, "01-01-1980", "friend"),
("Bill", 33, "03-01-1980", "tall"),
("Jane", 43, "12-01-1980", "thin")
ON DUPLICATE KEY UPDATE age=VALUES(age),
since=VALUES(since),
description=VALUES(description);
Hopefully self-explanatory when you read it?
$sql = array();
foreach( $return as $key=>$row ) {
$sql[] = '("'.mysql_real_escape_string($row['fullname']).'", '.$row['age'].','.$row['since'].','.'"'.mysql_real_escape_string($row['description']).'")';
}
mysql_query('INSERT INTO data (name, age, since, description) VALUES '.implode(',', $sql). ' ON DUPLICATE KEY UPDATE age=VALUES(age), since=VALUES(since), description=VALUES(description);');
Edit, adding this into the user's code above.
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);
}
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')");