Let´s say i perform a query like this:
$charsnamequery = mysql_query("SELECT * FROM 'bookstable' WHERE 'bookcharactersname' = 'JHON'")
This will give back a resource that i then put in an array and use to print the results like this:
while ( $fullist = mysql_fetch_array( $charsnamequery ))
{ Print "book title: ".$fullist['id_book'] . ", book author:".$fullist['book_author'] . "
.....etc etc etc";
}
So, lets say that now i want to do is:
Search on my database for customers who have showed interest in any of those id_book in the past and gather their emails.
I know i am suposed to reformat the array in someway so that i can do a new query like:
$newquery = mysql_query("SELECT 'email' FROM 'customerstable' WHERE 'id_book_interested_in' IN ($value1,$value2,$value3....etc etc etc)"
Hope you can give me a hand with this! Thanks you in advance!
PS: I rather not join the querys even if it were possible for im trying to learn step by step.-
The reason why the query is not working is because you are wrapping the table name as well as column name with single quote.
SELECT * FROM bookstable WHERE bookcharactersname = 'JHON'
These are identifiers and not string literals. In this case, backticks are optional since non of them are reserved keywords.
MySQL - when to use single quotes, double quotes, and backticks?
Related
I have had at this issue for a day now. From PHP + MYSQL angle. I but because of the amount of data, most all scripts, that I've tried have timed out.
So we have two tables:
People with the row name - about 4000 unique entries
Texts with the row message - about 24 000 entries
Messages have their own format, that names get put into [] tags, like so: [Jenna].
Sadly, not all entries from Texts are correctly formatted. However I do have alot of names in People. So I want to parse trough the Texts->message's and see if any names from People is matched. Of course I do not want to match [Somename], since its already tagged.
Ultimately, the goal is to then do an UPDATE query, so the freshly matched message would be then formatted correctly with [] tag. I don't know if, this could be achieved inside the same single SQL query?!
This is a regex example on, what I want to detect and explanation on what is going on inside preg_match_all(): https://regex101.com/r/cQ6gK5/1
This is what I tried, as advanced MySQL is not my strongest side:
<?
function GetPeople () {
global $DB;
$results = $DB->query("SELECT `name` FROM People");
while ($result = $DB->fetch_array($results)) {
$return[] = $result['name'];
}
return implode('|', $return);
}
$people = GetPeople();
echo '<table><tr><th>Message raw</th><th>Matches</th>';
$results = $DB->query("SELECT `message` FROM Texts WHERE `message` NOT REGEXP '\[(.+?)\]'");
while ($result = $DB->fetch_array($results)) {
if (preg_match_all('/(?:(?:^|[\s])(' . $people . ')[\s|\n])/i', $result['message'], $matches)) {
echo '<tr><td>' . $result['message'] . '</td><td><pre>'; print_r($matches); echo '</pre></td></tr>';
}
}
echo '</table>';
I have indexed out the name and message in MySQL, because I assume, that makes it easier to search. And I imagine, that all this could be done without the php matching and only with SQL query alone. Sadly, I could never get it so optimized as it should be on my own. Any help is highly appreciated, thank you.
You could try something like this:
SELECT texts.message
FROM texts
JOIN people on texts.message LIKE CONCAT('%', people.name, '%');
This will join the two tables and then perform a like comparison based on the 'names' column in the 'people' table.
I have this code:
<?php
$data = mysql_query("SELECT * FROM repin WHERE new_pin_id LIKE ".$pinDetails->id) or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "".$info['from_pin_id'].",".$info['new_pin_id']."";
}
?>
Obtained thanks to this article: Check field for identical number
I'm trying to use the detail I pulled: ".$info['from_pin_id']." to get data from another table. I'm looking for the best way to do this.
I thought about making it a variable and then running a second statement within the same <?php?> which would look something like this:
Print "".$info['from_pin_id'].",".$info['new_pin_id']."";
}
$newdata = "".$info['from_pin_id']."";
// new statement here.
?>
But 1. it won't work and 2. it looks messy.
What is the best way to achieve it?
FYI, what I need to do is use ".$info['from_pin_id']." to match a field in another table where the data is the same ID, then pull more info based on the match.
Use the following query:
"SELECT *
FROM repin r
LEFT JOIN otherTable o
ON o.someColumn = r.from_pin_id
WHERE r.new_pin_id LIKE '".$pinDetails->id."'"
Also, the argument to LIKE must be a string; you need to put quotes around it.
I need to find the category id in the products table below. However the cms_ecom_categories.id is wrapped with the & character like &12&. Is there some kind of wild card I could use to wrap around? like %cms_ecom_categories.id% ?
$sql = "SELECT * FROM cms_ecom_products, cms_ecom_categories
WHERE cms_ecom_products.pCategories = cms_ecom_categories.id
AND cms_ecom_categories.slug = ".$page."";
You can use LIKE => WHERE id LIKE %12%
Or add the &-signs to the id: $page = '&' . $page . '&' => WHERE id = $page
Either use AND cms_ecom_categories.slug = '&".$page."&' - just put the ampersands in the quotes
Or use the _ wildcard, meaning exactly one character: AND cms_ecom_categories.slug LIKE '_".$page."_'
Or use the % wildcard, meaning zero or more characters: AND cms_ecom_categories.slug LIKE '%".$page."%'
It might be better to modify the $page variable itself though. And why are you building SQL-queries from a string? You should check parameterized queries or at least escape, it's easier and more secure.
Is there any way to check if a column is "anything"? The reason is that i have a searchfunction that get's an ID from the URL, and then it passes it through the sql algorithm and shows the result. But if that URL "function" (?) isn't filled in, it just searches for:
...AND column=''...
and that doesn't return any results at all. I've tried using a "%", but that doesn't do anything.
Any ideas?
Here's the query:
mysql_query("SELECT * FROM filer
WHERE real_name LIKE '%$searchString%'
AND public='1' AND ikon='$tab'
OR filinfo LIKE '%$searchString%'
AND public='1'
AND ikon='$tab'
ORDER BY rank DESC, kommentarer DESC");
The problem is "ikon=''"...
and ikon like '%' would check for the column containing "anything". Note that like can also be used for comparing to literal strings with no wildcards, so, if you change that portion of SQL to use like then you could pre-set the variable to '%' and be all set.
However, as someone else mentioned below, beware of SQL injection attacks. I always strongly suggest that people use mysqli and prepared queries instead of relying on mysql_real_escape_string().
You can dynamically create your query, e.g.:
$query = "SELECT * FROM table WHERE foo='bar'";
if(isset($_GET['id'])) {
$query .= " AND column='" . mysql_real_escape_string($_GET['id']) . "'";
}
Update: Updated code to be closer to the OP's question.
Try using this:
AND ('$tab' = '' OR ikon = '$tab')
If the empty string is given then the condition will always succeed.
Alternatively, from PHP you could build two different queries depending on whether $id is empty or not.
Run your query if search string is provided by wrapping it in if-else condition:
$id = (int) $_GET['id'];
if ($id)
{
// run query
}
else
{
// echo oops
}
There is noway to check if a column is "anything"
The way to include all values into query result is exclude this field from the query.
But you can always build a query dynamically.
Just a small example:
$w=array();
if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";
if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where='';
$query="select * from table $where";
For your query it's very easy:
$ikon="";
if ($id) $ikon = "AND ikon='$tab'";
mysql_query("SELECT * FROM filer
WHERE (real_name LIKE '%$searchString%'
OR filinfo LIKE '%$searchString%')
AND public='1'
$ikon
ORDER BY rank DESC, kommentarer DESC");
I hope you have all your strings already escaped
I take it that you are adding the values in from variables. The variable is coming and you need to do something with it - too late to hardcode a 'OR 1 = 1' section in there. You need to understand that LIKE isn't what it sounds like (partial matching only) - it does exact matches too. There is no need for 'field = anything' as:
{field LIKE '%'} will give you everything
{field LIKE 'specific_value'} will ONLY give you that value - it is not partial matching like it sounds like it would be.
Using 'specific_value%' or '%specific_value' will start doing partial matching. Therefore LIKE should do all you need for when you have a variable incoming that may be a '%' to get everything or a specific value that you want to match exactly. This is how search filtering behaviour would usually happen I expect.
Let's say I have a query:
" SELECT * FROM table
WHERE donor_id = " .$this->session->userdata('id') ."
GROUP BY rating"
However, it appears that I get a mysql syntax error here, citing that $this->session->userdata('id') gives me '25' for example, instead of 25. Are there any workarounds here to prevent $this->session->userdata('id') from being quoted?
Thanks.
In CI, I do this all the time:
$id = intval($this->session->userdata('id'));
$sql = " SELECT * ".
" FROM table ".
" WHERE donor_id = {$id} ".
"GROUP BY rating ";
//process $sql below
Creating query like this will make you easier to spot bug and prevent SQL injection. Use concatenation when you need to split query to multiple lines instead of make it a long multiple string is to prevent the actual query string got too long. Indent the SQL keyword is to make it easier spot logical and syntax bug.
intval($this->session->userdata('id'))
Assuming you mean that it is returning you a string instead of an integer you could always try using settype or intval:
$var = '2';
settype($var, "integer");
$var = intval($var);
However, if you mean that the quotes are for some reason hard-coded in, you could do a string replace, if you are sure that the value will not contain quotes:
ech str_replace("'", "", "'2'"); // prints 2