MySQL - A query based on another query - php

I write a lot of queries resembling the query example code below. I was wondering whether there was a more efficient code/script?
$query1 ="SELECT * FROM table1 WHERE date >= '$todaysdate' ";
$result1 = mysql_query($query1)
or die ("Error in query: $query1. " . mysql_error());
if (mysql_num_rows($result1) > 0) {
while($row1 = mysql_fetch_object($result1)) {
echo "$row1-date";
$query2 ="SELECT * FROM table2 WHERE table1ID >= '$row1-table1ID' ";
$result2 = mysql_query($query2)
or die ("Error in query: $query2. " . mysql_error());
if (mysql_num_rows($result2) > 0) {
while($row2 = mysql_fetch_object($result2)) {
echo "$row->datatable2";
}
}
}
}

Try using SQL JOINs, like the following example:
SELECT
*
FROM
table1
INNER JOIN
table2 ON (table2.table1ID = table1.ID)
WHERE
table1.date >= '2009-12-20';

I don't know about the structure of your tables, but I've modified your code so that it uses a join:
$query = 'SELECT table1.date, table2.datatable2 FROM table1, table2 WHERE table1.date >= \''.$todaysdate.'\' AND table2.table1ID >= table1.table1ID';
$result = mysql_query($query)
or exit('Error in query: '.$query.' '.mysql_error());
if (mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_object($result))
{
echo $row->date;
echo $row->datatable2;
}
}
In this case you select multiple tables with FROM separated with commas, but you can also use INNER/OUTER/LEFT/RIGHT JOIN (see the link in the first answer).

You can use PDO.
Your queries should look like this..
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_COLUMN);
// OR
$result = $sth->fetchAll(PDO::FETCH_OBJ);
var_dump($result);
PDO MANUAL: http://php.net/manual/en/book.pdo.php

Related

Php array: How to use different values for a query

I have this code:
$sql='SELECT id FROM table1 WHERE "'.$date.'"=Date';
$result = mysqli_query($connect, $sql) or die(mysqli_error($connect));;
while($row = mysqli_fetch_array($result)){
$c=$row['id'];
}
This returns more than 1 value. How can i use the different values for another query?
Ex:
$sql2='SELECT name FROM TABLE2 WHERE name="'.$c.'" ';
PS: i know the code is not good
Is this what you mean? Not 100% sure but hope it helps ...
$sql='SELECT id FROM table1 WHERE Date = '.$date;
$result = mysqli_query($connect, $sql) or die(mysqli_error($connect));;
while($row = mysqli_fetch_array($result)){
$sql2='SELECT name FROM TABLE2 WHERE name="'.$row['id'].'" ';
$sub_result = mysqli_query($connect, $sql2) or die(mysqli_error($connect));
}
I m not sure if this s what you need but here we go:
$sql='SELECT id FROM table1 WHERE Date="'.$date.'"';
$result = mysqli_query($connect, $sql) or die(mysqli_error($connect));;
while($row = mysqli_fetch_array($result)){
$c=$row['id'];
$sql2='SELECT name FROM TABLE2 WHERE name="'.$c.'" ';
//DO SOMETHING HERE
}
Or with LEFT JOIN
$sql='SELECT table1.something, TABLE2.something2
FROM table1
LEFT JOIN TABLE2
ON table1.id=TABLE2.name
WHERE table1.Date="'.$date.'"';
$result = mysqli_query($connect, $sql) or die(mysqli_error($connect));;
while($row = mysqli_fetch_array($result)){
//DO SOMETHING HERE
}

PHP SQL INSERT INTO statement not working directly after table creation [duplicate]

