Matching row data from excel to an array in php - 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

Related

Condition for comparing two arrays

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>

Get the number of rows inserted in the database per hour

I know there are similar questions already, but I can't find a clear and simple answer.
I have this query :
"SELECT dbo.tbTransaction.dateHeure, dbo.tbTransaction.Etat, dbo.tbPoste.nomPoste
FROM dbo.tbTransaction
INNER JOIN dbo.tbPoste ON dbo.tbTransaction.ID_poste = dbo.tbPoste.ID_POSTE
WHERE dbo.tbPoste.id_site LIKE 47
AND dbo.tbPoste.nomPoste LIKE '0909_CLIENT'
AND dateHeure >= DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)
ORDER BY dateHeure DESC";
It enables me to fetch all the database insertions of the day(>= DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)) on a particular post (0909_CLIENT), sorted by the most recent time of insertion(ORDER BY dateHeure DESC).
I would like to be able to retrieve the number of inserts per hour, the goal is to be able to generate live graphics hour by hour.
I manage to get the total number of insertions during the day with :
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_num_rows( $result ). PHP_EOL;
echo '<br>';
if ($row_count === false)
echo "Error in retrieveing row count;
else {
echo $row_count;
}
I can see the lines entered in the database at a particular time with :
$five = "05:";
$six = "06:";
$seven = "07:";
if ($result === false) {
die(print_r(sqlsrv_errors(), true));
} else {
while ($row = sqlsrv_fetch_array($result)) {
$heureformate = $row["dateHeure"]->format('H:i');
if (strpos($heureformate, $five) !== false) {
echo $heureformate;
echo '<br>';
//count(array($heureformate));
} elseif (strpos($heureformate, $six) !== false) {
echo $heureformate;
echo '<br>';
} elseif (strpos($heureformate, $seven) !== false) {
echo $heureformate;
echo '<br>';
}
}
}
But as I told you, I don't manage to get the number of lines entered per hour and it's this number that interests me to create graphics.
If you have any ideas on how to get this number in SQL or PHP, please help me.
Do you want aggregation?
select datepart(hour, t.dateheure), count(*) as cnt
from dbo.tbtransaction t
inner join dbo.tbposte p on t.id_poste = p.id_poste
where p.id_site = 47 and p.nomposte = '0909_client' and t.dateheure >= cast(gedate() as date)
group by datepart(hour, dateheure)
This filters the dataset for rows whose dateheure belongs to the current day, and counts how many records there is in each hour.
Note that I simplified the date filtering logic, and turned the like conditions to equalities (since no wildcards are involved, both are equivalent).

php filtering an array by key

I have a csv file in a format resembling the following. There are
no column heads in the actual file - They are shown here for clarity.
id|user|date|description
0123456789|115|2011-10-12:14:29|bar rafael
0123456789|110|2012-01-10:01:34|bar rafael
0123456902|120|2011-01-10:14:55|foo fighter
0123456902|152|2012-01-05:07:17|foo fighter
0123456902|131|2011-11-21:19:48|foo fighter
For each ID, I need to keep the most recent record only, and write
the results back to the file.
The result should be:
0123456789|110|2012-01-10:01:34|bar rafael
0123456902|152|2012-01-05:07:17|foo fighter
I have looked at the array functions and don't see anything that
will do this without some kind of nested loop.
Is there a better way?
const F_ID = 0;
const F_USER = 1;
const F_DATE = 2;
const F_DESCRIPTION = 3;
$array = array();
if (($handle = fopen('test.csv', 'r')) !== FALSE) {
while (($data = fgetcsv($handle, 1000, '|')) !== FALSE) {
if (count($data) != 4)
continue; //skip lines that have a different number of cells
if (!array_key_exists($data[F_ID], $array)
|| strtotime($data[F_DATE]) > strtotime($array[$data[F_ID]][F_DATE]))
$array[$data[F_ID]] = $data;
}
}
You'll have, in $array, what you want. You can write it using fputcsv.
NOTE. I didn't test this code, it's meant to provide a basic idea of how this would work.
The idea is to store the rows you want into $array, using the first value (ID) as the key. This way, on each line you read, you can check if you already have a record with that ID, and only replace it if the date is more recent.
Each time you encounter a new id, put it in your $out array. If the id already exists, overwrite it if the value is newer. Something like:
$in_array = file('myfile.txt');
$out_array = array();
$fields = array('id', 'user', 'date', 'description');
foreach($in_array as $line) {
$row = array_combine($fields, explode('|', $line) );
//New id? Just add it.
if ( !isset($out_array[ $row['id'] ]) ) {
$out_array[ $row['id'] ] = $row;
}
//Existing id? Overwrite if newer.
else if (strcmp( $row['date'], $out_array[ $row['id'] ]['date'] ) > 0 ) {
$out_array[ $row['id'] ] = $row;
}
//Otherwise ignore
}
//$out_array now has the newest row for each id, keyed by id.

Get specific data from csv file based on mysql value using php

