Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'd like to know what is the best approach to retain variables between multiple queries and echo them out in the last query. My current logic is to nest the queries, like the example below.

I heard that nesting slows down a program, and that it's unnecessarily verbose, and bad practise in general. I heard about "join" and "left join" but I've no idea how to apply it in an example or how to convert something like the following code into a "join" statement.
Can anybody tell me how to re-construct my code using best practises?

What I have tried:

PHP
/*First SQL query:*/
	$sql1 = "SELECT * FROM (select * from my_table WHERE id < $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
	$result1 = mysqli_query($conn, $sql1);
	$resultCheck1 = mysqli_num_rows($result1);
	if ($resultCheck1 > 0) {
		while ($row1 = mysqli_fetch_assoc($result1)) {
			$sum1 = $row1['sum'];
			/*Second SQL query:*/
			$sql2 = "SELECT * FROM (select * from my_table WHERE id = $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
			$result2 = mysqli_query($conn, $sql2);
			$resultCheck2 = mysqli_num_rows($result2);
			if ($resultCheck2 > 0) {
				while ($row2 = mysqli_fetch_assoc($result2)) {
					$sum2 = $row2['sum'];
					/*Third SQL query:*/
					$sql3 = "SELECT * FROM new_table"; /*Different table*/
					$result3 = mysqli_query($conn, $sql3);
					$resultCheck3 = mysqli_num_rows($result3);
					if ($resultCheck3 > 0) {
						while ($row3 = mysqli_fetch_assoc($result3)) {
							$sum3 = $row3['sum'];
							echo $sum1 + $sum2 + $sum3;
						}
					}
				}
			}
		}
	}
Posted
Updated 8-Sep-18 5:11am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900