How can i reduce my text file size? - php

I have a php code that gets product IDs from my database (23436 unique records).
I fetch each product ID and check if it has been set in feature_product table by comparing productIDs.
If no records are found under that ID in features tables than I get check a trial.txt file for the missing features of the products again by comparing the productID in the text file with the productID that was not present in the feature_product table.
The problem is the trial.txt file has 593262 lines in it and it takes forever to match productID in this file. I run out of memory. I took me 15 hours to actually get all the data off the file and that too in parts manually. Is there any way to make it faster or not run out of time and memory?
I tried increasing the max execution time in my php.ini file as suggested by some posts on sites. But it keeps running out of memory or max execution time. I will be using mysqli once i get this right, as mysql is not used any more. I thought of dividing the product IDs so i can loop only say 5000 at a time but I don't think it would help in execution time.
<?php
$conn = mysql_connect("localhost", "dbuser", "pwd");
//loop through the 1st line to avoid the headers in csv
if (!$conn){
die('Could not connect : ' . mysql_error());
echo mysql_error();
}
echo '<p>Connected!';
mysql_select_db("mydb") or die( "Unable to select database");
//Select all product ids from product table into product array
$pArray = mysql_query("SELECT `id_product` from `product`",$conn);
//loop through each product id
while($row = mysql_fetch_assoc($pArray)) {
//get product ID to check if it exists in features table
$productID = $row["id_product"];
//check whether product id exists in feature table where product_id matches both product table and features table
$fArray = mysql_query("SELECT * from `feature_product` WHERE `id_product`=$productID");
//if product Id does not have entry in feature table than call a function to get check if product id has features in text file
if(mysql_num_rows($fArray) ==0)
{
checkFeatures($productID);
}
else continue;
}
function checkFeatures($productID){
//trial.txt contains features of the products that are missing in features table but the products are in products table
$fd = fopen('trial.txt', 'r');
$fheader = fgets($fd);
//creates a new text file to save all features(multiple records per product) separated by ',' for future use
$my_file = 'file.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);
while (($data = fgetcsv($fd,0, "~")) !== FALSE) {
//Since this text file has many products i only get the ones that are missing in the features table by comparing product ID which is the 1st element of data array
if($data[0]==$productID){
$d= $data[0].",".$data[1].",".$data[2].$data[3]."\n";
echo $d."<BR/>";
fwrite($handle, $d);
}
}
fclose($fd);
fclose($handle);
}
?>
example of product table
id_product,shop,manufacutrer,category
1000010,1,41,1112,1
1000011,1,7,1721,1
1000012,1,7,1721,1
example of feature table
feature_id,id_product,value
1,1000010,1
3,1000010,2
6,1000011,5
11,1931555,1
sample trial.txt
IMSKU~AttributeID~Value~Unit~StoredValue~StoredUnit
1000006~16121~2-25~~~
1000006~3897~* McAfee Protection Suite~~~
1000006~3933~* 1yr Subscription~~~
1000010~1708~Feb 2011~~~
1000010~1710~Cisco~~0.00~
1000010~1711~http://www.cisco.com~~~
1000011~2852~1~~0.00~
1000011~2855~Light Cyan~~0.00~
1000012~2840~May 2010~~~
1000012~2842~HP~~0.00~
I tried to load the text file as a table in sql as suggested by the users
<?php $con=mysqli_connect("localhost","username","pwd","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed: " . mysqli_connect_error();
}
mysqli_query($con,"CREATE TABLE IF NOT EXISTS `add_features` (`id_product` INT(10) NOT NULL, `id_feature` INT(10) NOT NULL, `value` varchar(255),`unit` varchar(20),`s_value` varchar(20),`s_unit` varchar(20))");
$sql = "LOAD DATA INFILE 'trial.txt'
INTO TABLE `add_features`
FIELDS TERMINATED BY '~'
";
if ($con->query($sql) === TRUE) {
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$result = mysqli_query($con,"SELECT * FROM `add_features`");
echo "<table class='add_features'>
<tr class='titles'>
<th>Product_id</th>
<th>feature_id</th>
<th>value</th>
<th>Unit</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id_product'] . "</td>";
echo "<td>" . $row['id_feature'] . "</td>";
echo "<td>" . $row['value'] . "</td>";
echo "<td>" . $row['unit'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
But i am getting an error
Error: LOAD DATA INFILE 'trial.txt' INTO TABLE add_features FIELDS TERMINATED BY '~'

If the trial.txt file is static, I would process it / parse it into either separate smaller files based on some logical divider, or import it into a new database table (preferable) where searching it will be instant. It's a one time import and then it's done.
If it's not static, how often does it change?

Related

trouble getting info from an array and then inserting it into a db

I have a page that I have been working on. It runs several queries to get existing data from several tables in my DB. There is a table that shows the result of three queries. The first query gets the extension and the secret of phones, the 2nd query gets MAC addresses of phones, and finally the third query gets the names of templates for the phones. The results of the last two queries (with the help of others) are setup as dropdowns in the 3rd and 4th columns of the table created to show the extensions. This way I can select the MAC of the phone I want to assign to the extension and then the template to make the phone work the way I want. The whole page is set as a form and I am using $post to the insert page. My goal here is to take the information (array) that is created by the user making their selections and insert ALL the 4 columns of information into a new table, from there I want to create files using that information to setup the phones. Here is the code I have for now.
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
$link = mysql_connect("localhost", "root", "cacti") or die ('Error connecting to mysql' . mysql_error());
mysql_select_db("cqadmin");
$sql2 = "SELECT extension, secret from extensions;";
$result2 = mysql_query($sql2) or die(mysql_error());
echo "<table border='3'>
<tr>
<th>Extension #</th>
<th>Secret</th>
<th>MAC Address</th>
<th>Template</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
$sql = "SELECT id , mac FROM phones order by mac;";
$result = mysql_query($sql) or die(mysql_error());
$sql1 = "SELECT id , templatename FROM templates order by templatename;";
$result1 = mysql_query($sql1) or die(mysql_error());
echo "<tr>";
echo "<td>" . $row['extension'] . "</td>";
echo "<td>" . $row['secret'] . "</td>";
echo "<td> <select name='phone'>";
while($rowA = mysql_fetch_array($result)) {
echo '<option value="' . $rowA['id'] . '">' . $rowA['mac'] . '</option>';
}
echo "</select></td>";
echo "<td><select name='template'>";
while($rowB = mysql_fetch_array($result1)) {
echo '<option value="' . $rowB['id'] . '">' . $rowB['templatename'] . '</option>';
}
echo "</select></td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" value="Submit your selections">
</body>
</html>
And my insert page
<?php
echo "You got here";
//***********Get the Assignment information *************
$values = array_values($_POST);
print_r($values);
?>
The resulting print shows this
Array ( [0] => 324 [1] => 24 )
Looking at my db table 324 is the index id of the last phone scanned and in the template table 24 is the last template created, No info on the extension or the secret.
I think I am close but I do not know where to go from here.
PS. I know I need to use mysqli or pdo, not sure how to change over yet.

Deleting an item from a mysql cart with php

I'm creating a cart system and trying to find a way to have a simple button that once pressed deletes the corresponding row. However, I cannot seem to find a way to dynamically do this with while loop I currently have.
<?php
//connect to DB.
$con = mysqli_connect("localhost", "root", "", "books");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySql: ". mysqli_connect_error();
}
$query = "SELECT * FROM cart WHERE customerID = '$_SESSION['id']'";
$result = mysqli_query($con, $query);
//creates a table for dumping the DB to, loops through the DB and posts the contents elegantly.
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td></tr>";
$totalprice += $row['bookPrice'];
}
echo "</table>";
echo "The total present price is: $".$totalprice;
//closes the conncection to the DB
mysqli_close($con);
?>
I've considered trying to put an echo query statement into the database and adding "$row['deletebutton']" to the while loop but I'm not sure that would necessarily work.
The easy way is to create a new page and send the message to this page to delete the item.
So, in the table you add a new column with a link
delete
And in the page you treat this value.
To expand on the comment posted to the question, you could add this to your row:
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td><td><input type='checkbox' name='remove[]' value='" . $row['ROW_ID'] . "' /></td></tr>";
And then with the data submitted in the form you could do something like this:
$query = "DELETE FROM cart WHERE ROW_ID IN (" . implode(',',$_POST['remove']) . ")";
Keep in mind to check the value of remove before using it in queries.