<?php
$query1 = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X";
$query2 = "CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)";
$query3 = "CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank as current_rank LEFT JOIN previous_rankings.rank as prev_rank
ON (current_rankings.player = previous_rankings.player)";
$query4 = "SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
$result = mysql_query($query4) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['player']. $row['current_rank']. $row['prev_rank']. $row['rank_change'];
}
?>
All the queries work independently but am really struggling putting all the pieces together in one single result so I can use it with mysql_fetch_array.
I've tried to create views as well as temporary tables but each time it either says table does not exist or return an empty fetch array loop...logic is there but syntax is messed up I think as it's the 1st time I had to deal with multiple queries I need to merge all together. Looking forward to some support. Many thanks.
Thanks to php.net I've come up with a solution : you have to use (mysqli_multi_query($link, $query)) to run multiple concatenated queries.
/* create sql connection*/
$link = mysqli_connect("server", "user", "password", "database");
$query = "SQL STATEMENTS;"; /* first query : Notice the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS"; /* last query : Notice the dot before = at the end ! */
/* Execute queries */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_array($result))
/* print your results */
{
echo $row['column1'];
echo $row['column2'];
}
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
}
EDIT - The solution above works if you really want to do one big query but it's also possible to execute as many queries as you wish and execute them separately.
$query1 = "Create temporary table A select c1 from t1";
$result1 = mysqli_query($link, $query1) or die(mysqli_error());
$query2 = "select c1 from A";
$result2 = mysqli_query($link, $query2) or die(mysqli_error());
while($row = mysqli_fetch_array($result2)) {
echo $row['c1'];
}
It seems you are not executing $query1 - $query3. You have just skipped to $query4 which won't work if the others have not been executed first.
Also
$query4 = "SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
should probably be
$query4 = "SELECT *, #rank_change := prev_rank - current_rank as rank_change from final_output";
or else the value of rank_change will just be a boolean, true if #rank_change is equal to (prev_rank - current_rank), false if it is not. But do you need #rank_change at all? Will you use it in a subsequent query? Maybe you can remove it altogether.
Even better, you could just combine all the queries into one like this:
SELECT
curr.player,
curr.rank AS current_rank,
#rank_change := prev.rank - curr.rank AS rank_change
FROM
main_table AS curr
LEFT JOIN main_table AS prev
ON curr.player = prev.player
WHERE
curr.date = X
AND prev.date = date_sub('X', INTERVAL 1 MONTH)
You should concatenate them:
<?php
$query = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X";
$query .= " CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)";
$query .= " CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank as current_rank LEFT JOIN previous_rankings.rank as prev_rank
ON (current_rankings.player = previous_rankings.player)";
$query .= " SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['player']. $row['current_rank']. $row['prev_rank']. $row['rank_change'];
}
?>

How can i use the result of one mysql query and use it in another query in php?

I am trying to get a result from on table and use this result in a query on another table. How can i pass this result as binding parameter? I am posting the required variable from android studio and receiving it in php code.
Here is my code:
<?php
$con = mysqli_connect("localhost","root","2015","testdatabase") or die("Error Connecting" . mysqli_error($link));
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$Customer = $_POST["Customer"];
$statement = mysqli_prepare($con,"SELECT id FROM Customer WHERE Customer = ?");
mysqli_stmt_bind_param($statement,"s",$Customer);
$result = mysqli_stmt_execute($statement);
if (!$result)
{
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
$statemente = mysqli_prepare($con,"SELECT * FROM comments WHERE c_id = ? ORDER BY DESC id");
mysqli_stmt_bind_param($statemente,"s",$row[0]);
$resultt=mysqli_stmt_execute($statemente);
while($roww = mysqli_fetch_assoc($resultt))
{
$output[]=$roww;
}
echo(json_encode($output));
mysqli_close($con);
?>
You can get the result by on one sql statement
SELECT c.*
FROM `Customer` u INNER JOIN `comments` c ON u.id = c.c_id
ORDER BY c.c_id DESC
or assemble the ids from $rows with implode()
$id = implode($rows, ',');
mysqli_stmt_bind_param($statemente, "s", $id);
the modified sql like below:
SELECT * FROM comments WHERE c_id in ? ORDER BY id DESC

The max value in a column with php

I have a MySql table "MyTable" with the column "order"
order
-----
3
4
2
1
I want to get the highest number. The sql statement works well inside MySql:
SELECT MAX(order) FROM MyTable"
But I do not know how to use it with php and echo it? Something like:
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$row = mysqli_fetch_array($result);
echo $row[0];
If you don't provide an alias to a MySQL function it will be shown as you've written it:
$row = mysqli_fetch_array($result);
echo $row['MAX(order)'];
What you can do is write something like:
$result = mysqli_query($con, "SELECT MAX(order) as 'max' FROM MyTable");
$row = mysqli_fetch_array($result);
echo $row['max'];
Which is using an alias.
Hope this helps!
Alternatively you can use ORDER BY DESC and Limit result to 1 this way you can easily get the maximum of an column .
$result=$con->query("SELECT order FROM MyTable ORDER BY order DESC LIMIT 1");
$row=mysqli_fetch_array($result);
echo $row['order'];
Or using MAX
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$row=mysqli_fetch_array($result);
echo $row[0];
This tutorial is directly from tizag, using the MySql Max function
MySQL Aggregate Functions - MAX()
// Make a MySQL Connection
$query = "SELECT type, MAX(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "The most expensive ". $row['type']. " is $" .$row['MAX(price)'];
echo "<br />";
}
Here's my answer:
$host = "localhost";
$username = "your_username";
$password = "your_password";
$db_name = "your_db_name";
$connection = mysql_connect($host, $username, $password) or die ("Error:: [1]");
mysql_select_db($db_name, $connection) or die ("Error:: [2]");
$query = "SELECT `order` FROM `MyTable` order by `order` desc";
$res = mysql_query($query, $connection);
$row = mysql_fetch_array($res);
print $row[0];
With this query , you always have the highest value of the give column.

