Dynamic query for high charts - php

I was using highcharts - stacked column charts. I tried to create a dynamic query.
$query = mysql_query("SELECT * FROM products WHERE productid IN ".$full);
This was the query and the $full is defined as:
$que1 = mysql_query("SELECT productid from admin_levels WHERE level>1 AND userid=$UserID ORDER BY productid");
$op1="";
while($row1 = mysql_fetch_row($que1))
{
foreach($row1 as $cell1)
{
$op1.="'".$cell1."',";
}
}
$temp1=strlen($op1)-1;
$op1=substr($op1,0,$temp1);
$full = "( ".$op1." )";

You can call the above queries in a single query like this:
$query = mysql_query("SELECT * FROM products WHERE productid IN (SELECT productid from admin_levels WHERE level>1 AND userid=$UserID ORDER BY productid)") or die(mysql_error()) ;
I will suggest you not to use mysql statements because these are vulnerable. Instead of this you please try mysqli or PDO statements

Related

Get results and use them to another query mysql php

How can I use the fetched result to use the values to make another query? I tried to find info on php.net, but can`t figure out.
$sql = "SELECT id FROM orders WHERE customer_id=$customer_id";
$query = mysqli_query($conn, $sql);
while($row= mysqli_fetch_array($query)) {
$ordersid=$row['id'];
}
$ordersid returns: 13 - order number 1 and 3.
Here is my difficulty. How can I make $orderid(1,3)?
After that I want to use 1 and 3 like that in another query:
SELECT * FROM orderdetails WHERE order_id IN ($orderid)
In that way without direct relation will have all answers from the first query to second.
Where is my mistake?
You could put the results into an array and use like follows:
$a = array();
$sql = "SELECT id FROM orders WHERE customer_id=$customer_id";
$query = mysqli_query($conn, $sql);
while($row= mysqli_fetch_array($query)) {
array_push($a, $row['id']);
}
$data = implode("', '", $a);
And in your next query like so:
SELECT * FROM orderdetails WHERE order_id IN ('$data')

Error creating SQL statement

I made the following code to try and grab the number of entries in 3 tables in a database. The queries work when I use them in phpMyAdmin but when I run this code I get:
Error creating SQL statement
which is generated by the if(!$stmt) statement and I have no idea why it's not working. Thanks in advance :)
<?php
include 'connection.php';
$countArtists = $countAlbums = $countTracks = 0;
/* Create queries to get counts from each table */
$sql = "SELECT COUNT(*) FROM artist;";
$sql .= "SELECT COUNT(*) FROM cd;";
$sql .= "SELECT COUNT(*) FROM tracks;";
$stmt = $conn->prepare($sql);
if(!$stmt)
{
echo "Error creating SQL statement";
return 1;
}
$stmt->execute();
$stmt->bind_result($countArtists, $countAlbums, $countTracks);
echo "<li>Number of Artists: $countArtists</li><br>\n" .
"<li>Number of Albums: $countAlbums</li><br>\n" .
"<li>Number of Tracks: $countTracks</li><br>\n";
?>
I think you want a single query like this:
$sql = "SELECT (SELECT COUNT(*) FROM artist) as countArtists, ".
"(SELECT COUNT(*) FROM cd) as countAlbums, ".
"(SELECT COUNT(*) FROM tracks) as countTracks";
This is one query with three columns, as opposed to three separate queries.

PHP PDO dynamic WHERE clause

I have a simple function that returns a count from a database table, based on some criteria.
function MyCount($strTable, $strCriteria) {
$strSQL = "SELECT COUNT(*) FROM " . $strTable . " ";
if (trim($strCriteria) != "") $strSQL .= "WHERE " . $strCriteria;
$results = mysql_query($strSQL, $objConn);
$row = mysql_fetch_array($results);
return $row[0];
}
Its very useful for quickly getting a value in 1 line of code, e.g:
$Users = MyCount("Users", "Deleted = 0");
However, I'm now trying to move to PDO and am having trouble passing in the were as parametrized values. I'm trying to do something like the below (which doesn't work):
$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE :criteria");
$objQuery->bindParam(':table_name', $strTable);
$objQuery->bindParam(':criteria', $strCriteria);
I guess the obvious would be:
$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE ".$strCriteria");
$objQuery->bindParam(':table_name', $strTable);
But, this seems to go against the spirit of parametrized values... does anyone have any other suggestions?
Thanks
This line is the issue:
$objQuery->bindParam(':table_name', $strTable);
You can only bind values ( field= :value) in PDO you cannot bind table names or column names or custom dynamic where clause.
So you just build the query manually:
SELECT count(*) as TheCount FROM `$strTable` WHERE $strCriteria
function my_count($strTable, $strCriteria, $objConn)
{
$sql ="SELECT count(*) as TheCount FROM $strTable WHERE $strCriteria";
$objQuery=$objConn->query($sql);
$row =$objQuery->fetch();
return $row['TheCount'];
}
$Users = my_count("Users", "Deleted = 0", $objConn);

how can i use two mysql query with user defined variable in php

select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
This query works in mysql console
but
$query = "
select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
";
$result = mysql_query($query);
this code raise error in php
so, I tried this
$query="
select * from ct_product, (select #min_price:=min(prd_sale_price),#max_price:=max (prd_sale_price) from ct_product) as b
where prd_sale_price=#min_price or prd_sale_price=#max_price
";
$result = mysql_query($query);
that works
...
$query = "
select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
";
$result = mysql_query($query);
What's the way that this code would work well without modification as my second way?
Use two calls to mysql_query:
$query1 = "select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product";
$query2 = "select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price";
mysql_query($query1);
mysql_query($query2);
Variables are associated with a database connection, so they'll persist between the calls.
in PHP mysql_query() can handle only one query at a time
You can't make this method handle 2 query at the same time
what I can suggest is using mysql_query() for every query

Using a php array in a mysql query

I'm querying one database to get product stockcodes related to a news article
$result = mysql_query('
SELECT stockcode FROM news_related WHERE news = "'.$news_id.'"');
then I need to use the data taken from the stockcode column to query a second database. I'm using
$rows = mysql_fetch_array($result);
to put the info in to an array. How do I use that array in the second mysql query?
$also_result = mysql_query("SELECT * FROM WebProducts
WHERE WebProducts.stockcode THE ARRAY GOES HERE AND WebProducts.visible='Y'") or die(mysql_error());`**
Sounds like a simple join for me.
mysql_query("SELECT * FROM WebProducts p
JOIN news_related n
ON p.stockcode = n.stockcode
WHERE n.news = " . $news_id . "
AND p.visible='Y'");
Tr in a single query like,
$result = mysql_query('SELECT * FROM WebProducts WHERE WebProducts.stockcode IN
(SELECT stockcode FROM news_related WHERE news = "'.$news_id.'"
AND WebProducts.visible="Y")');
From your approach it should be like,
$arrStock=array();
while($rows = mysql_fetch_array($result))
{
$arrStock[]=$rows['stockcode'];
}
if(!empty($arrStock))
{
$also_result=mysql_query("SELECT * FROM WebProducts WHERE WebProducts.stockcode
IN (".implode(',',$arrStock)." AND WebProducts.visible='Y'");
}
You know about the second parameter in mysql_query() which is connection identifier, in your case there are two databases so you should have 2 connections like $con1 and $con2
$result = mysql_query('SELECT * FROM WebProducts WHERE WebProducts.stockcode IN
(SELECT stockcode FROM news_related WHERE news = "'.$news_id.'"
AND WebProducts.visible="Y")',$con1);// use $con1 for first db
and in the second query
$also_result=mysql_query("SELECT * FROM WebProducts WHERE WebProducts.stockcode
IN (".implode(',',$arrStock)." AND WebProducts.visible='Y'",$con2);
// use $con2 for second db
Also the mysql_ is deprecated and will removed in the upcoming versions of PHP so use mysqli_*

Categories