OpenCart: How to access database - php

I'm trying to access my custom table in the database where I have all my OC tables. I'm basically trying to enter in the product ID to my own custom table after the customer has successfully purchased the product. I'm having trouble translating a normal sql query into the OC syntax:
"$result = $this->db->query("SELECT * FROM " . DB_PREFIX . "table");"
Let's say I want to "SELECT * FROM test123 WHERE PID = '$x'";
Where "test123" is the name of my custom table.
How can I perform this query in OC?

$this->db->query("SELECT * FROM test123 WHERE PID = '" . (int)$x . "'");
or
$this->db->query("SELECT * FROM test123 WHERE PID = '" . $x . "'");
Either of them should work for you.
Usually opencart tables start with a prefix, for example 'oc_'. So all the tables customers, users, etc are named as oc_customers, oc_users, etc. If you have named your table with the same prefix then you can try
$this->db->query("SELECT * FROM " . DB_PREFIX . "test123 WHERE PID = '" . (int)$x . "'");

Related

Return query with missing/different data only

i have a form where you can select category and will return products that are in this category
$query = $this->db->query("SELECT id, name FROM " . DB_PREFIX . "shared_products_product WHERE category = '" . (int)$id . "' AND status != 2");
Result
Array
(
[0] => Test 1
[1] => Test 2
[2] => Test 3
)
Than you can select only Test 1 and Test 2 to insert in different table
$this->db->query("INSERT INTO " . DB_PREFIX . "shared_products_view SET product_id = '" . (int)$product_id . "', shared_product_id = '" . (int)$shared_product_id . "', category_id = '" . (int)$cat_id . "'");
When i run 1st query how will i get result that still not inserted into shared_products_view for current category_id ?
you need to join table and check if value is already existing
Like this
$query = $this->db->query("SELECT `spp`.id, `spp`.name
FROM " . DB_PREFIX . "shared_products_product `spp`
LEFT JOIN " . DB_PREFIX . "shared_products_view `spv` ON `spp`.`id`=`spv`.shared_product_id
WHERE category = '" . (int)$id . "' AND status != 2 AND `spv`.shared_product_id IS NULL");
When you run your second query, the INSERT, the row will be added, unless you have an error. One thing that comes to mind is you seem to insert integers as strings.
It is better to use PDO and bindValue() and explicitly state it is an integer.
If I understand you right, you want to know if the INSERT succeeded. (Is that correct?)
In that case check the result of your command $this->db->query("INSERT ...").
You didn't mention what database handle $this->db is, but I expect it will return false on failure.
I highly recommend you study this hands-on guide first before proceeding:
https://phpdelusions.net/pdo

Querying MySQL tables

I am working on someone else program. I have 2 tables Products and Seller. These tables are connected and the connection is made in the Seller table. I want to display the Product name from the Products table and also display the Seller who has made the product entry.
This is how I display the product table:
public function getProductName($product_id,$language_id) {
$query = $this->db->query("SELECT name FROM " . DB_PREFIX . "product_description WHERE
product_id = '".(int)$product_id."'
AND language_id = '".(int)$language_id."'");
if($query->row AND $query->row['name'] != '') {
return $query->row['name'];
} else {
return '-';
}
}
The Seller table has fields seller_name, seller_id, sproduct_id. How can I pull the associated seller name for each product?
Using your code:
public function getProductName($product_id, $language_id)
{
$strSQL = "SELECT p.name, s.seller_name FROM " . DB_PREFIX .
"product_description p INNER JOIN " . DB_PREFIX .
"Seller s ON p.product_id = s.sproduct_id WHERE product_id = '" .
intval($product_id) . "' AND language_id = '" .
intval($language_id) . "'";
$query = $this->db->query($strSQL);
if($query->row AND $query->row['name'] != '') {
return $query->row['name'];
} else {
return '-';
}
}
If product_id and language_id are integer values you don't need to enclosed them in ''. Also remember to add error checking to make sure that $product_id and $language_id have valid values for your query. More info on SQL joins.
You'll want to join the two tables together on the common product_id key. Here's the resultant Sql you'll want. Also, if product_id and language_id are integers in the database (as they seem to be in PHP) that you can drop the '':
"SELECT pd.name, s.seller_name
FROM " . DB_PREFIX . ".product_description pd
INNER JOIN " . DB_PREFIX . ".Seller s on pd.product_id = s.sproduct_id
WHERE
product_id = ".(int)$product_id."
AND language_id = ".(int)$language_id.";";

OpenCart, display the total number of products

I'm using OpenCart ecommerce, and I would like to see in the index of ecommerce the total number of products
I do not have (for now) access to the db opencart, so to understand what is the structure of the db I have referred to this image
And this is an example of a query that I'm trying to use to display the total number of products (the result is obviously not what I expect)
//Test Count Product
//$query_test = $db->query("SELECT " . DB_PREFIX . "product_description.name FROM " . DB_PREFIX . "product INNER JOIN " . DB_PREFIX . "product_description ON " . DB_PREFIX . "product.product_id = " . DB_PREFIX . "product_description.product_id");
$query_test = $db->query("SELECT * FROM " . DB_PREFIX . "product");
$count_test = 0;
foreach ($query_test as $row) {
$count_test++;
}
echo $count_test;
Try this:
$query = $db->query("SELECT COUNT(*) AS total FROM ".DB_PREFIX."product");
echo $query->row['total'];
Nicolo,
Your code is also correct. For that you need to use this code
$query_test = $db->query("SELECT * FROM " . DB_PREFIX . "product");
$count_test = 0;
foreach ($query_test->rows as $row) {
$count_test++;
}
echo $count_test;
But, I will recommend Monkeyman's way to get product_totals but with some modification (Monkeyman's code will NOT work for multiple stores)
$query = $db->query("SELECT COUNT(*) AS total FROM ".DB_PREFIX."product_to_store WHERE store_id = '" . (int)$this->config->get('config_store_id') . "'");
echo $query->row['total'];

opencart seo_url not working for categories

$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($part) . "'");
echo "SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($part) . "'";
exit();
i have added the keyword for the category and the output for this echo is
SELECT * FROM oc_url_alias WHERE keyword = 'fashion'
i echoed this part in seo_url.php under controller/common.
this is working for products and information but not for category even when i run this output query in sql it gives me a single row with keyqord ='fashion'
how can the query be right, yet it gives 0 when keyword is for category.

