Empty mysql_query, can't figure it out - mysql

I'm having trouble with making this query to work, I have 2 tables one with client info and the other one with product info. Trying to join them while querying the db.
mysql_query(
"SELECT client.id, client.email, client.prodid, prod.id, prod.name
FROM client, prod
WHERE client.id ="'.mysql_real_escape_string($_GET["id"]).'"
AND client.prodid =prod.id"
);
But that query doesn't return anything. What am I doing wrong? Thanks in advance.

Your quotes are wrong.
You use " to start the string in your method. In the middle you use "'.mysql_real_escape_string($_GET["id"]).'". Notice that you use "' instead of '".
This should work better (from a PHP point of view, I did not check your SQL syntax):
mysql_query(
"SELECT client.id, client.email, client.prodid, prod.id, prod.name
FROM client, prod
WHERE client.id ='".mysql_real_escape_string($_GET["id"])."'
AND client.prodid =prod.id"
);

Your quotes appear to be cancelling out the dynamic ID variable. If your client.id field is numeric, then you should remove the single quotes surrounding mysql_real_escape_string():
mysql_query(
"SELECT client.id, client.email, client.prodid, prod.id, prod.name
FROM client, prod
WHERE client.id = ".mysql_real_escape_string($_GET["id"])." AND client.prodid = prod.id"
);
If it works in PHPMyAdmin then the query's fine. Enable debugging and use var_dump():
ini_set('display_errors','on');
error_reporting(E_ALL);
$result = mysql_query($sql_query);
var_dump($result);

Related

JOIN two SELECTs with Doctrine

