Drupal+Ubercart: Get product list - php

Does anyone here knows how I could get the list of products including image paths so I could manually process them without using Views?

You can write your own mysql queries or use Drupal's framework to launch your customer queries. Something like:
<?php
$query = "SELECT * FROM uc_products WHERE YOUR_WHERE_CLAUSE_HERE";
$result=db_query($query);
print mysql_result($result, 0);
// you probably want to loop through the $result array
while ($row = mysql_fetch_row($result)) {
echo "Product Title = " . $row['title_field'];
echo "Image Url = " . $row['image_url'];
}
?>
Other tables related to Ubercart that may help:
uc_product_classes
uc_product_features
Put this code in a block or page or wherever you are trying to do it.

Related

How to efficiently have 1 html layout page for many products that'll call mysql database for product info and insert where I designate it?

Ok so eventually I will have let's say 100 products in mysql database. The product page pulls all info from database (such as partnumber, material, color, etc...) and inputs it into the areas of the page that I designate it, all this using php. The previous page will show all 100 products and when user click's on one product it'll go to that product page. Just like all websites right...
I don't believe I need to make 100 individual html pages for each product right? Can I make just 1 main html page that is the templet for the 100 different products? Basically when user clicks the image tag of the product(1st example of code) it'll open the main html templet but somehow call to the database on open and load that specific info? Then other products will have the same process but for they're specific data from database. The 1st sample code is one product on the page that'll display all 100 products with the href containing the image that'll get clicked to show user actual product page retrieved dynamically without page reload, into a predestined section. I'm sure there is a name for what I'm looking to do but all the research I've done I haven't found what I'm looking for. Is there a better way then what I'm explaining? Also I hope this makes sense, Thank you for any input.
<td><img class="td-Image" src="image.jpg">
</td>
<td class="td-manufacturer">
<h6>MANUFACTURER</h6>
<p>Lowes</p>
</td>
<td class="td-addComponent">
<p>$104.99</p>
<button class="add-button">ADD</button>
</td>
<td class="td-material">
<h6>MATERIAL</h6>
<p>Aluminum 7075-t6 Forged</p>
</td>
<td class="td-platform">
<h6>PLATFORM</h6>
<p>Large</p>
</td>
<td class="td-america">
<h6>AMERICAN MADE</h6>
<p>YES</p>
</td>
Actual product page where php gets info from database example
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="description">
<h3>Descrption</h3>
<p>
<?php
echo $row['Description'];
?>
</p>
</div>
<?php
}
}
?>
Editor Note: I edited the question to reflect what he want based on thread on my answer below.
In this scenario you would need to pass in a unique identifier i.e product-id and create a query to fetch from the database product info by product-id
$product-id= $_GET['id'];
$strSQL = "SELECT * FROM AR15Parts WHERE id='$product-id'";
$rs = mysql_query($strSQL);
if (!$rs) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_assoc($rs);
//display your data
if($row){
echo $row['field'];
}
Add an unique Id to your products in your mysql database, using the Auto Increment option (A_I checkbox in phpmyadmin). Then you can pass that id into a link to the product page ```href=“individualProduct.php?id=” while rendering all the products on the all products page.
Then in individualProduct.php you can get that id and retrieve the data
$sql = SELECT * FROM Parts WHERE id =?”;
$stmt = mysqli_prepare($sql);
$stmt->bind_param($_GET[“id”]);
$stmt->execute();
$result = $stmt->get_result();
// Do stuff with $result as it is the individual product corresponding to that id
Optimally, you'll need 2 files:
index/list of products
detail information of the selected product
index files (maybe call it index.php)
Here, you need to select products and make it a list:
$stmt = $pdo->query("SELECT * FROM Parts");
while ($row = $stmt->fetch()) {
echo '' . $row['name']."<br />\n";
}
Since you want the detail to be shown to the index/list page, let's add a container area:
<div id="container-detail">
</div>
Add a little javascript code to handle AJAX request:
<script type="text/javascript">
function loadDetail(itemId){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://website.address/path/to/detail.php?id=" + itemId, true);
xhr.onreadystatechange = function ()
{
if (xhr.readyState==4 && xhr.status==200)
{
document.getElementById("container-detail").innerHTML=xhr.responseText;
}
}
xhr.send();
}
</script>
detail page (let's call it detail.php)
In this screen, we fetch details for only one part, specified by HTTP GET id parameter. The one that's being supplied from index.php (the ?id= part).
$stmt = $pdo->query("SELECT * FROM Parts WHERE id = '" . $_GET['id'] . "'");
$part = $stmt->fetch();
echo "Name: " . $part['name'] . "<br />\n";
echo "Manufacturer: " . $part['manufacturer'] . "<br />\n";
echo "Price: " . $part['price'] . "<br />\n";
That's it, you should get it working with a few adjustments based on the table and template you have.
A little note is that I used PDO mechanism to do the query. This is because mysql_* function has been deprecated for so long that it is now removed from PHP 7.0. Also, the current PHP version has been PHP 8. So, be prepared, a lot of web hosting might gonna remove older PHP versions, moving forward.

Styling output of database from php loop

I'm trying to display data from database and it is important to me that this output is placed on different sides of website. I used php to connect to database, and ajax jquery to refresh data because every 20second values change.
I tried to
echo <div styles='position: absolute; top: 0px' class='text'>{$row['id']}</div>
in a foreach loop but when I do this all 6 of my id's are stacked on top each other.
Making <div> outside loop was unsuccessful too. I guess my problem is in reading data from database because I read all at once but I don't know any other way to do this except wrtiting 6 connection files to gather only the one value that I want to display and then styling it, but I feel like there is smarter way of doing this.
This is my code. Just want to say this is my first contact with php.
<?php
$hostname = "someinfo";
$username = "someinfo";
$password = "someinfo";
$db = "someinfo";
$dbconnect = mysqli_connect($hostname,$username, $password,$db) or die("cant");
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
$sensor_names = array();
$query2 = mysqli_query($dbconnect,"show tables");
while($row2 = mysqli_fetch_array($query2)){
if($row2[0] == 'sensors' or $row2[0] == 'measurments'){
break;
}
else{
array_push($sensor_names,$row2[0]);
}
}
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, max(dev.id), dev.temprature, dev.date from sensors s, `{$sensor_names[0]}` dev where s.id=dev.sensor_id gro
up by s.id, s.sensor_name order by s.id asc");
while($row = mysqli_fetch_array($query)){ //i konw this is ugly but this is working placeholder
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, dev.temprature, dev.date from sensors s, `{$sn}` dev where s.id=dev.sensor_id order by dev.id desc limit 1");
$row = mysqli_fetch_array($query);
echo "
{$row['id']}
{$row['sensor_name']}
{$row['temprature']}
{$row['date']}
<br>";
}
}
?>
This is off-the-cuff from a guy who hasn't touched PHP in a long while, so watch for major bugs. But the basic idea is like this: build the code in a variable, and when done, echo out the entire variable. Makes it easier to add the structure/formatting you want. Note that you can also stick in a style tag along with that code and blurp out the style along with the "table" (Personally, I wouldn't use a table for styling, this is just for demo).
Note: I didn't style the output so that it puts the data on either side of the page - I left that for you to do. It's basic HTML - divs, styles, maybe css grid or flexbox. The point is to create your CSS/HTML/PHP mashup in a string variable and output the entire thing when done.
$out = '<style>.cell_id{font-weight:bold;}</style>';
$out .= '<table><tr><th>Label 1</th><th>Label 2</th><th>Etc</th></tr>'; //<=== ADDED!
while($row = mysqli_fetch_array($query)){
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, etc. etc. etc.);
$row = mysqli_fetch_array($query);
$out .= "
<tr>
<td class='cell_id'>{$row['id']}</td>
<td>{$row['sensor_name']}</td>
<td>{$row['temprature']}</td>
<td>{$row['date']}</td>
</tr>";
}
}
echo $out;
Ok I think I got it. Cssyphus's answer got me thinking and I wrote something like that array_push($data, $row) and $data is two dimentional array that hold all data I need and now I can style it easily.

How to populate multiple items on a different page using a search bar?

Hi I was wondering if anyone could help. I have just developed a search bar for my site which will be on every page loaded using an include function so they will all be the same. The code can read my database perfectly but I am at a lose on how to send more than one result to another page in the format that I need. The problem is that I post 2 to 3 variables to the next page in the url for each link of this sort and if the search bar returns more than 1 result then each result will need 2 to 3 variables to populate the next page.
Link example
Movies Home
Here is the search bar code.
<?php
if(isset($_POST['search_term'])){
$search_term = $_POST['search_term'];
if (!empty($search_term)) {
$query = "SELECT title FROM database WHERE title LIKE '%".mysql_real_escape_string($search_term)."%'";
$query_run = mysql_query($query);
$query_num_rows = mysql_num_rows($query_run);
$result = mysql_query($query_num_rows);
if ($query_num_rows >= 1) {
echo $query_num_rows.' results found:<br>';
while ($query_row = mysql_fetch_assoc($query_run)){
echo $query_row ['title']. '<br>';
}
}
else{
echo 'No results found.';
}
}
}
?>
This code currently echos on the current page. I am hopeing to pass it to a results page and populate multiple items depending on how many results were found in the search bar. Here is an example of the code that I would be hopeing to populate from the search bar on the target page.
<?php
if (isset($var1)){
$subject_set = mysql_query("Select * FROM database WHERE genre like '%".$info."%' and media = '".$med."' ORDER BY ".$sort." ", $connection);}
else{
$subject_set = mysql_query("Select * FROM media", $connection);
}
if (!$subject_set){
die("Database connection failed: " . mysql_error());
}
htlm code</div>
<?php } ?>
I was thinking that if I was even able to pass the results id's using an array and then retrieve the corrosponding results from the database on the target page.
Sorry I am still quite a novice at this type of coding and I hope I did not confuse anyone with what I am trying to say. Thank you for your time and hopefully I can get this problem sorted. Thanks again.
If you want to display the results on other pages, consider putting them in SESSION variables.
<?php
session_start ( ); // at top of page
...
$theIndex=0;
while ($query_row = mysql_fetch_assoc($query_run)){
echo $query_row ['title']. '<br>';
$_SESSION['searchResult'][$theIndex] =$query_row ['title'];
$theIndex++;
}
Then on your the page where you want to display the results, loop through the SESSION['searchResult'] and echo it out...
<?php
session_start ( ); // at top of page
$theResults = $_SESSION['searchResult'];
foreach ($theResults as $key=>$value){
echo htmlentities($value) . "<br>";
}

Smarty php variables output

Using realestate script 3 which uses smarty 3.
I managed to create the loop which gets information from the database.
<?php
function smarty_function_my_plugin($params,&$smarty)
{
$con=mysqli_connect("localhost","root","","res3");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
$result = mysqli_query($con,"SELECT * FROM res3_listings WHERE listing_type_id=5 ORDER BY views DESC");
while($row = mysqli_fetch_array($result)) {
$title=$row['title_1'];
$price=$row['price'] ;
$id=$row['listing_id'];
$result = mysqli_query($con,"SELECT listing_photo_file FROM res3_listing_photos WHERE listing_photo_id=1");
while($row = mysqli_fetch_array($result)) {
$picture=$row['listing_photo_file'];
}
echo $title. "<br/>".$price."<br/>".$picture;
$smarty->assign('naslov', $title);
echo "<br>";
}
}
mysqli_close($con);
echo '<h1>Test</h1>';
}
?>
So I put the script in plugins folder and return TEST echo at the end of script and 3 variables $title, $price, $picture. Using command in template {my_plugin}
But I want to have access to these variables so I can call them in *.tpl file, e.g.: {$title}
That way I can put HTML part in .tpl file and just insert variables I need from that function.
It should loop for 10 results on template file ;)
Theoretically your code have assigned to the naslov smarty variable the last title.
You can change it to append if you would access all of them.
This way theoretically after the {my_plugin} call you can access the titles in the {$naslov} variable.
Or you can return in your template with a $smarty->fetch('othertemplate.tpl') And you can use these variables in othertemplate.tpl.
For limiting the result to at most 10, probably the easiest way to append limit 10 to your db query.

How to select certain fields from table in mySQL using PHP

I'm trying out my hand at php at the moment - I'm very new to it!
I was wondering how you would go about selecting all items from a mySQL table (Using a SELECT * FROM .... query) to put all data into an array but then not displaying the data in a table form. Instead, using the extracted data in different areas of a web page.
For example:
I would like the name, DOB and favorite fruit to appear in one area where there is already say 'SAINSBURYS' section hardcoded into the page. Then further down the next row that is applicable to 'ASDA' to appear below that.
I searched both here and google and cant seem to find an answer to my strange questions! Would this involve running the query multiple times filtering out the sainsburies data and the asda data where ever I wanted to place the relevant
echo $row['name']." ";
echo $row['DOB']." "; etc etc
next to where it should go?
I have got php to include data into an array (I think?!)
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['DOB']." ";
echo $row['Fruit']." ";
}
?>
Just place this (or whatever your trying to display):
echo $row['name']." ";
Anywhere you want the info to appear. You can place it within HTML if you want, just open new php tags.
<h1>This is a the name <?php echo $row['name']." ";?></h1>
If you want to access your data later outside the while-loop, you have to store it elsewhere.
You could for example create a class + array and store the data in there.
class User {
public $name, $DOB, $Fruit;
}
$users = new array();
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$user = new User;
$user->name = $row["name"];
$user->DOB = $row["DOB"];
$user->Fruit = $row["Fruit"];
$users[$row["name"]] = $user;
}
Now you can access the user-data this way:
$users["USERNAME"]->name
$users["USERNAME"]->DOB
$users["USERNAME"]->Fruit

Categories