Output of DISTINCT and <> from SQL Query issue - php

I am obtaining some values from an array and making a match against these values in an SQL Query.
The code for this is as follows:
foreach($files as $ex){
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$sql = 'SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` <> "' . $search . '" LIMIT 4';
}
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
The issue that I am having is that the <> seems not to be working.. I have even tried using the != operator, but still having the same issue.
The output of $search from the array are :
101m
102l
102m
103l
The output of SQL from the query is still:
101m
102l
102m
103l

Your code doesn't seem that logical, as you generate numerous SQL statements and then just execute the last one.
However I assume what you want to do is take a list of files, extract a string from each file name and then list all the pdb_code values from the table which are not already in the string.
If so something like this would do it. It takes each file name, extracts the sub string and escapes it, putting the result into an array. Then it builds one query, imploding the array to use in a NOT IN clause:-
<?php
$search_array = array();
foreach($files as $ex)
{
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$search_array[] = mysql_real_escape_string($search);
}
if (count($search_array) > 0)
{
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('" . implode("','", $search_array) . "') LIMIT 4";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
}

You have to use not in:
SELECT * FROM table_name WHERE column_name NOT IN(value1, value2...)

Try this:
$searchIds = implode(',',$search);
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('$searchIds') LIMIT 4";

Related

Separate records with comma

I'm new to php and I want to separate the records with a comma.
Database:
the table in sql
I use this code to get the data:
<?php
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result))
{
echo "Test: " . $row["value"]. "<br>";
}
mysqli_close($con);
?>
It return twice as:
Test: Test
Test: Test1
I want to separate the records with a ',' like this:
Test: Test, Test1
Store your values in an array and than implode with ",". You will get the result:
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
$yourArr = array();
while($row = mysqli_fetch_array($result))
{
$yourArr[] = $row["value"];
//echo "Test: " . $row["value"]. "<br>";
}
echo "Test: ". implode(",",$yourArr);
You can do this entirely in MySQL using GROUP_CONCAT:
<?php
$id = get_the_ID();
$sql = "SELECT `parent_id`, GROUP_CONCAT(`value` SEPARATOR ', ') AS comma_separated_values
FROM tablename
WHERE `parent_id` = '$id'
GROUP BY `parent_id`";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result))
{
echo 'Test: ' . $row["comma_separated_values"]; // Test: test, test2
}
mysqli_close($con);
?>
You should change the "comma_separated_values" name to something more appropriate for your data.
In your particular case, you would not need the while() loop either as we're limiting the MySQL to a single row.
If you were to remove the WHEREparent_id= '$id' from the SQL query, then you could return the results of multiple parent_id values. For example:
while ($row = mysqli_fetch_array($result))
{
echo 'Parent ' . $row['parent_id'] .': ' . $row["comma_separated_values"] . '<br>';
}
Would return:
Parent 292: Test1, Test2
Parent 293: Test3, Test4
Parent 294: Test5, Test10, Test50
etc...
you can use update query for this
$query="Update tablename set value=CONCAT(value,',test1') where parentid='295'";
$result=mysqli_query($conn,$query);

How to make a full text search engine with php and mysql?

I have created a php search engine by using an open source code. I have created a database and a table with 5 columns:
title, description, keywords, link, date
The code I'm using is the php code below:
<?php
$keywords = $_GET ['input'];
$keywords = "Led Zeppelin";
$words = explode(" ",$keyword);
foreach ($words as $w) {
$keyword_parts .= "+" . $w ." ";
}
$keyword_parts = substr($keyword_parts,0,-1);
$query = "SELECT
*,
MATCH (keywords,title) AGAINST ('" . $keywords . "') as score
FROM search
WHERE MATCH (keywords,title) AGAINST ('" . $keyword_parts . "' IN BOOLEAN MODE)
ORDER BY score DESC";
//connect
mysql_connect ("localhost", "root", "password");
mysql_select_db("intranet");
$query = mysql_query($query);
$numrows = mysql_num_rows ($query);
if($numrows >0){
while ($row = mysql_fetch_assoc($query)){
$id = $row ['id'];
$title = $row ['title'];
$description = $row ['description'];
$keywords = $row ['keywords'];
$link = $row ['link'];
$date = $row ['date'];
echo "<h2><a href='$link'>$title</a><h2/>
$description <br /><br />";
}
}
else
echo "No results found for \"<b>$each</b>\" ";
//disconnect
mysql_close();
?>
The search script works fine, but the only problem is that it searches by keyword which increases the search result, but makes it hard to find what you want because a lot of keywords on different entries match.
Now, I was reading online about full text search ("Full-text searching is performed using MATCH() ... AGAINST syntax. MATCH()") but I don't know how to apply that to my code.
This is what I've used in the past. Also, the column you're doing a MATCH on must be altered to allow FULLTEXT:
$keyword = "Led Zeppelin";
$words = explode(" ",$keyword);
$keyword_parts = '';
foreach ($words as $w) {
$keyword_parts .= "+" . $w ." ";
}
$keyword_parts = substr($keyword_parts,0,-1);
$query = "SELECT
*,
MATCH (column1,column2) AGAINST ('" . $keyword . "') as score
FROM table
WHERE MATCH (column1,column2) AGAINST ('" . $keyword_parts . "' IN BOOLEAN MODE)
ORDER BY score DESC";

PHP: How to pass multiple values to SELECT query

