I'm trying to build a script for a cron job that loads some values from a CSV file. This CSV file has 2 fields
product_id
price
The script will load the values from CSV, then it searches in mysql table for product_id matches. If found, it will update the price for that particular matched product_id in the table with the corresponding price in CSV.
I reached the below code so far but I got stuck at the part where I need to compare the array values from CSV with the array values from mysql.
<?php
// DB part
$con = mysqli_connect('localhost','user','pass','db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"products");
$sql="SELECT product_id, price, FROM products";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
// CSV part
$file_handle = fopen("prices.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$code = str_replace(' ', '', $line_of_text[0]); //
$price = str_replace(' ', '', $line_of_text[1]); //
if (in_array($code, str_replace(' ', '', $row)))
{
echo "Match found";
print $code . " - " . $price . "<br />";
}
else
{
echo "Match not found";
print $code . " - " . $price . "<br />";
}
}
fclose($file_handle);
mysqli_close($con);
?>
You're storing just the first line of your products table in $row. Then you are doing some hard-to-understand comparisons, but all of those comparisons compare just your first row.
Here's what I'd do:
// Untested Code Below, Not Suited For Production Use
// ...
// open the DB connection, open the file, etc.
// ...
// iterate over the complete CSV file
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$product_id = clean_product_id($line_of_text[0]);
$price = $line_of_text[1];
// for any entry in the CSV file check if there is more than one result
$sql="SELECT COUNT(*) FROM products WHERE product_id='$product_id'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
if( $row[0] == 1 ) {
// update the table price for the corresponding row (product), if there is just a single result for this $product_id
$sql="UPDATE products SET price = '$price' WHERE product_id='$product_id' LIMIT 1"; // in production code use mysqli_real_escape_string() on $price and $product_id!
$result = mysqli_query($con,$sql);
} else {
// if there are more results for this $product_id, add an error to your report.txt file
}
}
Related
My teacher table is like:'
I have a teacher attendance table with data like as shown below:-
I'm trying to write codes which when executed will populate an excel file in the format given below. Where A= Absent, P= Present and, S= Sunday.
Logic for Present (P) : For any given date if ta_clock_in_tm & ta_clock_out_tm both are present then it's P.
Logic for Absent (A) : If no records exist for dates of the month in the teacher attendance table then it's A.
I also want to mark Sundays as S and calculate Total Present days and absent days.
I have not done anything like this before. I'm really confused about the sql query. Are both my tables enough to meet my requirement??
function export_to_mwiseallattenexcel($mnth)
{
$columnHeader ='';
$setData='';
$currYr = date("Y");
$noDaysInGvnMonth = cal_days_in_month(CAL_GREGORIAN, $mnth, $currYr);
$columnHeader = "Sl No"."\t"."Emp Name"."\t";
for($i=1; $i<=$noDaysInGvnMonth; $i++)
{
$columnHeader .= $i."\t";
}
$columnHeader .= "Total Working Days"."\t"."Total Absent"."\t"."Total Present"."\t"."Remarks"."\t";
$sql="";//<---WHAT TO WRITE HERE?????
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$rowData = '';
foreach($row as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData)."\n";
}
}
header("Content-Encoding: UTF-8");
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=Attendance_as.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader)."\n".$setData."\n";
}
Please help me with the SQL query. Thanks.
Open a connection to your server. There you can query EVERY command you want:
The code is:
try {
$sql = new PDO('mysql: host=localhost:3306; dbname=dbname', 'user', 'pwd');
$sql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = "do something";
$sql -> query($statement)
} catch(PDOException $e) {
echo 'Connection failed: (f) ' . $e->getMessage();
}
Some interesting commands are:
CREATE TABLE table (any datatypes); -> creates new table
INSERT INTO table () VALUES (value1),(value2); -> fills table with values
ALTER TABLE table CHANGE old_name new_bane datatype; -> change table
ALTER TABLE table DROP COLUMN user_id; -> drops a column from a database
DELETE FROM table WHERE condition; -> delete all values where condition is true
UPDATE table SET data=value WHERE condition; updates values inside a table where condition is true
I am trying to work with a voting database system. I have a form to display all the candidates per candidate type. I'm still trying to to explore that. But this time, I want to try one candidate type, lets say for Chairperson, I want to display all candidate names for that type in the ballot form. However, there's an error with the line where i declare $query and made query statements, can somebody know what it is. I am very certain that my syntax is correct.
function returnAllFromTable($table) {
include 'connect.php';
$data = array ();
$query = 'SELECT * FROM ' . $table. 'WHERE candidateId=1'; //ERROR
$mysql_query = mysql_query ( $query, $conn );
if (! $mysql_query) {
die ( 'Go Back<br>Unable to retrieve data from table ' . $table );
} else {
while ( $row = mysql_fetch_array ( $mysql_query ) ) {
$data [] = $row;
}
}
return $data;
}
As #Darwin von Corax says, I sure that you have a problem between $table and WHERE
Your query:
$query = 'SELECT * FROM ' . $table. 'WHERE candidateId=1';
If $table = 'Chairperson';
You have:
'SELECT * FROM ChairpersonWHERE candidateId=1';
The your query should be:
$query = 'SELECT * FROM ' . $table. ' WHERE candidateId=1';
I'm looking for a way to search a MySQL database for specific values and put these in an array.
The contacts table has name,email,group,Phone...
I would like to search the database by group and return the email adresses in an array, separated by , (comma) to use further in my code.
What is the best way to do this?
$result = mysqli_query($link,"SELECT * FROM Contacts WHERE Group='Group 1'")
or die(mysqli_error());
...
while($row = mysqli_fetch_array( $result ))
{
array ( row->email,...)
}
Here you have different options beginning with:
Update your select query to only display the email, if you don't require the other fields this is the way to go
In your loop just add only the email field to the array
$dataArray[] = $row->email;
$result = mysqli_query($link,"SELECT email FROM Contacts WHERE Group='Group 1'")
or die(mysqli_error());
$emailArray = [];
while($row = mysqli_fetch_array( $result ))
{
array_push($emailArray,$row->email);
}
$responseEmail = implode(",", $emailArray);
Hope this will works!
I found the way of what I was trying to do. I needed a selectbox with values from the database.
....
$query = mysqli_query($link,"SELECT * FROM XXX WHERE category='$category' AND stelplaats='$stelplaats'");
echo '<td><select name ="collega" required>';
echo '<option value"">---</option>';
while ($row2 = mysqli_fetch_array( $query ))
{
echo '<option value =" '.$row2['id'].'"';
echo '>'.$row2['name'].'</option>';
}
echo '</select></td></tr>';
....
Here is my double-minded query:
$Quest = "SELECT * FROM TOAWorkorders";
$FindTechResult = mysql_query($Quest, $cxn)
or die ('The easter bunny is watching you' . mysql_error());
while ($row = mysql_fetch_array($FindTechResult))
{
if (strpos($BBT, 0, 3) != 'Sys')
{
$IdNum = $row['IdNum'];
$BBT = $row['BBT'];
$BBTArray = explode("-", $BBT);
$TechNum = $BBTArray["0"];
$Title = $BBTArray["2"];
$Name = explode(" ", $BBTArray['1']);
$FirstName = $Name["0"];
$LastName = $Name["1"];
}
echo $TechNum . ' !! ' . $FirstName . ' !! ' . $LastName . ' !! ' . $Title . '<br>';
$Quest = "UPDATE TOAWorkorders SET TechNum = '$TechNum', FirstName = '$FirstName', LastName = '$LastName', Title = '$Title' WHERE IdNum = '$IdNum'";
$result = mysql_query($Quest, $cxn) or die(mysql_error());
}
Everything works for about 2/3s of the database. That leaves 33,000 rows that are not updated. I cannot find any difference between the data that works and the data that doesn't.
Since you're doing an UPDATE, and you say the rest of the code works (meaning, I hope, that you get 109,112 echo'ed results), it must be that the ID isn't being found (WHERE IdNum = '$IdNum').
Try preceding that command with "SELECT COUNT(*) from TOAWorkorders WHERE IdNum = '$IdNum'" and see if you get 33,000 zeros when the program runs. If you do, then you have missing IdNum values in your table.
If you don't, please provide details and I'll let you know.
I'm trying to get an array of id's from my database and then be able to echo out each id.
Something like this:
$query = mysql_query("SELECT id FROM TableName WHERE field = 'test' ORDER BY id DESC") or die(mysql_error());
$row = mysql_fetch_array($query);
echo "array: ".$row[1]." <br>";
echo "array: ".$row[2]." <br>";
echo "array: ".$row[3]." <br>";
This doesn't seem to be working though?
The problem is that mysql_fetch_array fetches an ARRAY, which is 0-based. You're fetching a single field from the database, which will be stored at $row[0] in your result array. Since you're echoing out only row[1] through row[3], you'll never see the result:
$row = mysql_fetch_array($query);
print_r($row);
should give you:
Array (
0 => 'id_field_value_here'
)
and
echo $row[0]
would also output
id_field_value_here
mysql_fetch_array fetches 1 row. You need to do something like
...
$res = array();
while ($row = mysql_fetch_array($query))
{
$res[] = $row;
}
//now $res[0] - 1st row, $res[1] - 2nd, etc