PHP Mysqli select two DISTINCT from data base - php

I am trying to fetch two different DISTINCT values from data base am not able to do that that gives me an error. I don't want both to be combined in as statement and fetch as one I need individual DISTINCT values.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DISTINCT AttendanceID from attendance_master where Attendence_taken_by !='admi' at line 1\
My Query
$query = "select DISTINCT Standard , DISTINCT AttendanceID from attendance_master where Attendence_taken_by !='$admin' and SchoolID='$schoolid' and AttendanceDate >= '$tfrom_date' and AttendanceDate <= '$tto_date' ";
$result = mysqli_query($mysqli,$query)or die(mysqli_error($mysqli));
while($row=mysqli_fetch_array($result))
{
echo "<table><tr>".$row["Standard"]."</tr><tr>".$row["AttendanceID"]."</tr></table>";
}

Syntax of DISTINCT is
SELECT DISTINCT column_name,column_name
FROM table_name;
So change your query with
$query = "select DISTINCT Standard , AttendanceID from attendance_master.....
Instead of assign direct value use bind_param

Related

right syntax to use near '%+ads.title+%\r\n AND\r\n products_request

I would like to compare two columns by like :
$sql = "SELECT
products_requests.id as req_id,ads.id as send_id,
products_requests.user_id,ads.des,ads.title
FROM
products_requests,ads
WHERE
products_requests.title LIKE '%'+ads.title+'%'
AND
products_requests.ads_cat_id = ads.ads_cat_id
AND
products_requests.ads_sub_cat_id = ads.ads_sub_cat_id
AND
products_requests.price_type_id = ads.price_type_id
AND
products_requests.province_id = ads.province_id
AND
products_requests.city_id = ads.city_id";
but I get this error :
"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '%+ads.title+%\r\n AND\r\n products_request' at line 9"
In MySQL, perform string concatenation operations with the CONCAT function
... LIKE CONCAT('%',ads.title,'%')
I also recommend you ditch the old-school comma syntax for the join operation, and use the JOIN keyword instead. And move the join predicates into an ON clause. And consider using shorter table aliases to qualify the column references.
SELECT req.id AS req_id
, ads.id AS send_id
, req.user_id
, ads.des
, ads.title
FROM products_requests req
JOIN ads
ON req.title LIKE CONCAT('%',ads.title,'%')
AND req.ads_cat_id = ads.ads_cat_id
AND req.ads_sub_cat_id = ads.ads_sub_cat_id
AND req.price_type_id = ads.price_type_id
AND req.province_id = ads.province_id
AND req.city_id = ads.city_id

PHP Prepared Statement variable binding error with subquery

I have a query with a few subqueries like so
SELECT ...
FROM (SELECT ...
FROM ...
GROUP BY ...) as speedLimitCalc INNER JOIN
(SELECT ...
FROM date a INNER JOIN HOURLY_TEST b ON a.[FULL_DAY_DT] = b.DATE
WHERE (b.DATE BETWEEN '".$date_s."' AND '".$date_e."')
AND HOUR BETWEEN ".$time_s." AND ".$time_e."
AND(LKNO BETWEEN '".$lkno_s."' and '".$lkno_e."')
AND RDNO= '".$rdno."'
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (".$dayquery.")
GROUP BY RDNO, LKNO, PRESCRIBED_DIRECTION, CWAY_CODE) as origtable ON ...
,(SELECT ...
FROM [Dim_date]
WHERE (FULL_DAY_DT BETWEEN '".$date_s."' AND '".$date_e."')
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (".$dayquery.") ) as c
ORDER BY ...
where I am inserting variables in the inner query where clause.
I am trying to parametrize this query using odbc_prepare and odbc_execute, however I am running into issues of binding the variables. At present, when I use the following
$result = odbc_prepare($connection, $query);
odbc_execute($result)or die(odbc_error($connection));
to run this query, everything works fine. However, when I try to bind a variable, such as
AND RDNO= ?
...
odbc_execute($result, array($rdno))or die(odbc_error($connection));
I get the following error message.
PHP Warning: odbc_execute() [/phpmanual/function.odbc-execute.html]: SQL error: [Microsoft][ODBC SQL Server Driver]Invalid parameter number, SQL state S1093 in SQLDescribeParameter
My guess is that it's because I'm binding a variable in a subquery, since this procedure works when the Where clause is in the top Select query.
I was wondering whether anyone else has encountered this issue before, and how they solved it? Thanks
Fixed the issue by removing the need for parameters in the subquery by separating the query into multiple queries using temporary tables.
$query = "SELECT ...
INTO ##avgspeedperlink
FROM Date a INNER JOIN HOURLY_TEST ON a.[FULL_DAY_DT] = b.DATE
WHERE (b.DATE BETWEEN ? AND ?)
AND HOUR BETWEEN ? AND ?
AND(LKNO BETWEEN ? and ?)
AND RDNO= ?
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (?,?,?,?,?,?,?)
GROUP BY RDNO, LKNO, PRESCRIBED_DIRECTION, CWAY_CODE";
$result = odbc_prepare($connection, $query);
odbc_execute($result, array($date_s,$date_e,$time_s,$time_e,$lkno_s,$lkno_e,$rdno,$daysanitised[0],$daysanitised[1],$daysanitised[2],$daysanitised[3],$daysanitised[4],$daysanitised[5],$daysanitised[6]))or die(odbc_error($connection));
$query = "SELECT ...
INTO ##daysinperiod
FROM [RISSxplr].[dbo].[Dim_date]
WHERE (FULL_DAY_DT BETWEEN ? AND ?)
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (?,?,?,?,?,?,?)";
$result = odbc_prepare($connection, $query);
odbc_execute($result, array($date_s,$date_e,$daysanitised[0],$daysanitised[1],$daysanitised[2],$daysanitised[3],$daysanitised[4],$daysanitised[5],$daysanitised[6]))or die(odbc_error($connection));
$query = "SELECT ...
FROM ##avgspeedperlink, ##daysinperiod
ORDER BY LKNO, OUTBOUND
drop table ##avgspeedperlink
drop table ##daysinperiod";
Note that I had to use double ## for making the temporary tables (single # means that table is local to the query, ## means that the temporary table becomes global for multiple queries).

