Select multiple rows from MySQL table - php

I have a session that contains an array and that array is filled with id's. What is the best way to select all the rows from a MySQL table that correspond to these id's?
So I need something like:
SELECT * FROM table WHERE id = $_SESSION['ids']
Obviously, this doesn't work, since $_SESSION['ids'] is an array.

SELECT *
FROM
table
WHERE
find_in_set(id, $_SESSION['ids'])>0

You can just use IN SQL operator.
In this case your query will look like
$sql = 'SELECT * FROM table WHERE id IN ("' . implode('","', $_SESSION['ids'] . '")';
This code will produse a query like following:
SELECT * FROM table WHERE id IN ("1", "2", "foo");
Hope it helps

HI Try This,
$var = $_SESSION['ids'];
and then fire your query as
$sql = SELECT * FROM table WHERE id = '$var';

Related

How to write a query to check if a column value is in a PHP array that may be empty

I want to return records where a id field is in a php array. Usually I would do something like this:
$ids = array(1,2,3,4)
$query = "SELECT * FROM table WHERE statusId IN (" . implode(',',$ids) . ")";
However, if the $ids array happens to be empty, I get a error from mysql because of the empty parentheses. I can accomplish my goal using a subquery like this:
$query = "SELECT * FROM table WHERE statusId IN (SELECT statusId FROM statuses WHERE /* some conditions */)";
If the subquery is empty, then it will just return an empty record set without an error. I don't want to use the subquery because I already have the ids in the php variable.
Is there a way to write the first query so it doesn't return an error if the php array is empty? I know I can just write a conditional statement and just not run the query if the php array is empty. But for style reasons, I just want to see if there is a way to write the query that returns a empty set if the php array is empty.
You would better check if the array is empty. Just write:
if ( empty($ids) ) {
//Don't run query
}
$ids = array(1,2,3,4)
$idClause = !empty($ids) ? implode(',',$ids) : 'NULL';
$query = "SELECT * FROM table WHERE statusId IN (" . $idClause . ")";
try doing a ternary
$ids = array(1,2,3,4)
$query = !empty($ids) ? "SELECT * FROM table WHERE statusId IN (" . implode(',',$ids) . ")" : "SELECT * FROM table WHERE statusId IN (SELECT statusId FROM statuses WHERE /* some conditions */)";
;

How to ask a SELECT * from table where all columns that = $var

hi how to select columns that have the var value?
like this:
$var=$_GET['id'];
$select="SELECT * FROM table WHERE **COLUMNS THAT EQUAL TO VAR** = $var";
How to select those columns that have the $var value?
Clarification: SELECT only the columns that have the value $var in them.
Example:
$var="1";
Column 1, 7, 11 have on some row value 1 then pick those columns and show in which columns the value 1 is in
You have to mention your column name in your query
If you want to check exact match you can do as follows
$var=$_GET['id'];
$select="SELECT * FROM table WHERE column_name = '$var'";
If you want to check column that contain #var you can do as follows
$var=$_GET['id'];
$select="SELECT * FROM table WHERE column_name like '%$var%'";
You must look into INFORMATION_SCHEMA Database
Provide your database name => $db
Provide your column name => $column
Then :
$sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" . $db . "' AND COLUMN_NAME = '" . $column . "'";
The easy ways is to use php to get array from all columns:
SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'YOUR-DB-NAME' and TABLE_NAME='YOUR-TABLE-NAME'
And use 'for' to create 'where'
for example:
for($i=0;$colums[$i];$i++) $where.=" or {$colums[$i]} like '%string%'";
$SQL="Select * from table where 1=1 $where";
The query will look like this:
$var=$_GET['id'];
// for checking if both the column name and value are the same $var value
$select= "SELECT ".$var." FROM table_name WHERE ".$var."='".$var."'"
OR
$var = $_GET['id'];
// for checking if both the column name and value are different
$select= = "SELECT ".$var." FROM table_name WHERE ".$var."='".$otherValue."'"
Between this is SQLinjection vulnerable code. You should check the variables before using them in query. Also you should start using mysqli and prepared statements

Select all data from a table and insert it to another table

I wanted to select all the data from one of my table and insert it to another table. I have this code but it wasn't working..This is what the phpMyadmin says "MySQL returned an empty result set (i.e. zero rows). (Query took 0.0010 seconds.)"
Here is my code:
if(isset($_POST['select_table']))
{
$select_table = mysql_real_escape_string($_POST['select_table']);
$query_select = "INSERT INTO pdf_table
SELECT * FROM $select_table";
$select_query = mysql_query($query_select,$connectDatabase);
}
Please ensure that both the tables have equal number of columns.
It is a good practice to use following way for inserting records with select query :-
INSERT INTO pdf_table (column_1, column_2) SELECT column_1, column_2 FROM $select_table
your sql query is like
INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1;
The approach you are using INSERT INTO pdf_table SELECT * FROM $select_table will give you only single row inserted from 1st table to another table.
As per your requirement you want all the records from 1st table should get insert in your pdf_table
So i will like to suggest try the following approach
May be this is what you looking for
if(isset($_POST['select_table']))
{
$select_table = mysql_real_escape_string($_POST['select_table']);
$select_query = mysql_query( "select * from $select_table ",$connectDatabase);
while ($row = mysql_fetch_array($select_query))
{
mysql_query( "insert into pdf_table values($row['column1'],$row['column2'],...,$row['columns']) ",$connectDatabase);
}
}
try this one :
if(isset($_POST['select_table']))
{
$select_table = mysql_real_escape_string($_POST['select_table']);
$query_select = " Create Table pdf_table ( SELECT * FROM $select_table); ";
$select_query = mysql_query($query_select,$connectDatabase);
}
but, this query will create new table "pdf_table".

Select from table where value does not exist

I have a table (country_table) with a list of all countries and their respective ids.
|country_id|country_name|
|ES |Spain |
.
.
.
I have an array, fetched from another table using fetch_array that looks like this:
$array = Array(
[0]=>Array([country_id]=>'ES')
[1]=>Array([country_id]=>'DE')
[2]=>Array([country_id]=>'GB'))
How can I select the records (country_id and country_name) from country_table that do not exist in the table but exist in the array?
$sql ="SELECT country_id, country_name FROM country_table
WHERE country_id NOT IN (". implode(",", $array) .")";
implode() function will generate comma-seprated string representation of array elements .
This is the sql.
select country_id, country_name from table where country_id not in ('ES','DE','GB');
// gather unwanted id's first
$notInIds = array();
foreach ($array as $arr) $notInIds[] = $arr['country_id'];
// prepare query
$query = 'SELECT `country_id`, `country_name` FROM `your_table`
WHERE `country_id` NOT IN (' . implode(',',$notInIds) . ')';
// then execute it
For the question: "How can I select the records (country_id and country_name) from country_table that do not exist in the table but exist in the array?"
I guess you have to write some code (eg. in PHP) in order to achieve the result you want.
The problem is that you can not display data that is not in the table (eg. country_name), that's not possible as you don't know this data. The only possibility would to show the country_id's which are in the array and not in the table as this is the only data you have...

Use an array inside a query string

Im trying to pass an array that I already found by a query into another query. For example:
$first_query = "SELECT id FROM from Table WHERE user = '{$_SESSION['id'}'";
$result = mysql_query($first_query,$connection);
$ids = mysql_fetch_array($result);
This is where it gets tricky for me. I want to pass $ids into the next query.
$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id = '{$id_implode}';
The second query doesnt seem to be working. Any help is greatly appreciated!
your second query's syntax is wrong. Once evaluated it should read
select * from Table2 where id in (1,2,3)
ditch the curly braces and change the = to in. Don't use OR - that's a dumb way of ignoring good sql functionality
EDIT: Teneff's comment makes a very good point - why are you approaching the problem in this way? If there is a relationship between the tables they can be joined and all the data you want can be retrieved in a single query. If for some reason you can't / won't join the tables you could at least try a sub-query
select * from table2 where id in (select id from table where user = $_SESSION['id']);
To use a where statement with multiple entries to match on, use in ().
$id_implode = "'".implode("', '", $ids)."'"
$second_query = "SELECT * FROM Table2 WHERE id in ({$id_implode});
I think you should use IN
$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id IN '({$id_implode})';
This assumes that $ids is made of int of course, otherwise you have to enclose eache entry in quotes. that means
IN (6,7,8,9)//this doesn't need quotes
IN ('lemon', 'orange')//needs quotes
try to use the IN syntax:
$id_implode = implode("', '", $ids);
$second_query = "SELECT * FROM Table2 WHERE id in ('{$id_implode}');

Categories