Condition for comparing two arrays - php

I have two variables that return various Id numbers. I intend that when the value exists in the two variables that I update the database, if the value only exists in one, I do insert.
For example the variables will return the following values:
$N_utente1(1,2,3,4,5,6)
$N_utente(1,2,4,5,7)
So I want to create a condition that does the following:
If the values ​​in the variable $N_utente are equal to the values ​​of the variable $N_utente1, then it updates and in case the value of the variable $N_utente does not exist in the variable $N_utente1 then it inserts these values.
my code:
$query1 = $conn->prepare("SELECT N_utente FROM raddb.Areceber");
$query1->execute();
while($row=$query1->fetch(PDO::FETCH_ASSOC)){
$N_utente1 = $row["N_utente"];
$file = $_FILES["file"]["tmp_name"];
$file_open = fopen($file,"r");
while(($csv = fgetcsv($file_open, 1000, ",")) !== false){
$N_utente = $csv[1];
if($N_utente == $N_utente1){
$query = 'UPDATE Areceber SET N_utente= ? WHERE N_utente = ? ';
$conn->prepare($query)->execute([$N_utente, $$N_utente]);
}else{
$query = 'INSERT INTO Areceber (Id_linha, N_utente)
VALUES ( ?, ?)';
$stmt= $conn->prepare($query);
$stmt->execute([$Id, $N_utente]);
}
}
}
What I want is for the condition to compare the two values ​​line by line and if true, update, if false, insert

<pre>
use this code I think it will work
for ( $j = 0; $j <= count($a)||$j <= count($b); $j+1 ) {
if (a[$j] == b[$j] ) {
//
} else {
//
}
}
</pre>

Related

How to differentiate between each isset and update a specific table row in PHP

The first part of my code creates some entries in a table using $_POST.
foreach ($_POST['form_item'] as $key => $value) {
$item = $_POST['form_item'][$key];
$barcode = $_POST['form_barcode'][$key];
$task = $_POST['form_task'][$key];
$bottom_items = $pdo->prepare("INSERT INTO carpet_items_extra (`item_id`,`item_task`, `item_barcode`) VALUES ('$log_id', '$task', '$barcode')");
$bottom_items->execute();
The next part contains the data I need to update the entries with.
if(isset($_POST['form_price_standard'][$key]) && $_POST['form_price_standard'][$key] != ''){
$price_standard = $_POST['form_price_standard'][$key];
}
else{
$price_standard = 0;
}
if(isset($_POST['form_price_daily_1'][$key]) && $_POST['form_price_daily_1'][$key] != '' && isset($_POST['form_duration_2'][$key]) && $_POST['form_duration_2'][$key] != ''){
$price_daily_1 = $_POST['form_price_daily_1'][$key];
$duration_2 = $_POST['form_duration_2'][$key];
}
else{
$price_daily_1 = 0;
$duration_2 = 0;
}
$update = $pdo->prepare("UPDATE carpet_items_extra SET `price_standard` = '$price_standard', `price_daily_1` = '$price_daily_1', `duration_2` = '$duration_2' WHERE item_id = '$log_id AND item_task = '$task' AND item_barcode = '$barcode'");
$update->execute();
}
The problem is when the data is only from the first isset it's saved as it should be, but when there's data in the second isset as well, only the first row in the table gets update.
How can I differentiate between the two?
I have tried using for to execute the query once for every $barcode item, as well as using nested foreach.
The result though was multiple extra entries in the database table.

Implode array and insert dynamic data to mysql database

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();

Matching row data from excel to an array in php

$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

PHP Dynamic insert function is inserting duplicate rows

I have created a function that inserts data into MYSQL database dynamically to avoid code repetition just like so :
function insert($table, $data)
{
// connection
global $db;
if(!is_array($data)) die("Error : second parameter must be an array of keys and values");
$keys = array_keys($data);
$values = array_values($data);
// sql query
$sql = "INSERT INTO `$table` (";
// if more than one column
if(count($data) > 1)
{
for($i = 0; $i < count($data) -1; $i++)
{
$sql .= "`$keys[$i]`, ";
}
$sql .= "`" . end($keys) . "`) VALUES (";
for($i = 0; $i < count($data) -1; $i++)
{
$sql .= ":$keys[$i], ";
}
$sql .=":" . end($keys) . ")";
}else{ // only one column
$sql .= "`$keys[0]`) VALUES(:$keys[0])";
}
// make keys as named placeholders
$binds = array_map(function($elem){
return ":".$elem;
}, $keys);
// combine placeholders with values
$binds = array_combine($binds, $values);
$stmt = $db->prepare($sql);
return $stmt->execute($binds) ? true : false;
}
So Later on i can insert data just like that :
echo insert("users",[
"Name" => "Timino",
"Email" => "admin#timino.io"
]); // result 1 inserted or 0 failed
However its inserting duplicate rows ??
when i debug the code everything looks okay
echo $sql; //INSERT INTO `users` (`Name`, `Email`) VALUES (:Name, :Email)
print_r($binds) // Array
(
[:Name] => Timino
[:Email] => admin#timino.io
)
What am i doing wrong ?
Note : i have updated the code to procedural to make it easy for everyone who one to test it quickly !
Are you executing this code in your index.php?
echo $db->insert("users",[
"Name" => "Timino",
"Email" => "admin#timino.io"
]); // result 1 inserted or 0 failed
It might not be a code issue.
I had a similar issue where I was testing the insert in my index.php, and I had a rule in my .htaccess that would redirect not found files to index.php. And when the browser tries to locate your favicon, it's redirected to the index.php which will execute the code once again.
If that's the case, you can try moving your code into another file test.php and call your domain with http://localhost/test.php and check if it's still duplicating.

Insert NULL values on DB (method)

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,t‌​u_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_tu‌​e_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,t‌​u_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_tu‌​e_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})");

Categories