union in codeigniter my sql error

acutally i want get search with multi field so i decided to union query and i write my code following
$this->db->select("id, title, job_type");
$this->db->distinct();
$this->db->from("jobs");
$this->db->like('title',$keyword);
$this->db->get();
$query1 = $this->db->last_query();
$this->db->select("company");
$this->db->distinct();
$this->db->from("employers");
$this->db->join('jobs', 'jobs.userId = employers.userId');
$this->db->or_like('company',$company_name);
$this->db->get();
$query2 = $this->db->last_query();
$query = $this->db->query($query1." UNION ".$query2);
return $query->result();
as above code produce following sql query semes like bellow
SELECT DISTINCT `id`, `title`, `job_type` FROM (`jobs`) WHERE `title`
LIKE '%dfsdf%' UNION SELECT DISTINCT `company` FROM (`employers`) JOIN
`jobs` ON `jobs`.`userId` = `employers`.`userId` WHERE `company` LIKE '%%'
and it shows following error
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'JOIN jobs ON jobs.userId = employers.userId WHERE
company LIKE '%%' at line 5
can anyone help me
First of all, in order to use union the no. of columns and their data types should match in both the queries.
You are trying to do a union between a query which selects three columns with another query which only one column. This will not work.
To know more about mysql unions, you can go through the below link
http://dev.mysql.com/doc/refman/5.0/en/union.html

Getting values from different tables in mysql query (practical example)

I have two tables: first and second
this and that are primary keys, common and always present on both tables, so I guess there is no need of left joins
$query = "SELECT
first.one,first.going,first.what,first.ever,second.another,second.outre,second.oneplus,second.more,second.anotherthing,second.alldifferent
WHERE second.THIS = first.THAT AND first.is = '1' AND
first.yet = '$variable' AND second.againe = '1'";
The error is the following
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE second.THIS = first.THAT AND first.is = '1' AND first.y' at line 1
But I can't get to understand why this happens.
Any help on this one? Ty very much
You need to specify a table name.
$query = "SELECT first.one, ... ,second.alldifferent WHERE ...";
Should be
$query = "SELECT first.one, ... ,second.alldifferent FROM first, second WHERE ...";

Mysql query for using count on a view in php

I have a query:
$result = mysql_query("CREATE VIEW temporary(IngList) AS (
SELECT DISTINCT (r1.Ingredient)
FROM recipes r1,
recipes r2
WHERE r1.Country = '$temp'
AND r2.Country = '$temp2'
AND r1.Ingredient = r2.Ingredient)
SELECT COUNT(*) FROM temporary");
I want the query to make a view called temporary and have it return a count of the number of rows in the view temporary. I know this code works without the SELECT COUNT(*) because I checked my database and the view is created.
Yet this code throws the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT COUNT(*) FROM temporary' at line 1
I checked the syntax and it seems to be correct. What seems to be the problem because its quite frustrating.
From the mysql_query documentation:
mysql_query() sends a unique query (multiple queries are not supported)...
You can't create the view, and select from it in a single mysql_query. The view is unnecessary:
$sql = sprintf("SELECT COUNT(DISTINCT r1.Ingredient)
FROM recipes r1
WHERE r.country = '%s'
AND EXISTS(SELECT NULL
FROM recipes r2
WHERE r2.Country = '%s'
AND r1.Ingredient = r2.Ingredient)",
$temp, $temp2);
$result = mysql_query($sql);
For starters you have two statements. What you're writing looks more like a stored procedure. Even if it worked, you would need a semicolon at the end of the first statement. And another statement somewhere saying "DROP VIEW ...." when you are done.
And a temp view is a bit of a non sequitur. I can't find any reference to "CREATE VIEW temporary". Or maybe it's to create a view named temporary with an argument? Views don't take arguments.
I think you might get what you want with a semi-simple SQL statement something like:
$result = mysql_query(
"SELECT COUNT(DISTINCT r1.Ingredient)
FROM recipes r1
JOIN recipes r2 ON r1.Ingredient = r2.Ingredient
WHERE r1.Country = '$temp'
AND r2.Country = '$temp2'");

Categories