Mysql Insert data to table with duplicate data except one field

I am developing a classroom website.
There is a form to insert student profile/data into the database table student.
This site has 5 class groups, IDs as id= 1, 2, 3, 4, 5.
Inserting data to database table succeeds.
But I have a question: Each student must be under classroom 1 and 2, so when we insert data I need the database to automatically create two database results for each times, both results all field are same data except classgroup_id, i mean one result must classgroup_id=1 and second result must be classgroup_id=2, i need mysql automatically generated this for when add each student... any idea.?
this is my table structure
student_id (int) AI
name
email
classgroup_id (default value=1)
user_id
this is my php code for insert data to table
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "'");
thanks... i have only a medium level php knowledge
ClassGroups are in table or just static numbers?
If they are just static numbers, then i think simpliest way is to do another insert with duplicated data. For example for both rows should be:
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "'");
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "', classgroup_id =2");
If they are in some table, then you can do insert with one insert(code will be shorter) but with different insert syntax then yours. For example your ClassGroup table is just ClassGroups:
$this->db->query("INSERT INTO " . DB_PREFIX . "student (user_id, name, email, ClassGroup_id)
select " . (int)$this->user->getId() . ", '" . $this->db->escape($data['name']) . "', '" . $this->db->escape($data['email']) . "',ClassGroup_id from ClassGroups where ClassGroup_id=1 or ClassGroup_id=2");
But i think it should be best if you do for each data(student, ClassGroup) different table and do relation table for them, it will not duplicate data and table student will be faster if you gather data from it by primary AI key and not by varchar type column name.
You don't need PHP to do this... Pure SQL pseudosolution:
INSERT INTO student (student_id name, email) SELECT name, email from student where classgroup_id = ?
If you construct a fiddle and leave a comment as to where to find said fiddle, I'd be happy to tweak the query for your specific needs.
In order to avoid duplicate entries for students, you can make another table in which you link the students to their classes.
For example:
Students
student_id (primary key)
name
email
user_id (if still needed...)
Classgroups
classgroup_id (primary key)
classgroup_name
StudentsPerClassgroup
student_id (foreign key)
classgroup_id (foreign key)
You have to keep the record in temporary table first and then do the operations .. try it
//get last insertId
$last_insert_id = $this->db->insert_id();
$new_id = $last_insert_id +1;
$query = "CREATE TEMPORARY TABLE tmp SELECT * FROM yourtable WHERE your_primary_key = $last_insert_id;
UPDATE tmp SET your_primary_key= $new_id,classgroup_id = 2 WHERE your_primary_key = $last_insert_id;
INSERT INTO yourTable SELECT * FROM tmp WHERE your_primary_key = new_id";
$this->db->query($query);
Hope you get some idea

Categories