I am new to PHP and hope someone can help me with this.
I currently use the below lines to retrieve a value from a db and to output it as an array with the item's ID and value which works as intended.
Now I would need to do the same for multiple items so my input ($tID) would be an array containing several IDs instead of just a single ID and I would need the query to do an OR search for each of these IDs.
I was thinking of using a foreach loop for this to append " OR " to each of the IDs but am not sure if this is the right way to go - I know the below is not working, just wanted to show my thoughts here.
Can someone help me with this and tell me how to best approach this ?
My current PHP:
$content = "";
$languageFrm = $_POST["languageFrm"];
$tID = $_POST["tID"];
$stmt = $conn->prepare("SELECT tID, " . $languageFrm . " FROM TranslationsMain WHERE tID = ? ORDER BY sortOrder, " . $languageFrm);
$stmt->bind_param("s", $tID);
$stmt->execute();
$result = $stmt->get_result();
while($arr = $result->fetch_assoc()){
$content[] = array("ID" => $arr["tID"], "translation" => $arr[$languageFrm]);
}
My thought:
foreach($tID as $ID){
$ID . " OR ";
}
Many thanks for any help,
Mike
There are two approaches, assuming $tID is an array of IDs
Using MySQL IN() clause
This will work also when $tID is not an array, but a single scalar value.
$tID = array_map('intval', (array)$tID); // prevent SQLInjection
if(!empty($tID)) {
$query .= ' WHERE tID IN(' . implode(',', $tId) . ')';
} else {
$query .= ' WHERE 0 = 1';
}
Using OR clause, as you suggested
A bit more complicated scenario.
$conds = array();
foreach($tID as $ID) {
$conds[] = 'tID = ' . intval($ID);
}
if(!empty($conds)) {
$query .= ' WHERE (' . implode(' OR ', $conds) . ')';
} else {
$query .= ' WHERE 0 = 1';
}
As per above conditions you can try with implode();
implode($tID,' OR ');
You can also use IN condition instead of OR something like this.
implode($tID,' , ');

PHP query does not return result

This query is not returning any result as there seems to be an issue with the sql.
$sql = "select region_description from $DB_Table where region_id='".$region_id."' and region_status =(1)";
$res = mysql_query($sql,$con) or die(mysql_error());
$result = "( ";
$row = mysql_fetch_array($res);
$result .= "\"" . $row["region_description"] . "\"";
while($row = mysql_fetch_array($res))
{
echo "<br /> In!";
$result .= " , \"" . $row["region_description"] . "\"";
}
$result .= " )";
mysql_close($con);
if ($result)
{
return $result;
}
else
{
return 0;
}
region_id is passed as 1.
I do have a record in the DB that fits the query criteria but no rows are returned when executed. I beleive the issue is in this part ,
region_id='".$region_id."'
so on using the gettype function in my php it turns out that the datatype of region_id is string not int and thus the failure of the query to function as my datatype in my tableis int. what would be the way to get parameter passed to be considered as an int in php. url below
GetRegions.php?region_id=1
Thanks
Try it like this:
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
The region_id column seems to be an integer type, don't compare it by using single quotes.
Try dropping the ; at the end of your query.
First of all - your code is very messy. You mix variables inside string with escaping string, integers should be passed without '. Try with:
$sql = 'SELECT region_description FROM ' . $DB_Table . ' WHERE region_id = ' . $region_id . ' AND region_status = 1';
Also ; should be removed.
try this
$sql = "select region_description from $DB_Table where region_id=$region_id AND region_status = 1";
When you are comparing the field of type integer, you should not use single quote
Good Luck
Update 1
Use this.. It will work
$sql = "select region_description from " .$DB_Table. " where region_id=" .$region_id. " AND region_status = 1";
You do not need the single quotes around the region id i.e.
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"

retrieving a mysql query

I have written a mysql query and fetched the result as an assoc array using mysql_fetch_assoc().The query returns a list for two fields.I am looping through this field using through the result array and am extracting the value.how do i display the two fields since doing a plain echo is not working for me?The code which i have written is
Thanks in advance.
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
extract( $s );
echo $x . " - " . $y . "<br />";
}
I advise against using extract. it makes code very hard to follow.
I'd just do this:
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) ) {
echo $s['x'], ' - ', $s['y'], '<br/>';
}
mysql_fetch_assoc returns an array of mappings of key to value. As you didn't retrieve one and two from the database, $one and $two ($s['one'] and $s['two'] respectively) don't exist. Therefore do something like this, using the columns you selected as keys.
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
echo $s['x'] . " - " . $s['y'] . "<br />";
}
Or if you want to continue using extract (I don't recommend it, it can lead to some hard to track down bugs)
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
extract($s);
echo $x . " - " . $y . "<br />";
}
extract is a bad practice, furthermore your columns are probably called x and y and not one and two.
i suggest using the following:
echo htmlspecialchars($s['x']), ' - ', htmlspecialchars($s['y']);
According to your SELECT statement mysql_fetch_assoc() returns an array like array('x'=>something, 'y'=>something)and extract() would "translate" that to $x='something' and $y='something', not $one and $two.
Try
error_reporting(E_ALL);
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink) or die(mysql_error());
echo 'there are ', mysql_num_rows($result), " records in the result set\n";
while( false!==($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
echo $row['x'], ' ', $row['y'], "\n";
}

Categories