php/mysql with multiple queries

<?php
$query1 = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X";
$query2 = "CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)";
$query3 = "CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank as current_rank LEFT JOIN previous_rankings.rank as prev_rank
ON (current_rankings.player = previous_rankings.player)";
$query4 = "SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
$result = mysql_query($query4) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['player']. $row['current_rank']. $row['prev_rank']. $row['rank_change'];
}
?>
All the queries work independently but am really struggling putting all the pieces together in one single result so I can use it with mysql_fetch_array.
I've tried to create views as well as temporary tables but each time it either says table does not exist or return an empty fetch array loop...logic is there but syntax is messed up I think as it's the 1st time I had to deal with multiple queries I need to merge all together. Looking forward to some support. Many thanks.
Thanks to php.net I've come up with a solution : you have to use (mysqli_multi_query($link, $query)) to run multiple concatenated queries.
/* create sql connection*/
$link = mysqli_connect("server", "user", "password", "database");
$query = "SQL STATEMENTS;"; /* first query : Notice the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS"; /* last query : Notice the dot before = at the end ! */
/* Execute queries */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_array($result))
/* print your results */
{
echo $row['column1'];
echo $row['column2'];
}
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
}
EDIT - The solution above works if you really want to do one big query but it's also possible to execute as many queries as you wish and execute them separately.
$query1 = "Create temporary table A select c1 from t1";
$result1 = mysqli_query($link, $query1) or die(mysqli_error());
$query2 = "select c1 from A";
$result2 = mysqli_query($link, $query2) or die(mysqli_error());
while($row = mysqli_fetch_array($result2)) {
echo $row['c1'];
}
It seems you are not executing $query1 - $query3. You have just skipped to $query4 which won't work if the others have not been executed first.
Also
$query4 = "SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
should probably be
$query4 = "SELECT *, #rank_change := prev_rank - current_rank as rank_change from final_output";
or else the value of rank_change will just be a boolean, true if #rank_change is equal to (prev_rank - current_rank), false if it is not. But do you need #rank_change at all? Will you use it in a subsequent query? Maybe you can remove it altogether.
Even better, you could just combine all the queries into one like this:
SELECT
curr.player,
curr.rank AS current_rank,
#rank_change := prev.rank - curr.rank AS rank_change
FROM
main_table AS curr
LEFT JOIN main_table AS prev
ON curr.player = prev.player
WHERE
curr.date = X
AND prev.date = date_sub('X', INTERVAL 1 MONTH)
You should concatenate them:
<?php
$query = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X";
$query .= " CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)";
$query .= " CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank as current_rank LEFT JOIN previous_rankings.rank as prev_rank
ON (current_rankings.player = previous_rankings.player)";
$query .= " SELECT *, #rank_change = prev_rank - current_rank as rank_change from final_output";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['player']. $row['current_rank']. $row['prev_rank']. $row['rank_change'];
}
?>

Categories