$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??
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'];
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.
Related
I am trying to implement a search using php5 pdo and mysql. What I am trying to do is search for a given set of keywords in my table 'posts' and return records that contain any of the given keywords in the column 'title'. But it returns no result set even if I give keywords that I know exist in the table. I use collation 'utf8mb4_unicode_ci'. Here is my code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$charset="utf8mb4";
$dsn="mysql:host=$host;dbname=$db;charset=$charset";
$opt=[ PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION];
$pdo=new PDO($dsn,$user,$pass,$opt);
$keywords=$_POST['keywords'];
$keywordArray=explode(' ',$keywords);
$n=count($keywordArray);
$query="SELECT * FROM posts WHERE title LIKE ?";
$keywordArray[0]="'%".$keywordArray[0]."%'";
for($i=1;$i<$n;$i++){
$keywordArray[$i]="'%".$keywordArray[$i]."%'";
$query=$query." OR title LIKE ?";
}
$query=$query." LIMIT 50;";
echo $query;
$stmt=$pdo->prepare($query);
$stmt->execute($keywordArray);
$res=$stmt->fetchAll();
echo "<br><h1>SEARCH RESULTS:</h1><br><ul>";
if($res){
foreach($res as $row){
echo "<li>".$row['date']."".$row['title']."</li><br>";
}
}
else{
echo "<h2 style=\"color:red;\">No results!</h2>";
}
echo "</ul></div>";
}
?>
Its working inside the console.
SELECT * FROM posts WHERE title LIKE '%hit%' OR title LIKE '%fifa%';
returns two rows. But searching with 'hit fifa' using the form returns zero rows.
Since you are using prepared statements, you don't need the single quotes around your expression. Change your code, removing those quotes, to
$query="SELECT * FROM posts WHERE title LIKE ?";
$keywordArray[0]="%".$keywordArray[0]."%";
for($i=1;$i<$n;$i++){
$keywordArray[$i]="%".$keywordArray[$i]."%";
$query.=" OR title LIKE ?";
}
It was treating the quote marks as being part of the value inside the parameter. So you would have ended up with SQL something like
SELECT * FROM posts WHERE title LIKE '\'%Something%\''
and clearly this won't match, because the values in the database won't have single quotes at the start and end in most cases.
With the changes, it should translate into SQL like this
SELECT * FROM posts WHERE title LIKE '%Something%'
This is because the parameterisation process handles the quoting and escaping job automatically for you - it's one way in which it protects against SQL injection attacks ( and also, incidentally, against syntax errors caused by erroneous / unescaped quote marks).
P.S. If a request is ever submitted to this code where no keyword at all was provided, then the code will crash because it assumes there is always a value in $keywordArray[0]. Consider revising this to either validate that a keyword was provided, or just loop the whole array and, if no keywords are submitted, simply don't add a WHERE clause to the query at all.
I'm trying to pass a variable in the select portion of one of my mysql statements here but am not getting the desired result. Heres a snippet of my code:
if(isset($_GET['send'])) {
$send='ra_dccr.'.$_GET['send'];
}
$query = $link->prepare("SELECT locale.id, locale.provider_num, locale.provider_name, :var as ccr
FROM `ra_dccr`
INNER JOIN `locale`
ON ra_dccr.id = locale.id
WHERE locale.report_record_num LIKE concat ('%',:recordnum,'%')
$query->bindParam(':var', $send, PDO::PARAM_STR);
$query->execute();
My issue is that ccr is displaying as ra_dccr.{value of $send}
instead of the actual value that should be pulled from the database when I fetch the result. Am I actually allowed to use variables in this way in a select statement? How can I get sql to look for the appropriate column name this way. For instance if send is ct_scan, it should look for ra_dccr.ct_scan and then pull the val.
Thanks in advance
Heres an image of what is happening
No, this is not possible. Parameters are for passing values to a query. And that's what happens here: the value you pass to :var is returned literally.
If you want to use a dynamic field name, build the query using the actual field name without using bind parameters:
"SELECT locale.id, locale.provider_num, locale.provider_name, $send as ccr
The best way to do this is to verify the value of $_GET['send'] first. Maybe you can even check it against a whitelist of allowed fields.
if (!in_array($_GET['send'], array('field1', 'field3', 'field30'))) {
die('invalid field!');
}
I pass two different values into the file, one which the user entered and the other which is selected from a predefined set of values in a drop down menu, which is the one i'm having trouble with.
When using a single placeholder for the query it works,for example:
$result = pg_query_params($con, "SELECT * FROM chemsub WHERE name like $1", array("%".$_REQUEST['term']."%"));
I want to alter the query so the user can change which column they are searching i can't seem to get it to work, here is what i have
$result = pg_query_params($con, "SELECT * FROM chemsub WHERE $1 like $2", array($_REQUEST['dropdown'],"%".$_REQUEST['term']."%"));
I know the correct value is being passed into the file with the correct spelling matching a column name in the database but for some reason it returns no rows.
Any help would be much appreciated.
You can't have params in place of identifiers. If you want to have a dynamic column being queried again you can either prepare the query text in php or have the sql look like ($1 = 'foo' AND foo LIKE $2) OR ($1 = 'bar' ANd bar LIKE $2.`
I am working on a shopping cart website for a university project and need some help.
The site is currently under production at http://www.cutecupcak.es.
At the moment, each product has a url of something like http://cutecupcak.es/product.php?id=11, but I want it to be something like http://cutecupcak.es/product.php?id=chocolate_cupcake.
This is the code we have been given to make this work.
if(isset($_GET['id'])) {
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM `CAKE` WHERE `cake_id`=($id)");
}
What do I need to change to get the cake_name to show rather than the cake_id?
Generally, if you want to reference your products by a name instead of id - you should add a new column (I always name it as "slug") with an UNIQUE key. Then, when product is added or edited, based on its name you generates new value for the slug column. For example - from "Chocolate Cake" you will create "chocolate_cake". Then you have to check if the slug is unique - and if not - resolve conflict somehow (e.g. "chocolate_cake_1").
If you have all this set up - just select the appropriate product by unique slug:
$result = mysql_query("SELECT * FROM `CAKE` WHERE `slug`='" . mysql_real_escape_string($_GET['id']) . "'");
And - obviosuly - use mysqli instead of deprecated mysql functions.
http://php.net/manual/en/mysqli.query.php
You can put the name in the url, which should be quite simple, since you have both the name and the id in your database and you can search by and use both.
Both name and id
But I would advise against it. Product names can change a little, and changing it means that the old link wont work anymore.
I would create an url like this:
http://cutecupcak.es/product.php?id=11&name=chocolate_cupcake
or rather even:
http://cutecupcak.es/product/11/chocolate_cupcake
These urls can be indexed safely. You retain the numeric id, which you can use to lookup the number. The name is in the url as well, which is good for readability and for SEO (search engine optimization), but the name has no actual meaning. You can safely ignore it, because you got the number. Therefor all previously indexed and linked urls will remain valid after you change the name.
I would choose to use dashes instead of underscores in the product name. I believe chocolate-cupcake and chocolate+cupcake are both indexed better than chocolate_cupcake, but my information on this topic may be a bit stale.
mysql? Parameters!
I also would advise you to no longer use mysql_*, and start using PDO or mysqli. Both allow the use of parameterized queries. This allows you to pass an id or name to a query in a safe and transparent method. Safer, cleaner and better performing than using mysql_real_escape_string or functions like that. It's especially safer, because once you become accustomed to using parameters, you will start passing all variables as parameters. While you can forget to escape a variable in your current query, you cannot possibly forget to escape a variable, because it doesn't need escaping.
Try something like this:
if(isset($_GET['id'])) {
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM `CAKE` WHERE `cake_name`=(". mysql_real_escape_string($id). ")");
}
Note: I also added mysql_real_escape_string, as not doing that poses a huge SQL injection risk.
I think this just changes to:
$result = mysql_query("SELECT * FROM `CAKE` WHERE `cake_name`=($id)");
The Following is a blueprint to what you have to do:
1- In your table you should set cake_name field to be unique.
2- Your sql query should be:
$result = mysql_query("SELECT * FROM `CAKE` WHERE `cake_name`=($id)");
3- Change the links found of your products list to obtain the cake_name value instead of the numeric id.
I feel like I'm making a rookie error here somewhere but can't figure out what's going wrong. I am using PHP and mySQL. I have an array $users that stores a current user's information. The array is storing the customer id (cid, its an integer). So I'm trying to pull information that is only tagged to a specific customer. My code is:
try
{
$sql = 'SELECT id, title, image_url FROM shelf WHERE cid = $user['cid']';
$result = $pdo->query($sql);
}
I feel like I have similar code in other parts of my program that are working so this seems like I may be doing something wrong in terms of syntax. If I replace $user['cid'] in the request with a hard-coded number like 22, the statement works fine. However, I need to pull the integer from $user. I'm getting a T_STRING error on the SELECT statement line. I have also tried to add an additional set of single quotes around $user['cid'] but that's not working either (i.e. $user['cid'])
Thanks for your help.
Twine
You're using PDO, so you should be using place-holders, too:
$stmt = $pdo->prepare('SELECT id, title, image_url FROM shelf WHERE cid=:cid');
$stmt->bindParam(':cid', $user['cid']);
$stmt->execute();
This ensures your data is escaped correctly and handles conversion to the appropriate database format where required.
Yup, rookie error. Change to double quotes and add { } around value like:
$sql = "SELECT id, title, image_url FROM shelf WHERE cid = {$user['cid']}";
$sql = 'SELECT id, title, image_url FROM shelf WHERE cid = '.intval($user['cid']);