How do I dynamically display the results of my PHP results in separate divs according to their ID?

I'm trying to create a simple e-commerce system. First thing I did was select the rows with the same Order ID from mysql. My table looks like this:
Now, I'd like to know how I can group them into separate divs, it should look like this:
Here's my code:
$con = mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result2 = mysqli_query($con, "SELECT DISTINCT request_date, department_id FROM tbl_requests WHERE request_id=".$_GET['request_id']) ;
while($row2 = mysqli_fetch_array($result2)) {
echo "" . $row2['request_date'] . "<br/>";
echo "Order from Department " . $row2['department_id'] . "<br/>";
echo "<br/>";
echo "<hr/>";
echo "<br/>";
}
$result = mysqli_query($con,"SELECT * FROM tbl_requests WHERE request_id=".$_GET['request_id']);
while($row = mysqli_fetch_array($result)) {
echo "" . $row['request_details'] . "";
echo "<br/>";
}
I'm sorry if ever this question is incomplete, please feel free to ask me any more questions. Thank you in advance :)
You can check for every product in array using Javascript or jQuery(much easier).
This way you can check if your page does contain any existing div with that manufacture id (ie. #m_1055, #m_1040) or not.
If div does exist, append product in that div (in jQuery.append())
If not, then first append the div with that manufacture id to the document and then append the product to it.

Display results from an MDB file based on a selection using PHP

I hope someone can help me with this?
I have a Joomla installation running and the website looks and works great.
Here's the problem, the website is for a car dealership, which means they need to display a list of their stock on the floor.
They are using a custom system to manage their stock and this system saves the data to a MS Access database.
I got it to work to a point where I can display a table from the database. (http://www.autodeal.co.za/newsite/used-car-sales-south-africa).
Now when someone clicks on the model, which is a link that will take them to another page which displays only the information relevant to the selected model.
That's what I can't figure out. The link works fine and it takes me to the page that I want, but it doesn't display the data like it's supposed to.
Please see the code below for connecting to the database and displaying the results:
<?php
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$sql = "SELECT Make, Model, Year, Price, SpecialPrice, Branch, StockNO FROM Vehicle ORDER BY Make";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
echo "\t" . "<tr>\n";
echo "\t" . "<th>Make</th><th>Model</th><th>Year</th><th>Price</th><th>Special Price</th><th>Location</th><th>Stock Number</th>" . "\n";
while (odbc_fetch_row($rs))
{
$make = odbc_result($rs, Make);
$model = odbc_result($rs, Model);
$year = odbc_result($rs, Year);
$price = odbc_result($rs, Price);
$specialPrice = odbc_result($rs, SpecialPrice);
$branch = odbc_result($rs, Branch);
$stockNo = odbc_result($rs, StockNO);
echo "\t" . "<tr>\n";
echo "\t\t" . "<td>" . $make . "</td><td><a href=http://www.autodeal.co.za/newsite/selected-vehicles>" . $model . "</a></td><td>" . $year . "</td><td>" . $price . "</td><td>" . $specialPrice . "</td><td>" . $branch . "</td><td>" . $stockNo . "</td>\n";
echo "\t" . "</tr>\n";
}
odbc_free_result($rs);
odbc_close($conn);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
?>
Please see the code below to display a specific vehicle information from the table based on a selection made from the above script.
<?php
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$selected_id = intval($_GET['Id']);
$sql = "SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO, MainPic FROM Vehicle WHERE Id = Id";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
$id = odbc_result($rs, Id);
$make = odbc_result($rs, Make);
$model = odbc_result($rs, Model);
echo $make;
echo $model;
$image_path_main = "<img src=db/vehicleImages/" . $mainPic . "/>";
echo "this is a test";
odbc_free_result($rs);
odbc_close($conn);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
?>
EDIT So I've updated the above code based an answer received, but the individual records aren't displayed. I printed a test line and that works fine, so that tells me that there's an issue with the query? The thing is, the query works fine to display all the records in a table, but I need to display a single record when that record has been clicked.
Furthermore, the $mainPic variable above is referencing the image name from the database. The actual image isn't saved in the database; it's in a different location. I assume I need to create a variable with the actual path of the image and use the reference variables above to display the image, but it's not working.
So to recap, I need some help displaying all information from the database based on a selection.
For example: in the table, I select 323i. On a new page, I need to display all the information that's in the database about the 323i on a new page.
Is that doable and if so, could anyone please assist me in this matter.
Thank you very much in advance.
You are not using given ID parameter in your query:
$sql = "SELECT ... FROM Vehicle WHERE Id = Id ORDER BY Make";
you need to get $ID from user and place it into the query like:
$id = intval($_GET['id']); // assuming it is an integer
$sql = "SELECT ... FROM Vehicle WHERE Id = $id; // no need to order

Parsing one field to fill another field in MySQL

I am new to PHP/MySQL and am working my way through the basics.
I have a MySQL database scwdb (that I moved from Access 2000 which my Windows 7 won't work with) with a table tblsplintersbowlinventory which has 2 fields:
fields and data:
txtProductBowlCode
data examples: OakSc07-001, MapleTi07-030, MapleTi07-034, BlackLimba07-002, AshSc07-017
txtProductPrimarySpecies
data examples: Oak, Maple, Maple, BlackLimba, Ash
In other words, I want to record just the species in the txtProductPrimarySpecies field.
I tried the following PHP script:
<?php
$con = mysql_connect("localhost","xxxxxxx","zzzzzzz");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("scwdb", $con);
$species = 'Maple';
mysql_query("UPDATE tblsplintersbowlinventory WHERE txtProductBowlCode LIKE $species SET txtProductPrimarySpecies=$species%");
echo "done";
mysql_close($con);
?>
It seems to run, does not show an error and prints "done", but when I check the database I don't see any changes.
What am I missing?
This db has over 600 records, and I added this new txtProductPrimarySpecies field to make my searches easier while leaving the full code which has specific info on the bowl. There are several species that I need to do this to, so I plan on using a loop to run through a list of species.
How would I code that loop to read a list of species?
OK, I found the way to make this work!
<?php
$con = mysql_connect("localhost","xxxxxx","zzzzzzz");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("scwdb", $con);
$species = 'Maple';
$result = mysql_query("UPDATE tblsplintersbowlinventory SET txtProductPrimarySpecies = '$species' WHERE txtProductBowlCode LIKE '$species%'");
$result = mysql_query("SELECT * FROM tblsplintersbowlinventory WHERE txtProductBowlCode LIKE '$species%'");
echo "<table border='1'>
<tr>
<th>Index</th>
<th>Bowl Code</th>
<th>Species</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['intProductID'] . "</td>";
echo "<td>" . $row['txtProductBowlCode'] . "</td>";
echo "<td>" . $row['txtProductPrimarySpecies'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "done";
mysql_close($con);
?>
This worked, and I manually changed the $species value and ran it for each of the species of wood in the database...since this was a one time shot it made more sense not to use a list and loop through it - I was bound to miss one or two species anyway.
Shouldn't the set without % come before where with %. Also I think your parameter should be wrapped with a quote as it is string type.
mysql_query("UPDATE tblsplintersbowlinventory
SET txtProductPrimarySpecies='$species'
WHERE txtProductBowlCode LIKE 'CONCAT($species, '%')'");

Categories