How can i use LIKE in this query?
I have a problem with the syntax.
$query="SELECT id,dediche FROM table_dediche WHERE dediche not in (select dedica as dediche from ".$row['nome']."_quotes)";
I have to eliminate sentences from the table using LIKE %%.
$query="SELECT id,dediche FROM table_dediche WHERE dediche not in (select dedica as dediche from ".$row['nome']."_quotes)";
$sql = mysql_query($query); //faccio la query
echo "<select style='width: 515px; margin-bottom:7px;' id='frasi' name='frasi'>";
while ($res = mysql_fetch_array($sql)){ //prendo il risultato della query
echo "<option value=\"".$res['dediche']."\">".$res['dediche']."</option>";
}
echo "</select>";
?>
Thanks in advance.
To eliminate sentences, I presume you are looking for NOT LIKE
For example
SELECT sentence FROM sentences WHERE sentence NOT LIKE '%once upon a time%';
That will obviously need to be changed to work with your table structure.
If I understand you correctly you have one table with words (or more general text). This is your table $nome. Now you want to select all rows from another table table_dediche, where column dediche does not containt anything that is in the table $nome. Is this correct?
That is not possible, if you get the values from another table. There is nothing like combining like and in with the result of a subquery. You can have a look at MySQL LIKE IN()? where they solve that problem using an regex. Not sure if that works in your case.
Related
I have a column in mysql db that contain multiple ids separated by a comma like so... 100,112,324 . The column is defined as varchar.
I want to find those rows whose ids column contains the id 112 or some other id that I specify. Similar questions I have found suggest splitting up the values in the column using lengthy code. Maybe I'm wrong but I would think there is a cleaner approach. Here is what I'm attempting to do, any help is appreciated...
<?php
include "../connect.php";
$usrid = "%112%";
$stm = $conn->prepare("SELECT * FROM subjects WHERE ids LIKE ?");
$stm->execute($usrid);
while($row = $stm->fetch(PDO::FETCH_ASSOC)) {
echo $row['consultant']."<br>";
}
?>
I get a blank page as is.
Look at this PDO prepared statement:
Try putting the "to be binded variable" in an array:
$stm->execute(array($usrid));
use single quotes for LIKE query, because you have data type as varchar.
Try this:
$stm = $conn->prepare("SELECT * FROM subjects WHERE ids LIKE '?'");
$stm->execute($usrid);
I'd like to search 3 separate tables I've created from 1 form and return the data in alphabetical order. Currently I can search 3 tables separately with use of a drop-down box (from my form) to select a table but I've fallen short at querying them simultaneously and returning all the data in alphabetical order. I've been trying to solve it but I'm struggling a lot.
Currently what my program searches through separate tables for what the user previously input into my form. Now I would like to be able to search through all my tables in 1 go and return the information in alphabetical order, meaning some values from tables might be spread out.
I have 3 tables: "Insecttable", "birdtable" and "butterflytable"
There are 3 controllers: "ControllerInsectTable", ControllerBirdTable and "ControllerButterflyTable"
I'm trying to make another controller: "ControllerAllTables" that can search through all tables.
HTML:
<form name="searchForm" id="searchForm" method="POST" action="ControllerAllTables.php">
Search for: <input type="text" name="aSearch">
<input type="submit" name="searchButton" value="Search">
</form>
PHP:
// Collect Data
// If an input has been given
if(isset($_POST["aSearch"])) {
$searchq = $_POST["aSearch"];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq); //Can only search words
// Select statements if keywords match
$sql = "SELECT * FROM insecttable WHERE insectName LIKE '%$searchq%'";
$sql1 = "SELECT * FROM butterflytable WHERE butterflyName LIKE '%$searchq%'";
$sql2 = "SELECT * FROM birdtable WHERE birdName LIKE '%$searchq%'";
}
// Tests if the code been inserted
if ($conn->query($sql && $sql1 &&sql2)=== TRUE){
echo "The rows you have searched for are:";
} else {
echo "Connection failed: ";
echo $conn->error;
}
// Show fields
$result = $conn->query($sql && $sql1 &&sql2);
// Output data of each row
if ($result-> num_rows> 0) {
readfile("ViewReturn.html");
while($row = $result-> fetch_assoc()) {
// echo "ID: ".$row["id"]. "<br>";
echo "Insect: ".$row["insectName"]. "<br><br>";
echo "Bird: ".$row["birdName"]. "<br><br>";
echo "Butterfly: ".$row["butterflyName"]. "<br><br>";
}
} else {
echo "0 results";
}
I cut out some of the bits of my code that didn't affect my question, like making connections and such.
At the moment, I have no idea how to return values in order, and I'm seriously stuck at searching multiple tables from one query. I've looked at "joins" but I really don;'t understand them.
As you can tell I'm not very good at PHP, and I hope I can soon rid it from my life. I've been completely unsuccessful in this section of my program and I'm looking for help and criticism. I know it's a lot to ask but I'm really stuck, thanks.
You'll want to use the UNION operator to combine the query results, being sure to order the data after it has been combined. This can affect performance, but hopefully your result sets aren't too large.
SELECT name -- because we NEVER use select *
FROM
(
SELECT insectName AS name FROM InsectTable WHERE insectName LIKE '$searchq%'
UNION ALL
SELECT butterflyName AS name FROM ButterflyTable WHERE butterflyName LIKE '$searchq%'
UNION ALL
SELECT birdName AS name FROM BirdTable WHERE birdName LIKE '$searchq%'
)
Also, you might want to consider a redesign of the database. If the items in your tables are all related then they are effectively a super class. If you Google "SQL super class design" you should be able to find some good patterns for this.
Also, appending the word "Table" to the end of all of your table names is not something that is usually done. If your table holds data about insects then it's "Insect" or "Insects" (I'll ignore the singular/plural debate for now). The fact that it's a table is already self-evident.
I have a database of about 3000 books and i want to be able to search my database for books either by titles, subjects or authors.. I've done my best trying to write a script using php and mysql but i still didn't get it right. can anyone assist please. Below is how far I've come with the script.. and an example of the table in my mysql database
<?php
if (#$find == "")
// Otherwise we connect to our Database
mysql_connect("localhost", "root", "erhun") or die(mysql_error());
mysql_select_db("books") or die(mysql_error());
// We perform a bit of filtering
#$find = strtoupper($find);
#$find = strip_tags($find);
#$find = trim ($find);
#$search = strip_tags(stripslashes(mysql_real_escape_string(#$db, #$_POST["search"])));
//query the database
#$query = ("SELECT * FROM `project` WHERE (`author1` LIKE '%$search%' OR `main_title` `LIKE '%$search%' OR `subj1` LIKE '%$search%')");
//displaying the data
#$results=mysql_query(#$query) or die(mysql_error ());
if(mysql_num_rows(#$results) >= 1)
//here the table starts
echo "<table id='results'>";
while($row=mysql_fetch_array($results))
{
echo "<tr><td><img src='image1/".$row['image']."' height='100px' width='90px'></td><td valign='top'>
<b><a href='details.php?id=".$row['book_id']."'>".$row['main_title']."<br/>
By: ".$row['author1']."</a></b><br/>
<b>Call no:</b> ".$row['call_no']."<br/>
<b>Type:</b> ".$row['item_type']."<br/>
<b>Year:</b> ".$row['publdate']."</td></tr>";
}
echo "</table>";
?>
my table contains these different fields
Full texts
book_id
image
main_title
author1
call_no
item_type
publdate
publplace
publshr
item_home
item_status
subj1
subj2
Try like
#$query = "SELECT * FROM `project` WHERE (`author1` LIKE '%$search%' OR `main_title` LIKE '%$search%' OR `subj1` LIKE '%$search%')";
You have an extra quote ` after "main_title"
UPDATED :
Try changing this line :
#$search = strip_tags(stripslashes(mysql_real_escape_string($db, #$_POST["search"])));
to :
#$search = strip_tags(stripslashes(mysql_real_escape_string( #$_POST["search"])));
The only thing I needed to change was dropping the $db variable, just passing in the search string, and it seems to work fine. It might be that $db was needed for some other reason so I recommend going back to the documentation you got that from and investigate further.
P.S. I'd still recommend using MATCH AGAINST. If your subject, title and author fields have an appropriate FULLTEXT index you can use MATCH AGAINST e.g. :
#$query = "SELECT * FROM `project` WHERE MATCH (subj1, main_title, author) AGAINST ('$search' IN NATURAL LANGUAGE MODE)";
This query would require that you have a fulltext index over all three columns:
ALTER TABLE project ADD FULLTEXT(subj1, main_title, author);
The list of columns in the index must match the list of columns you want to MATCH AGAINST in the query for the sake of optimisation I believe. You'd have to create other indexes if you wanted to be able to match against individual columns separately. That query also worked on my test page and it should better support normal search queries with a bit of experimentation.
P.P.S. If you have a choice of DB I would recommend using something with more support for different types of text searching. The only relational databases I'm really familiar with are PostgreSQL and MySQL and PostgreSQL has a lot better support for text searching.
I am very new to using PHP so I am asking for some help. I have this code which works fine (I got it online from somewhere).
$data = mysql_query("SELECT * FROM products")
or die(mysql_error());
print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
print "<tr>";
print "<th>title:</th> <td>".$info['title'] . "</td> ";
print "<th>info:</th> <td>".$info['information'] . " </td></tr>";
}
print "</table>";
But what PHP would I use to pull just one cell? For example, I have 9 items in my db with productIDs how could I call just the name or price or description for that particular product?
Thanks in advance.
It sounds like you want a particular row, in which, case you would just changes your query to filter for some specific value that identifies the row. THis might look something like this:
SELECT * FROM products WHERE product_id = ?
Where ? is the known product_id value that you want to receive the full record for.
Also, since you are just learning, I should point out that you should not learn to use mysql_* functions. They are deprecated. Learn mysqli or PDO for interacting with MySQL.
To obtain just one cell try the following:
SELECT CellName FROM TableName Where productId = x
So to get the price you would do:
SELECT price FROM products WHERE productid=x
Where productid equals the specific product you talked about.
if you want to understand a bit more mysql I advise you to go to PhpMyAdmin and try those and think about the result:
SELECT * FROM products;
SELECT title, information AS lol FROM products;
SELECT title, count(*) AS count FROM products;
SELECT * FROM products WHERE title = 'XXXX';
SELECT *, count(*), CHAR_LENGTH(title) FROM products;
SELECT title AS lol FROM products;
you will understand better the query language i thinks.
please read this chapter http://dev.mysql.com/doc/refman/5.0/en/examples.html. it'll really help you.
I just want to say, you can retrieve any columns(s) in any condition column
SELECT column_name(s) FROM products WHERE colmnm_name = ?
While I am running this code it showing me a following error:-
Column 'virtuemart_product_id' in where clause is ambiguous
Can anyone tell me how to resolve it.
Thank you.
<?php
mysql_connect('localhost','root','');
mysql_select_db('joom');
$get=$_GET['virtuemart_product_id'];
$get1=$_GET['virtuemart_category_id'];
$sql="SELECT
btn9c_virtuemart_products_en_gb.virtuemart_product_id,
btn9c_virtuemart_products_en_gb.product_s_desc,
btn9c_virtuemart_products_en_gb.product_desc,
btn9c_virtuemart_products_en_gb.product_name,
btn9c_virtuemart_product_prices.product_price
FROM btn9c_virtuemart_products_en_gb
JOIN btn9c_virtuemart_product_prices ON
btn9c_virtuemart_products_en_gb.virtuemart_product_id=btn9c_virtuemart_product_prices.virtuemart_product_id
WHERE virtuemart_product_id='$get' ";
if($result=mysql_query($sql))
{
while($row=mysql_fetch_assoc($result))
{
echo $row['product_price'];
}
}
else
{
echo (mysql_error());
}
?>
Put table name (or alias) with column names in where clause which are common between tables you are joining.
Try below:
$sql="SELECT
btn9c_virtuemart_products_en_gb.virtuemart_product_id,
btn9c_virtuemart_products_en_gb.product_s_desc,
btn9c_virtuemart_products_en_gb.product_desc,
btn9c_virtuemart_products_en_gb.product_name,
btn9c_virtuemart_product_prices.product_price
FROM btn9c_virtuemart_products_en_gb
JOIN btn9c_virtuemart_product_prices ON
btn9c_virtuemart_products_en_gb.virtuemart_product_id=btn9c_virtuemart_product_prices.virtuemart_product_id
WHERE btn9c_virtuemart_products_en_gb.virtuemart_product_id='$get' ";
Just add the table name to the WHERE part of the query:
..."WHERE table_you_need.virtuemart_product_id='$get' ";
In your where clause the property virtuemart_product_id is not identified unambiguously by a table name. Just use the table prefix there as well.
SELECT
prod.virtuemart_product_id,
prod.product_s_desc,
prod.product_desc,
prod.product_name,
prices.product_price
FROM btn9c_virtuemart_products_en_gb prod
JOIN btn9c_virtuemart_product_prices prices ON
prod.virtuemart_product_id=prices.virtuemart_product_id
WHERE prod.virtuemart_product_id='$get'
Btw use aliases for the tablenames. Saves a lot of typing and makes things more readable.