Display results from an MDB file based on a selection using PHP - 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

Related

Inserting wrong data in to the database with $wpdb->insert

So hey guys!
I currently have a code that gets data from a custom table called wp_refundrequests, and prints them as a table to the page. On the page the admin can either Accept, or Deny the request by pressing a button on the side of each order. Denying the request just deletes the request from the table, but accepting should delete it from the current table and insert the information to the next table called "accepted requests".
The wp_refundrequests table contains customer's order that they want to refund.
The code that gets the info and prints it:
global $wpdb;
$requests = $wpdb->get_results("SELECT * FROM wp_refundrequests", ARRAY_A);
foreach ($requests as $row) {
echo "<div class='requests'>" . "<li class='refunds'>" . "Palauttajan nimi: ".
$row['customer_name'] . "</br>" ."Palautettavat tuotteet: ".$row['product_name']."<br> "."Määrä: ".
$row['product_qty'] . " "
. "<br>Kommentti: " . $row['comment'] . "<br> " . "Hinta: " . $row['refund_total'] . "€ " .
"<br>" . "Päivämäärä: " . $row['request_date'] . " " .
"<a class='right' href='admin-page?deleteid=" . $row['request_id'] . "'>Deny</a></li>" .
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']
. "'>Accept</a></li>" . "</div>";
$_SESSION['custname'] = $row['customer_name'];
$_SESSION['prodname'] = $row['product_name'];
}
With my current code, the "Accept" button deletes it, and inserts information in to the new table, BUT the information that is inserted is wrong. It seems like it wants to either insert the latest data that had been inserted in to the wp_refundrequests table to the wp_acceptedrequests, or it keeps the data from the latest refund request and tries to insert that instead because for example as seen here(Sorry for the bits of Finnish as well):
If I were to click the "Accept" button on the above, older one, the query would still insert it like this:
So it basically inserts the info from the latest refund_request insert and inserts that instead of the one selected. However the one that had been selected still gets deleted from the table.
Here's the code that is triggered when the user clicks on "Accept"
$custname = $_SESSION['custname'];
$prodname = $_SESSION['prodname'];
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
/* Query to do whatever here */
$wpdb->print_error();
$wpdb->insert("wp_acceptedrequests", [
"customer_name" => "$custname",
"name_product" => "$prodname",
"date" => date("Y/m/d/G:i:sa") ,
]);
$wpdb->print_error();
$wpdb->query("DELETE FROM wp_refundrequests WHERE request_id = $accept");
}
I have to say I have no idea why it doesn't want to insert the selected request, please comment if there's something confusing, I'll try to clear it up then.
Thanks in advance!
You redefine $_SESSION with in foreach loop so at the end of foreach it will equal to the last one, pass each row parameter to it is accept link like this
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']."&custname=".$row['customer_name']."&prodname=".$row['product_name']."'>Accept</a></li></div>";
Then call it the same way you get $accept-ID
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
$custname = $_GET['custname'];
$prodname = $_GET['prodname'];
Note:Iuse my phone so make sure if it was a syntax error in the href part of the code
Please try like this and comment out the session variable.
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
$accepted_requests = $wpdb->get_results("SELECT * FROM wp_refundrequests WHERE id = $accept", ARRAY_A);
if( !empty($accepted_requests) ) {
$insert = $wpdb->insert("wp_acceptedrequests", $accepted_requests);
if($insert) {
$wpdb->query("DELETE FROM wp_refundrequests WHERE request_id = $accept");
}
}
}

How can i reduce my text file size?

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?

Return Specific Row From DB

I have multiple links on a page where each link is suppose to return a specific row of data from a database. When the link is clicked, the user is forwarded to another page where the info associated with that link is displayed. Here is the code:
//db connection: (using xampp)
mysql_connect('localhost', 'root', '');
mysql_select_db('db_name');
$sql = "SELECT * FROM user_input";
$records = mysql_query($sql);
//code:
<div>
$open_report = mtsql_fetch_assoc($records);
echo "Error Report# {$open_report['id']};
echo "<p>" .$open_report['comments'] . "</p>";
</div>
The problem is it always returns the same row of data. Each row in the db is associated with a link and when that link is clicked I want to return the associated row of data in the db. I think it may have to do with this line: $sql = "SELECT * FROM user_input"; but I'm not sure how to fix it. If anyone can help it would be greatly appreciated.
I have restructured my answer to give it a better flow. I also noticed you are using mysql_ not mysqli_ . You need to use mysqli_ as mysql is depreciated.
EDIT: This would be the page that displays all the error reports. You would want to output them in the form of a hyperlink that passes a GET parameter to the page that shows the details.
$sql = "SELECT ID, Description, etc, etc from reports";
$open_reports = mysqli_query($sql);
//error check here as well if ANY results were returned
while($row = mysqli_fetch_array($open_reports, MYSQLI_ASSOC)) {
echo ''' . $open_reports['Description'] . '';
}
This will give you links that look like
detailspage.php?id=1 detailspage.php?id=2
etc...
On the "detailspage.php" You can capture that ID and display dynamic information on that same page.
if (isset($_GET['ID'])){
$sql = "Select * from user_input where ID='" . $_GET['id'] . "'";
$records = mysqli_query($sql)
while($open_report = mysqli_fetch_array($records, MYSQLI_ASSOC)) {
echo "Error Report# " . $open_report['id'] . "<br/>";
echo "<p>" .$open_report['comments'] . "</p>";
}
}

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.

Categories