This is code for insert dynamic data to mysql database.
$name = $_POST['name'];
for ($i = 0; $i < count($name); $i++) {
if ($name[$i] != "") {
$test= implode(", ", (array)$name[$i]);
print_r($test);
$sql = "INSERT INTO employee_table (name)
VALUES ('$test')";
if ($conn->query($sql) === true) {
echo ('ok');
}
}
}
$conn->close();
I used implode(", ", (array)$name[$i]) to returns a string from $name by comma but when print_r($test); like this:
AlexBrownHelloHugo
I got 2 problems and hope your help:
Result when print_r($test); is Alex,Brown,Hello,Hugo
Store $test [Alex,Brown,Hello,Hugo] same row into dabase.
Thanks all.
Something like this:
$names = empty($_POST['name']) ? [] : $_POST['name'];
foreach($names AS $name){
if (!empty($name)) {
$test= '['.implode(", ", (array)$name).']';
print_r($test);
$sql = "INSERT INTO employee_table (name)
VALUES ('$test')";
if ($conn->query($sql) === true) {
echo ('ok');
}
}
}
I wanted to repost this comment I made:
its a bad idea to store data as a delimited list when you can make it a related table. In any case I would save it as this ,Alex,Brown,Hello,Hugo, with leading and trailing delimiters, that way when you query it you can do this field LIKE '%,Alex,%'. The difference is if you have foo,some,bar and foo,something,bar and you do field LIKE '%some%' note no , you will find both of those some and something. To query the first and last items like I showed above with , they would need the , around them. You can just use trim($field, ',') to remove them before explode etc
UPDATE
And this one
its unclear the structure of $name is it implode($name[$i]) or impode($name) You use the first one in your code which implies name is [['foo','bar'], [...]] not ['foo','bar', ...] If it's the second your also storing it multiple times which you probably don't want.
So you may be able to do just this:
//$_POST['name'] = ['foo','bar', ...]
//remove the loop
//we can assign $name in the if condition and save a line or 2
//the second part, the assignment, will always return true.
if (!empty($_POST['name']) && $name = $_POST['name']) {
$test= '['.implode(',', (array)$name).']'; //changed mainly this line
print_r($test);
$sql = "INSERT INTO employee_table (name) VALUES ('$test')";
if ($conn->query($sql) === true) {
echo 'ok';
}
}
With no loop, because when you loop over the count of names, your inserting the same data each time, up to the number of items in the names variable.
Explaining your code
So with my example data $_POST['name'] = ['foo','bar', ...] and a simplified version of your original code, you would be doing this:
Assuming you meant implode($name) and not implode($name[$i]) in your original code, which is the only sane thing if your data looks like my example data
//canned example data
$name = ['foo','bar'];
for ($i = 0; $i < count($name); $i++) {
if ($name[$i] != "") {
$test= implode(", ", (array)$name); //changed from $name[$i]
//just output this stuff so we can see the results
print_r($test);
echo "\nINSERT INTO employee_table (name) VALUES ('$test')\n";
}
}
Outputs:
foo, bar
INSERT INTO employee_table (name) VALUES ('foo, bar')
foo, bar
INSERT INTO employee_table (name) VALUES ('foo, bar')
Sandbox
If should be obvious but if you changed this line $test= implode(", ", (array)$name); to $test= '['.implode(',', (array)$name).']; in the above code the output would be this:
foo, bar
INSERT INTO employee_table (name) VALUES ('[foo,bar]')
foo, bar
INSERT INTO employee_table (name) VALUES ('[foo,bar]')
Which still saves it more then one time. So we need to dump that loop, which basically forces us into the code I put at the top of this update.
Hopefully that all makes sense.
Cheers
Try this code, in fact your $_POST['name'] store your value as an array, so you don't need to cast it.
$name = $_POST['name'];
for ($i = 0; $i < count($name); $i++) {
if ($name[$i] != "") {
$test= '['.implode(', ', $_POST['name']).']';
print_r($test);
$sql = "INSERT INTO employee_table (name)
VALUES ('$test')";
if ($conn->query($sql) === true) {
echo ('ok');
}
}
}
$conn->close();
$emapData[3] is row 4 input data in the excel, how would I match $emapData[3] to $categories which is an array. Like if $emapData[3](row 4 excel input , so if user puts AMT 1) is == AMT 1 which exist in $categories array it will insert 5801D447D5583 to the Database which is the value of AMT 1. Also whatever input from the user it will match to categories array it exists. I have tried below.
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
$count = 0;
$stud_id = strtoupper(uniqid());
$categories=array("5801D447D5583" => "AMT 1","5801D447D5583" => "AMT 2","5801D457CAF7F" => "AMT 3");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$count++;
$stud_id = strtoupper(uniqid());
$added_by = $_SESSION['userid'];
if($count > 1) {
echo $count;
$sql = "INSERT into students(stud_id ,stud_no , first_name , last_name, date_added ,added_by) values ('$stud_id','$emapData[0]','$emapData[1]', '$emapData[2]' ,NOW(), '$added_by')";
$emapData[3] = $categories['AMT 1'];
$sql1 = "INSERT into categories(student_id ,category_id ) values ('$stud_id','$emapData[3]')";
mysql_query($sql);
}
I would use array search
http://php.net/manual/en/function.array-search.php
array_search — Searches the array for a given value and returns the first corresponding key if successful
So something like
$value = array_search('AMT 1', $categories);
Outputs:
5801D447D5583
So as you said all this
$emapData[3] is row 4 input data in the excel , how would I match $emapData[3] to $categories which is an array. Like if $emapData[3](row 4 excel input , so if user puts AMT 1) is == AMT 1
you would put something like array_search($emapData[3], $categories);
But I would check if it's found by doing
if( $value !== false)
Note- you need to use !== that checks the type as array search can return index 0 in some cases which is false in PHP. IN your particular case you don't have index 0 but it's good practice anyway. If you read the PHP documentation, specifically this warning.
Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
That is what it is saying.
Cheers.
UPDATE
This line in your code
$emapData[3] = $categories['AMT 1'];
I would replace with at least
$emapData[3] = array_search($emapData[3], $categories);
if(false !== $emapData[3]){
//insert
}else{
//do something else?
}
However there is a lot of other "Stuff" such as using mysql_ family of functions which are removed in PHP7, as well as directly inserting data into your query, which is a security issue, even from a file. It's called SQL Injection.
Personally I wouldn't overwrite $emapData[3] and instead use a separate variable, but I think that is the least of your worries at this point.
But those things are beyond the scope of this question, however I do strongly suggest using something like PDO and prepared statements instead.
UPDATE1
This bit of code
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
///..other code
if($count > 1) { //missing closing }
echo $count;
$sql = "INSERT into students(stud_id ,stud_no , first_name , last_name, date_added ,added_by) values ('$stud_id','$emapData[0]','$emapData[1]', '$emapData[2]' ,NOW(), '$added_by')";
$emapData[3] = $categories['AMT 1'];
$sql1 = "INSERT into categories(student_id ,category_id ) values ('$stud_id','$emapData[3]')";
mysql_query($sql);
} //end while
You'll note besides missing the ending } which I pointed out in comments, you never call mysql_query($sql1); so this second insert is never executed.
Ok... So the simple fix is to just add that in like this:
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
///..other code
if($count > 1) { //missing closing }
echo $count;
$sql = "INSERT into students(stud_id ,stud_no , first_name , last_name, date_added ,added_by) values ('$stud_id','$emapData[0]','$emapData[1]', '$emapData[2]' ,NOW(), '$added_by')";
mysql_query($sql);
$emapData[3] = $categories['AMT 1'];
$sql1 = "INSERT into categories(student_id ,category_id ) values ('$stud_id','$emapData[3]')";
mysql_query($sql1);
} //end while
You'll notice I moved the first one mysql_query($sql); which is simply for readability sake, you create a query and execute it. So it reads better to create 1 query execute it, then create a second query and execute that, the two things are separate operations independent of one another.
The last bit is I don't know exactly how you dealt with the original issue, but putting that all together should be something like:
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
///..other code
if($count > 1) {
echo $count;
$emapData[3] = array_search($emapData[3], $categories);
if(false !== $emapData[3]){
$sql = "INSERT into students(stud_id ,stud_no , first_name , last_name, date_added ,added_by) values ('$stud_id','$emapData[0]','$emapData[1]', '$emapData[2]' ,NOW(), '$added_by')";
mysql_query($sql);
$emapData[3] = $categories['AMT 1'];
$sql1 = "INSERT into categories(student_id ,category_id ) values ('$stud_id','$emapData[3]')";
mysql_query($sql1);
}else{
/*
do something else?
It's a question as I have no way to know the importance of
the array search to the insert, maybe it's ok if it's null.
maybe that is an error that ruins one or both inserts?
So without knowing that, I have no idea on the exact
implementation of non-matching states.
*/
}
}//end if $count
} //end while
UPDATE----
Afer using this method:
foreach($_POST as $k => $v) {
$params[] = empty($v)? "NULL":$v;
}
$params_string_values = "'" . implode("','",$params) . "'";
$param_name_list = "tu_id,tu_status,tu_name,tu_fk_tt_id,tu_mon_1_s,tu_mon_1_e,tu_mon_2_s,tu_mon_2_e,tu_mon_3_s,tu_mon_3_e,tu_tue_1_s,tu_tue_1_e,tu_tue_2_s,tu_tue_2_e,tu_tue_3_s,tu_tue_3_e,tu_wed_1_s,tu_wed_1_e,tu_wed_2_s,tu_wed_2_e,tu_wed_3_s,tu_wed_3_e,tu_thu_1_s,tu_thu_1_e,tu_thu_2_s,tu_thu_2_e,tu_thu_3_s,tu_thu_3_e,tu_fri_1_s,tu_fri_1_e,tu_fri_2_s,tu_fri_2_e,tu_fri_3_s,tu_fri_3_e,tu_sat_1_s,tu_sat_1_e,tu_sat_2_s,tu_sat_2_e,tu_sat_3_s,tu_sat_3_e,tu_sun_1_s,tu_sun_1_e,tu_sun_2_s,tu_sun_2_e,tu_sun_3_s,tu_sun_3_e";
$param_values = "'','1',{$params_string_values}";
$insert_query = mysql_query("INSERT into turn_conf( {$param_name_list} ) values ({$param_values})");
It creates a valid query as it seems (here I paste it), but no NULL value is stored on databse, all NULL values go to database as "00:00":
INSERT into turn_conf( tu_id,tu_status,tu_name,tu_fk_tt_id,tu_mon_1_s,tu_mon_1_e,tu_mon_2_s,tu_mon_2_e,tu_mon_3_s,tu_mon_3_e,tu_tue_1_s,tu_tue_1_e,tu_tue_2_s,tu_tue_2_e,tu_tue_3_s,tu_tue_3_e,tu_wed_1_s,tu_wed_1_e,tu_wed_2_s,tu_wed_2_e,tu_wed_3_s,tu_wed_3_e,tu_thu_1_s,tu_thu_1_e,tu_thu_2_s,tu_thu_2_e,tu_thu_3_s,tu_thu_3_e,tu_fri_1_s,tu_fri_1_e,tu_fri_2_s,tu_fri_2_e,tu_fri_3_s,tu_fri_3_e,tu_sat_1_s,tu_sat_1_e,tu_sat_2_s,tu_sat_2_e,tu_sat_3_s,tu_sat_3_e,tu_sun_1_s,tu_sun_1_e,tu_sun_2_s,tu_sun_2_e,tu_sun_3_s,tu_sun_3_e ) values ('','1','12345555','1','10:00','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL')
This is what it records on DB:
I have this query, in which sometimes variables '$va1', '$val2' and '$val3' will have no value:
$insert = mysql_query("INSERT INTO turn_conf (tu_id,value1,value2,value3) VALUES ('','$va1','$val2','$val3')") or die (mysql_error());
In case any of these variables have no value stored, anything related to it must be sent to the DB (in order to store a NULL value on DB), for exampe if only '$val1' stores info, the final query must be:
$insert = mysql_query("INSERT INTO turn_conf (tu_id,value1) VALUES ('','$va1')") or die (mysql_error());
To solve this I have created an structure for each variable, checking wether it stores something or not, and in case it doesn't, just declarating nothing and sending nothing:
if ($_POST['value1'] == ""){
$val1_p = "";
$val1_s = "";
}else {
$val1_p = ",value1";
$val1_sv = $_POST['value1'];
$val1_s = ", '$val1_sv'" ;}
if ($_POST['value2'] == ""){
$val2_p = "";
$val2_s = "";
}else {
$val2_p = ",value2";
$val2_sv = $_POST['value2'];
$val2_s = ", '$val2_sv'" ;}
if ($_POST['value3'] == ""){
$val3_p = "";
$val3_s = "";
}else {
$val3_p = ",value3";
$val3_sv = $_POST['value3'];
$val3_s = ", '$val3_sv'" ;}
and:
$insert = mysql_query("INSERT INTO turn_conf (tu_id $val1_p $val2_p $val3_p) VALUES ('' $val1_s $val2_s $val3_s)") or die (mysql_error());
This works, and creates the right query, but id like to know if you find ths method proper, or if it would be better to choose another more efficient one. Please not in this example I used only 3 variables, but this query on real has 43 variables, I make this question due to the amount of data.
$insert = mysql_query("INSERT INTO turn_conf (tu_id,value1,value2,value3) VALUES ('','".((isset($va1))?"'".$va1."'":"NULL")."','".((isset($va2))?"'".$va2."'":"NULL")."','".((isset($va3))?"'".$va3."'":"NULL")."')") or die (mysql_error());
Basically you want to test if the value is set. We use the short if-notation for this:
isset($va1)?"'".$va1."'":"NULL"
If $va1 is set (has a value), we will put "'value'" in the query, otherwise "NULL" for an empty value.
If you want to test on an empty string too:
(isset($va1) && $va1 != '')?"'".$va1."'":"NULL"
If you don't use prepared statement Try this:
foreach($_POST as $k => $v) {
$params[] = empty($v)? "NULL":$v;
}
mysql_query("insert into turn_conf(field1,field2...) values(" . implode(",",$params). ");
If you use prepared statement (better!) try something like this:
foreach($_POST as $v) {
$params[] = $v;
}
$sth = $dbh->prepare("INSERT INTO turn_conf (tu_id $val1_p $val2_p $val3_p) VALUES (?,?,?)");
$sth->execute($params);
So simple!
PS: This is an example but doesn't use directly $_POST value, filter it before (http://www.php.net/manual/en/function.filter-input.php, and http://www.php.net/manual/en/filter.filters.sanitize.php). example:
$field_int= filter_input(INPUT_POST, 'field1', FILTER_SANITIZE_NUMBER_INT);
UPDATE
you use this code:
$insert = mysql_query("INSERT into turn_conf(tu_id,tu_name,tu_status,tu_fk_tt_id,tu_mon_1_s,tu_mon_1_e,tu_mon_2_s,tu_mon_2_e,tu_mon_3_s,tu_mon_3_e,tu_tue_1_s,tu_tue_1_e,tu_tue_2_s,tu_tue_2_e,tu_tue_3_s,tu_tue_3_e,tu_wed_1_s,tu_wed_1_e,tu_wed_2_s,tu_wed_2_e,tu_wed_3_s,tu_wed_3_e,tu_thu_1_s,tu_thu_1_e,tu_thu_2_s,tu_thu_2_e,tu_thu_3_s,tu_thu_3_e,tu_fri_1_s,tu_fri_1_e,tu_fri_2_s,tu_fri_2_e,tu_fri_3_s,tu_fri_3_e,tu_sat_1_s,tu_sat_1_e,tu_sat_2_s,tu_sat_2_e,tu_sat_3_s,tu_sat_3_e,tu_sun_1_s) values('','$newTurnName','1','$newTurnType'," . implode(",",$params). "))")
but change it like this:
$params_string_values = "'" . implode("','",$params) . "'";
$param_name_list = "tu_id,tu_name,tu_status,tu_fk_tt_id,tu_mon_1_s,tu_mon_1_e,tu_mon_2_s,tu_mon_2_e,tu_mon_3_s,tu_mon_3_e,tu_tue_1_s,tu_tue_1_e,tu_tue_2_s,tu_tue_2_e,tu_tue_3_s,tu_tue_3_e,tu_wed_1_s,tu_wed_1_e,tu_wed_2_s,tu_wed_2_e,tu_wed_3_s,tu_wed_3_e,tu_thu_1_s,tu_thu_1_e,tu_thu_2_s,tu_thu_2_e,tu_thu_3_s,tu_thu_3_e,tu_fri_1_s,tu_fri_1_e,tu_fri_2_s,tu_fri_2_e,tu_fri_3_s,tu_fri_3_e,tu_sat_1_s,tu_sat_1_e,tu_sat_2_s,tu_sat_2_e,tu_sat_3_s,tu_sat_3_e,tu_sun_1_s";
$param_values = "'','{$newTurnName}','1','{$newTurnType}',{$param_string_values}";
$insert_query = mysql_query("INSERT into turn_conf( {$param_name_list} ) values ({$param_values})");