简体   繁体   中英

PHP & MySQL SELECT Substring

$content is a variable with a 'detailed description'. product_id is column which might contain a substring of the detailed description ( $content ) in a MySQL table called products

I am trying to create a select statement that would find a record if the product_id is CONTAINED in the $content variable. Then I want to update another table called receive_sms with the url field from the SELECT staement Researching on the website I have come up with the following.... But it doesn't work

$mysqlic = mysqli_connect("testsms.cloudaccess.net", "username", "password", "testsms2");
$prod_res=mysqli_query($mysqlic,"SELECT url from products
                                 WHERE %product_id% LIKE %$content%");
mysqli_query($mysqlic,"INSERT INTO recieve_sms (comments) VALUES ('$prod_res')");

Any Ideas??

Well, first of all, I don't understand why you're using wildcards on you field name. You want to check if a value is contained within the value of that field, consider changing this:

... WHERE %product_id% LIKE %$content%);

to

... WHERE product_id LIKE '%$content%');

Also, please, use prepared statements to avoid SQL injection. You're using MySQLi, which supports them.

EDIT

Also, the return of a mysqli_query is a MySQLi Resource. You'll have to fetch the results from the resource to gain access to the value you're looking for.

It should be:

$prod_res = mysqli_query($mysqlic, "SELECT url from products
                                    WHERE '$content' LIKE CONCAT('%', product_id, '%')");

or:

$prod_res = mysqli_query($mysqlic, "SELECT url from products
                                    WHERE LOCATE(product_id, '$content') != 0");

You need to put $content in quotes.

Actually, it would be better if you used a prepared query, then '$content' would become a placeholder ? .

After you query, you need to call mysqli_fetch_assoc() to get the column value:

$row = mysqli_fetch_assoc($prod_res);
$url = $row['url'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM