SQL CASE WHEN STATEMENt into PHP VARIABLE - php

I have that problem:
I have SQL Statement:
SELECT Amount FROM cicmpy
INNER JOIN (SELECT DealerCode, sum(Amount) as Amount FROM
(SELECT DealerCode, LOG as LogtLimit,TemporaryCreditLimit as TemporaryCreditLimit,
CASE WHEN TemporaryCreditLimit>0 then TemporaryCreditLimit ELSE LOG END as Amount
FROM LOG_DATA WHERE Status = 1 group by DealerCode) x
on x.DealerCode=debcode where debnr is not NULL and ltrim(debcode) = '21021287'`
and I want this statement into php $query variable.

try like this,it will solve your error.
$sql = "Put your query"; //put your query in php variable
$result = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
do stuff...
}
For More Reference

Related

Php -MySQL query failing - error Fatal error: Uncaught Error: Call to a member function fetch_assoc() on boolean

I have following php code :
<?php
$connect = mysqli_connect("localhost","root", "","archit") or die("Couldn't connect to database");
$str = "SET #id := (SELECT ID FROM users where Name ='$u_name'); SELECT UID FROM useratt where ID = '#id';";
echo $str;
$query12 = mysqli_multi_query($connect,$str);
echo $query12;
while($row = $query12->fetch_assoc())
{
$str1 = "SET #UID := '".$row."';
SELECT AttributeValue FROM att_value where UID=#UID;
SET #AID := (SELECT AID FROM att_value WHERE UID=#UID);
SELECT AttributeName FROM att_name WHERE AID=#AID;";
echo $str1;
$query1= mysqli_multi_query($connect,$str1);
echo $row[0];
}
?>
I get the generic error but when I run the same code on MySQL then it works without error. Can someone please help me what am I missing .
I even tried exception handling but it didn't help.
NOTE : code fails in the while loop condition.
The mysqli_multi_query() executes one or multiple queries which are concatenated by a semicolon.To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().mysqli_multi_query() only returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.
if (mysqli_multi_query($connect,$str))
{
do
{
if ($result=mysqli_store_result($connect)) {
while ($row=mysqli_fetch_row($result))
{
$str1 = "SET #UID := '".$row."';
SELECT AttributeValue FROM att_value where UID=#UID;
SET #AID := (SELECT AID FROM att_value WHERE UID=#UID);
SELECT AttributeName FROM att_name WHERE AID=#AID;";
echo $str1;
$query1= mysqli_multi_query($connect,$str1);
echo $row[0];
}
mysqli_free_result($result);
}
}
while (mysqli_next_result($connect));
}
A. The first problem is your SELECT, you write:
SELECT UID FROM useratt where ID = '#id';
You must remove the quote at #id variable to this:
SELECT UID FROM useratt where ID = #id;
B. After mysqli_multi_query execute, you must add two others call to get result:
Your query will return two result, first result is for set variable. And the second is that your data query. Thus, we next to move next to second result to get data:
mysqli_next_result($connect);
After move next to second result, we must get result using mysqli_store_result:
$query12 = mysqli_store_result($connect);
Hope this can help you!
<?php
$connect = mysqli_connect("localhost","root", "","archit") or die("Couldn't connect to database");
$str = "SET #id := (SELECT ID FROM users where Name ='$u_name'); SELECT UID FROM useratt where ID = '#id';";
echo $str;
$query12 = mysqli_multi_query($connect,$str);
echo $query12;
while($row = mysqli_fetch_assoc($query12))
{
$str1 = "SET #UID := '".$row."';
SELECT AttributeValue FROM att_value where UID=#UID;
SET #AID := (SELECT AID FROM att_value WHERE UID=#UID);
SELECT AttributeName FROM att_name WHERE AID=#AID;";
echo $str1;
$query1= mysqli_multi_query($connect,$str1);
echo $row[0];
}
?>

PHP/SQL Query - Inserting a Variable Inside a String Variable

Trying to insert a variable inside a string variable that will be used as a query.
$staffID = $_GET["staffID"];
$conn = mysqli_connect("localhost", "twa095", "twa095de", "factory095");
if ( !$conn )
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT staffName, orderID, orderDate, shippingDate
FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID
WHERE staffID = $staffID // Problem is over here.
GROUP BY orderDate"
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
?>
Getting this as error:
Problem with queryColumn 'staffID' in where clause is ambiguous
Also, is there a way I can have it check whether the given "staffID" (first line) is inside the database and if it isn't to terminate the script and display an error message before everything below it executes?
Actually staffID is present in both joined tables (purchase and staff). Mysql is confused either staffID is from purchase table or staff table. To resolve your problem add tablename. to the staffID in where clause of your query as:
$sql = "SELECT staffName, orderID, orderDate, shippingDate
FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID
WHERE staff.staffID = '{$staffID}' // Problem is over here.
GROUP BY orderDate"
Also as a best practice add {} around the variable inside another
string and single quotes in case variable is empty it will work fine.
Secondly, For checking if staff id is already in table and returning error you have to use mysqli_num_rows() inside the if clause and print error message to user as:
$sql = "SELECT staffName, orderID, orderDate, shippingDate
FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID
WHERE staff.staffID = $staffID // Problem is over here.
GROUP BY orderDate"
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
if(mysqli_num_rows($conn,$result)>0){
echo "Error Message";
exit;
}
You probably need single quotes around your variable name in your query:
WHERE staff.staffID = $staffID // Problem is over here.
Should change to:
WHERE staff.staffID = '$staffID'

PHP update table data based on other table

I am trying to create a cron job that will select the sum of points from a transaction table.
Based on the Sum of the points and the employee id I must update the total point table.
I want to make sure that I am using the best method and that this will work.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT ID, SUM(POINTS) as Points, FROM Transactions WHERE Status = 1 Group By ID";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
mysql_query("UPDATE Totals SET Points=" + $row["Points"] + "WHERE ID=" + $row["id"]);
}
mysql_free_result($result);
?>
You can still join tables (and subqueries) on UPDATE statements. Try this one,
UPDATE Totals a
INNER JOIN
(
SELECT ID, SUM(POINTS) as Points,
FROM Transactions
WHERE Status = 1
Group By ID
) b
ON a.ID = b.ID
SET a.Points = b.Points
Hope this helps.
example of using PDO Extension (Code Snippet).
<?php
$query = "UPDATE Totals a
INNER JOIN
(
SELECT ID, SUM(POINTS) as Points,
FROM Transactions
WHERE Status = ?
Group By ID
) b
ON a.ID = b.ID
SET a.Points = b.Points";
$iStatus = 1;
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $iStatus);
$stmt->execute();
?>
PDO Manual
PDO PreparedStatement
Why can't you just test the script out out before you run it via a cron job? I can't spot anything that's wrong with the syntax; but then again, I only gave it a quick glance and I don't know what your table structure is like.
If you're looking for the BEST way to do things, then you should looking into using mysqli or PDO instead of the mysql functions. That way, you can make use of prepared statements, which won't be as taxing on your DBMS if you're planning on running multiple queries inside a loop. Prepared statements don't require you to make separate round trips to the server, whereas the old mysql functions do.

Printing result of mysql query from variable

So I wrote this earlier (in php), but everytime I try echo $test", I just get back resource id 5. Does anyone know how to actually print out the mysql query from the variable?
$dave= mysql_query("SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)") or die(mysql_error());
print $dave;
This will print out the query:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
print $query;
This will print out the results:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($dave)){
foreach($row as $cname => $cvalue){
print "$cname: $cvalue\t";
}
print "\r\n";
}
well you are returning an array of items from the database. so you need something like this.
$dave= mysql_query("SELECT order_date, no_of_items, shipping_charge,
SUM(total_order_amount) as test FROM `orders`
WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)")
or die(mysql_error());
while ($row = mysql_fetch_assoc($dave)) {
echo $row['order_date'];
echo $row['no_of_items'];
echo $row['shipping_charge'];
echo $row['test '];
}
From php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(),
and other functions for dealing with result tables, to access the
returned data.
http://php.net/manual/en/function.mysql-query.php
$sql = "SELECT * FROM table_name ORDER BY ID DESC LIMIT 1";
$records = mysql_query($sql);
you can change
LIMIT 1
to
LIMIT any number you want
This will show you the last INSERTED row first.

MySQL query WHERE statement which is a query itself?

So I'll try to clearly explain my goal first:
First, I want to query one table in my database for a list of usernames.
Second, I want to take those usernames, and query another table in the database and return only the rows in which these usernames appear in the username field.
Finally, I want to take this output (in JSON array form right now), and return it to the requesting client.
My query looks like this right now:
$query = mysql_query("SELECT * FROM tagusers WHERE username =
(SELECT userA FROM friendtable WHERE userB = '$username')");
This works when the WHERE statement yields 1 result. So if I only get one returned userA, it works fine. But if I get multiple, I get a bunch of errors.
Here is the code in its entirety:
if (isset($_POST['username'])) {
$username = $_POST['username'];
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("TagDB");
$query = mysql_query("SELECT * FROM tagusers WHERE username =
(SELECT userA FROM friendtable WHERE userB = '$username')");
}
while ($e = mysql_fetch_assoc($query)) {
$output[] = $e;
}
$output = json_encode($output);
print $output;
I get the following error on the query line:
*Warning: mysql_query() [function.mysql-query]: Unable to save result set in C:\wamp\www\tag\appgetfriendinfo.php on line 21*
So all I really need to know is, how would I write that query in MySQL so that I get returned an array of rows?
You don't need a subquery at all, you'll usually get better performance out of a join. Make sure you have indexes defined on tagusers.username, friendtable.userA and friendtable.userB
SELECT
tagusers.*
FROM
tagusers
INNER JOIN
friendtable
ON
tagusers.username = friendtable.userA
AND
friendtable.userB = '$username'
Use the IN keyword.
$query = mysql_query("SELECT * FROM tagusers WHERE username IN
(SELECT userA FROM friendtable WHERE userB = '$username')");
Use either the IN clause, or a JOIN like in this example:
$query = sprintf("SELECT tu.*
FROM TAGUSERS tu
JOIN FRIENDTABLE ft ON ft.usera = tu.username
WHERE ft.userB = '%s'",
mysql_real_escape_string($_POST['username']));
$result = mysql_query($query);
$output = json_encode($result);

Categories