I need to write this query with Doctrine. How can I write it down using QueryBuilder?
SELECT charges.id, charges.currency, charges.total_transactions,
charges.total_volume, charges.commission, refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds
ON charges.id = refunds.id AND charges.currency = refunds.currency
You can use Native SQL and map results to entities:
use Doctrine\ORM\Query\ResultSetMapping;
$rsm = new ResultSetMapping;
$rsm->addEntityResult('AppBundle:Charges', 'charges')
->addEntityResult('AppBundle:Refunds', 'refunds')
->addFieldResult('charges', 'id', 'id')
->addFieldResult('charges', 'currency', 'currency')
->addFieldResult('charges', 'total_transactions', 'total_transactions')
->addFieldResult('charges', 'total_volume', 'total_volume')
->addFieldResult('charges', 'commission', 'commission')
->addFieldResult('refunds', 'total_payouts', 'total_payouts')
;
$sql = "
SELECT
charges.id,
charges.currency,
charges.total_transactions,
charges.total_volume,
charges.commission,
refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds ON charges.id = refunds.id AND charges.currency = refunds.currency
WHERE some_field = ?
";
$query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
$query->setParameter(1, $name);
$entities = $query->getResult();
You can use DQL like this:
$dql = "SELECT ...";
$q = $entityManager->createQuery($dql)->setParameters($arrayParameters);
$result = $q->execute();
or QueryBuilder for each sub-query, like:
// subquery 1
$subQuery1 = $entityManager->createQueryBuilder()
->select('...')
->from('...')
->getDQL()
;
// subquery 2
$subQuery2 = ...
// etc
// ...
// main query
$query = $entityManager->createQueryBuilder()
->select('...')
->from('...', $subQuery1)
->leftJoin('...', $subQuery1->getDQL()),
->where()
;
PS: I just try provide gist for you... hope now you have clue...
Now I found out that it's impossible.
Comment created by stof:
DQL is about querying objects. Supporting subselects in the FROM clause means that the DQL parser is not able to build the result set mapping anymore (as the fields returned by the subquery may not match the object anymore).
This is why it cannot be supported (supporting it only for the case you run the query without the hydration is a no-go IMO as it would mean that the query parsing needs to be dependant of the execution mode).
In your case, the best solution is probably to run a SQL query instead (as you are getting a scalar, you don't need the ORM hydration anyway)
Source: https://github.com/doctrine/doctrine2/issues/3542

MYSQL about variables

$sql = "SELECT COUNT(ID) AS total
FROM ".$datatable."
WHERE STATE=".$category ;
Im trying to figure out why this isnt working.
$sql = "SELECT COUNT(ID) AS total
FROM ".$datatable."
WHERE STATE='AL'" ;
this one hwoever works. Im unsure of what concactinate or " ' syntax issue it is.
You need to include single quotation marks for the where statement. Also, since you're using double quotes you don't actually need to escape from the string to include the PHP variables.
$sql = "SELECT COUNT(ID) AS total FROM $datatable WHERE STATE='$category'";

yii2 : remove comma from createCommand

i've create a Command in my controller like this :
public function actionTotal($id)
{
$query1 = new Query;
$query1 ->select('sum(patient_services.price) price, sum(receipts.price) receipts ,')
->from('patient_services ')
->leftJoin(' receipts ON patient_services.patient_id=receipts.patient_id')
->where('patient_services.patient_id=:id', array(':id'=>$id));
$command1 = $query1->createCommand();
$price = $command1->queryAll();
echo Json::encode($price);
}
when i try it ... the select code have a comma and idon't know how to remove it
SELECT sum(patient_services.price) price, sum(receipts.price) receipts FROM `patient_services` LEFT JOIN ` receipts ON` `patient_services`.`patient_id=receipts`.`patient_id` WHERE patient_services.patient_id=1
when i remove all commas from the sql code and try it in phpmyadmin .. it works fine :(
You have an invalid leftJoin replace it with this:
->leftJoin('receipts', 'patient_services.patient_id = receipts.patient_id')
also it seems you have an extra comma at the end of your select query remove that last comma the select query would look like this:
$query1 ->select('sum(patient_services.price) price, sum(receipts.price) receipts')
Hope this works.

Convert SQL query to yii2?

Until now I have been using a SQL query in yii2 which was working fine locally but as soon as I deploy it to the server it shows
I have tried changing it to yii query since its a proper implementation below
$query = $connection->createCommand("SELECT a.name_of_flight, a.time_of_flight, (a.no_of_passenger - b.cnt) as avail, a.no_of_passenger FROM flight_schedule a LEFT JOIN (SELECT flight_time, COUNT(id) AS cnt FROM book_eticket WHERE flight_date='$date' AND company_name = '$comp_name' GROUP BY flight_time) b ON a.id = b.flight_time")->queryAll();
to
$query = (new \yii\db\Query());
$query
->select('a.name_of_flight, a.time_of_flight, (a.no_of_passenger - b.cnt) as avail, a.no_of_passenger')
->from('flight_schedule a')
->leftJoin('flight_time', ('COUNT(id) AS cnt FROM book_eticket'))
->where(array('and', 'flight_date=2016-6-29', 'company_name = Team5'))
->groupBy(['flight_time b','ON a.id = b.flight_time']);
$command = $query->createCommand();
$query = $command->queryAll();
but I get an error:
Can anybody help me find out the problem? Thanks in advance
First screen says about access issues. Second - that operands like date and team is not string. That is wrong. Can you quote them?

MySQL join on 2 tables

I need to do a search on 2 simultaneous tables, and I thought that this join would work but its giving me an incorrect syntax error.
$return_arr = array();
$query = mysql_query("SELECT * FROM clients WHERE lastname LIKE '$q%' AND agencyid = '$agencyid'
UNION
SELECT * FROM busclients WHERE busname LIKE '$q%' AND agencyid = '$agencyid'")or die(mysql_error());
if($query) {
while ($result = mysql_fetch_array($query)) {
if(isset($result['busname'])){
$description['id'] = $result['ID'];
$description['value'] = $result['busname'] ;
array_push($return_arr,$description);
}
else
{
$description['id'] = $result['ID'];
$description['value'] = $result['lastname'] . ", " . $result['firstname'] ;
array_push($return_arr,$description);
}
}
}
echo json_encode($return_arr);
Edited with fix suggested below and entire syntax
This is a query from an autocomplete search box. So when someone types in a client or business client name, it uses this query to search the database and then displays the results using jquery.
The fix below works but when I do a search on a business client it is returning []. A client search works fine.
You could use two seperate query's and join them together like so:
SELECT * FROM clients
WHERE lastname LIKE "%agencyid%"
UNION
SELECT * FROM busclients
WHERE busname LIKE "%$agencyid%";
You sql syntax shoul look like this :
SELECT * FROM clients c
inner join
busclients b
on c.agencyid=b.idbus
WHERE (c.lastname and b.busname LIKE '$q%') AND c.agencyid = '$agencyid'
Just to complete the circle make sure you read this article on how to join tables in mysql