Building a query string in php variable - php

I am learning how.. but failing....
When I run this query I get all the products for the product type entered.
$productchk = "SELECT products"
. " from products"
. " WHERE active = '0' and product_type = '" . [v_product_type] . "'";
but I need to add the following:
order by product Limit 1
to the query and I have tried . " I keep getting syntax errors.
I thought that by adding it before the "."; on the end of statement would work but it doesnt..
Any thoughts?
Also.. what would you look up on the internet to learn about creating statements like this?

The last ' closes the value of product_type, so if you insert stuff there, it gets interpreted as part of that value. Append after "'" but before the closing ";".
Effectively:
$productchk = "SELECT products"
. " from products"
. " WHERE active = '0' and product_type = '" . [v_product_type] . "'"
. " order by product Limit 1";
Also, please use stored procedures and prepared statements! It's 1. faster, 2. much safer, 3. less escaping

$productchk = "SELECT products"
. " FROM products"
. " WHERE active = '0' AND product_type = '" . $v_product_type . "'"
. " ORDER BY product LIMIT 1";

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

Is it possible to combine these two SQL statements into one?

I am using these two MySQL statements to get all messages between two users, but I am running into a pretty big problem when it comes to manipulating the data later in the code since it's not in order by ID. Is there any way to combine these statements AND order the results by ID?
$sql = "SELECT * FROM messages WHERE sender='" . $username . "' AND receiver='" . $chatPartner . "'"
$sqlTwo = "SELECT * FROM messages WHERE sender='" . $chatPartner . "' AND receiver='" . $username . "'"
Essentially, I need every occurrence of a message between two people, but sorted by ID. As of right now, I am joining the arrays to get my full list, but it's not in order by ID.
SELECT * FROM messages
WHERE (sender='" . $username . "' AND receiver='" . $chatPartner . "'")
OR (sender='" . $chatPartner . "' AND receiver='" . $username . "'")
ORDER BY id DESC
How about just combine both into 1 query ?
$sql = "SELECT * FROM messages WHERE (sender=" . $username . " OR sender =". $chatPartner .") AND (receiver=" . $chatPartner . " OR receiver=" . $username .") ORDER BY id"
You could also write a shorter version of #dtj's answer using row constructors.
SELECT *
FROM messages
WHERE (sender, receiver) IN (($username, $chatPartner),($chatPartner, $username))
ORDER BY id DESC
In my opinion it looks a bit nicer in code and makes it more readable, but remember that it doesn't improve performance of execution.

using WHERE and AND clause with SQL and PHP

I have been trying to write the the select statement to fetch from the products table using the combination of the companyid and customerid, I am very sure I'm not doing it the right way, kindly help me to write the right sql to fetch using these parameters.
$customerid=$_SESSION['customersid'];
$companyid=$_SESSION['companyid'];
$test="SELECT producttype,quantity FROM product WHERE username= '" . mysql_real_escape_string($customerid) . "'" . 'AND'.mysql_real_escape_string($companyid) . "'" ;
You must put the fieldname for the companyid in the query
$test="SELECT producttype,quantity FROM product WHERE username= '" . mysql_real_escape_string($customerid) . "'" . 'AND COMPANYID_FIELDNAME ='.mysql_real_escape_string($companyid) . "'" ;
your syntax is incorrect. Try the following:
$customerid = mysql_real_escape_string($_SESSION['customersid']);
$companyid = mysql_real_escape_string($_SESSION['companyid']);
$test = "
SELECT producttype,quantity
FROM product
WHERE username='$customerid'
AND company='$companyid'
";
Btw, you should be using mysqli and not mysql since it is deprecated.

Why is this PHP / mySQL query giving me an error?

I am generating the first part of the query like this:
while ($all_products = $db->fetch_array($all_prods))
{
$filter_string .= 'AND product_id !=';
$filter_string .= $all_products['item_id'];
$filter_string .= ' ';
}
and then the second part like this:
$sql_more_items = $db->query("SELECT * FROM db_products
WHERE owner_id='" . $user_id . "' AND active=1 '" . $filter_string . "'
ORDER BY RAND() LIMIT 10");
However it's giving me a mySQL syntax error and the $filter_string part strangely adds ' twice before and after the string, so it runs like this:
WHERE user_id='12345' AND active=1 'AND product_id !=0001 AND product_id !=0002 ' ORDER BY RAND ...
What am I doing wrong?
$filter_string adds ' because you put it there. :P
Try with just the double quotes around $filter_string:
$sql_more_items = $db->query("SELECT * FROM db_products WHERE owner_id='" . $user_id . "' AND active=1 " . $filter_string . "ORDER BY RAND() LIMIT 10");
$sql_more_items = $db->query("SELECT * FROM db_products
WHERE owner_id='" . $user_id . "' AND active=1 '" . $filter_string . "'
ORDER BY RAND() LIMIT 10");
Check the way you're performing a string concatenation (putting together strings). It seems like there's a copy/paste error as you're using '" instead of just a "
I would use whitespace (and a good code editor) to your advantage by reformatting your code to look like this:
$queryString = "SELECT * FROM db_products WHERE owner_id='$user_id'"
." AND active=1 " //Note these
. $filter_string //are separated
. "ORDER BY RAND() LIMIT 10 "; //into individual lines
$sql_more_items = $db->query($queryString);
This style helps you keep track of whether you're using " or ' for your strings and also helps you debug things more easily than putting it into one giant hard to read string.
That's probably because of the part
`"' AND active=1 '"`
^.... This ' here

check column if empty then do update

guys i have a large database so when i want to fully update my some column i have timeout error (i attempt some method to increase timeout and fail) But my question is i want to bypass this problem i want to update my empty column in some table. so i want to use this query code but i have blank page with no error can some one tell me what problem with that or if possible pleas tell me a good method.
$sql = 'SELECT topic_first_poster_avatar FROM ' . TOPICS_TABLE . ' WHERE topic_poster = ' . (int) $row['user_id'] . 'IF topic_first_poster_avatar = ""
SET topic_first_poster_avatar = \'' . $db->sql_escape($avatar_info);
$db->sql_query($sql);
As plalx said in the comments, you don't need a SELECT or IF, you can specify WHERE for the update statement and have multiple contraints with AND/OR.
$sql = "UPDATE ". TOPICS_TABLE ."
SET topic_first_poster_avatar = '" . $db->sql_escape($avatar_info) ."'
WHERE topic_poster = " . (int) $row['user_id'] . " AND topic_first_poster_avatar = ''";

Categories