hi
so this is the setup: i need to update some prices from a csv file called pricelist.csv. the database table is called products and there is a column called product_id, which contains the product ids which can also be found in the first column of the csv file and the prices and lastly i need are located in the 7th column of the csv file. i need to write these to the price column of my database.
i have tried my best to come up with the code, but it just seems too much for my skill level. here is what i made:
<?php
include("admin/include/db.php");
$res=mysql_query("select * from products");
$row = 1;
$mycsvfile = array(); //define the main array.
if (($handle = fopen("pricelist.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
$num = count($data);
$row++;
$mycsvfile[] = $data;
}
fclose($handle);
}
$row['product_id'] = $mycsvfile[$which_row][1] //trying to find the row in the csv
$mycsvfile[$which_row][7] = $price; //should get price, but previous line does not work
while($row=mysql_fetch_array($res))
{
mysql_query("update products set price='".$price."', isavailable='1' where id='".$row['id']."'");
}
?>
any sort of help is welcome! thanks
I think you are looking for this (but I didn't test it):
<?php
include("admin/include/db.php");
if( ( $handle = fopen("pricelist.csv", "r") ) !== FALSE )
{
while( ( $r = fgetcsv( $handle, 1000, ";") ) !== FALSE )
{
mysql_query('UPDATE products SET "price"="'.$r[6].'", "isavailable"="1" where "id"="'.$r[0].'"');
}
}
Disclaimer: Yes I know I didn't sanitize the data, but I don't feel like working with outdated mysql functions.
You can use file() to read the CSV file into an array. Then use str_getcsv() to read each item from the file array and turn it into an array reprensnting a row from the CSV file. Then you pull the data from that array into an update query and run it.
Like this:
$id = 0;
$price = 6;
$csv_file = file('pricelist.csv');
foreach($csv_file as $row)
{
$data = str_getcsv($row);
$query = "UPDATE products SET price = {$data[$price]}, isavailable='1' WHERE `id` = {$data[$id]}";
//run the query
}

Why does using an If statement change a variable?

I am reading a text file and processing some records, a relevant sample of the text file is
#export_dategenre_idapplication_idis_primary
#primaryKey:genre_idapplication_id
#dbTypes:BIGINTINTEGERINTEGERBOOLEAN
#exportMode:FULL
127667880285760063715151750
127667880285760123715151751
I want to perform a specific action when application_id is already stored within my database AND is_primary = 1
I wrote this PHP to test my code:
$fp1 = fopen('genre_application','r');
if (!$fp) {echo 'ERROR: Unable to open file.'; exit;}
while (!feof($fp1)) {
$line = stream_get_line($fp1,128,$eoldelimiter); //use 2048 if very long lines
if ($line[0] === '#') continue; //Skip lines that start with #
$field = explode ($delimiter, $line);
list($export_date, $genre_id, $application_id, $is_primary ) = explode($delimiter, $line);
// does application_id exist?
$application_id = mysql_real_escape_string($application_id);
$query = "SELECT * FROM jos_mt_links WHERE link_id='$application_id';";
$res = mysql_query($query);
if (mysql_num_rows($res) > 0 ) {
echo $application_id . "application id has genre_id" . $genre_id . "with primary of " . $is_primary. "\n";
} else
{
// no, application_id doesn't exist
}
} //close reading of genre_application file
fclose($fp1);
which results in this output on screen and is exactly as I expected.
371515175application id has genre_id6006with primary of 0
371515175application id has genre_id6012with primary of 1
If I then add an IF statement as in the code below, it somehow changes the value of is_primary as shown by the screen display
$fp1 = fopen('genre_application','r');
if (!$fp) {echo 'ERROR: Unable to open file.'; exit;}
while (!feof($fp1)) {
$line = stream_get_line($fp1,128,$eoldelimiter); //use 2048 if very long lines
if ($line[0] === '#') continue; //Skip lines that start with #
$field = explode ($delimiter, $line);
list($export_date, $genre_id, $application_id, $is_primary ) = explode($delimiter, $line);
// does application_id exist?
$application_id = mysql_real_escape_string($application_id);
$query = "SELECT * FROM jos_mt_links WHERE link_id='$application_id';";
$res = mysql_query($query);
if (mysql_num_rows($res) > 0 ) {
if ($is_primary = '1') echo $application_id . "application id has genre_id" . $genre_id . "with primary of " . $is_primary. "\n";
} else
{
// no, application_id doesn't exist
}
} //close reading of genre_application file
fclose($fp1);
?>
The code above results in the following screen display, which incorrectly has the first field with a primary of 1, when as can be seen by the previous screen display and the sample text file it should be 0
371515175application id has genre_id6006with primary of 1
371515175application id has genre_id6012with primary of 1
Can anyone explain what I am doing to make the variable change and how I should use the If correctly please?
You are assigning a value instead of comparing:
($is_primary = '1')
you need
($is_primary == '1')
or === for a type-safe comparison.
This is why some people like to write their comparisons like so:
('1' == $is_primary)
the mistake is impossible to make here because "1" can't be assigned anything.
Personally though, I think that over time and with growing practice, one will learn to spot the mistake.
You need to use:
if ($is_primary == '1')
NOT
if ($is_primary = '1')
Because "=" defines variable and returns true, but "==" actually compares and doesn't change anything.
The if-line has only one = (assign value) instead of two == (compare value).
Try this instead:
if ($is_primary == '1')
if ($is_primary = '1')
You need to use the comparison operator ==, not the assignment operator =
if ($is_primary == '1')
....
NOT = BUT ==
Also consider removing all the stuff that bug the reading of your question for example somthing like:
// does application_id exist?
$res = mysql_query($query);
if (mysql_num_rows($res) > 0 ) {
echo $is_primary. "\n";
}
This is more readable and fit you purpose.
You may even find yourself does kind of bug.
If you type
if($x=10)...
Then you're telling it to attempt the operation
$x=10
to which it will return a success (return true). This will always run the loop, and alter the value of x.
To test $x, use
if($x==10)...
But note that to test for $x not equals 10 is
if($x!=10)...
ie, one equals and one bang.
Chek out PHP comparison operators

Categories