PHP/MySQL Multiple Querys - php

Whoops firgured otu where my parse error was. I had my semi-colon inside my first query.
So essentially I am trying to query with three different select statements in the same PHP script. Is this possible? (Last question I promise, after this I think the basics should get me a few weeks without having to ask more)
<?php
include("server_connect.php");
mysql_select_db("rnissen");
$query = "SELECT column_one, column_two, column_four FROM tbltable;"
$results = mysql_query($query) or die(mysql_error());
$querytwo = "SELECT column_one, column_two, column_five FROM tbltable WHERE column_five = 1989";
$results = mysql_query($querytwo) or die(mysql_error());
$querythree = "SELECT COUNT(column_five) FROM tbltable WHERE column_five = 1989";
$results = mysql_query($querythree) or die(mysql_error());
?>
Part Two
Ok so I changed the code as suggested and tried to add it into a table. I'm still getting
Parse error: syntax error, unexpected '$results1' (T_VARIABLE) in C:\xampp\htdocs\3718\assign5SELECT.php on line 7
I tried it without the table and it is still the same error. Is there something I am missing? Here is the updated code with the new variables.
mysql_select_db("rnissen");
$query = "SELECT column_one, column_two, column_four FROM tbltable;"
$results1 = mysql_query($query) or die(mysql_error());
echo "Column One, Column Two, Column Four : </br>";
echo "<table border=\"1\">\n";
while ($row1 = mysql_fetch_assoc($results1)) {
echo "<tr>\n";
foreach($row1 as $value1) {
echo "<td>\n";
echo $value1;
echo "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
$querytwo = "SELECT column_one, column_two, column_five FROM tbltable WHERE column_five = 1989";
$results2 = mysql_query($querytwo) or die(mysql_error());
echo "Column One, Column Two, Column Five : </br>";
echo "<table border=\"1\">\n";
while ($row2 = mysql_fetch_assoc($results2)) {
echo "<tr>\n";
foreach($row2 as $value2) {
echo "<td>\n";
echo $value2;
echo "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
$querythree = "SELECT COUNT(column_five) FROM tbltable WHERE column_five = 1989";
$results3 = mysql_query($querythree) or die(mysql_error());
echo "Column 4 has this many 1989s : </br>";
echo "<table border=\"1\">\n";
while ($row3 = mysql_fetch_assoc($results3)) {
echo "<tr>\n";
foreach($row3 as $value3) {
echo "<td>\n";
echo $value3;
echo "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>

$query = "SELECT column_one, column_two, column_four FROM tbltable;"
$results = mysql_query($query) or die(mysql_error());
$querytwo = "SELECT column_one, column_two, column_five FROM tbltable WHERE column_five = 1989";
$results = mysql_query($querytwo) or die(mysql_error());
$querythree = "SELECT COUNT(column_five) FROM tbltable WHERE column_five = 1989";
$results = mysql_query($querythree) or die(mysql_error());
The problem you are encountering is that you are overwriting your results by using the same variable name.
Example:
$Var = "test";
echo $Var; // Will output "test"
$Var = "Another String";
echo $Var; // Will output "Another String" rather than "test";
So append:
$Results_a = ...;
$Results_b = ...;
$Results_c = ...;
So you can work with your variables easily, another thing you could look at is SQL joins: http://dev.mysql.com/doc/refman/5.0/en/join.html to cut down your amount of seperate queries

You need to save the queries to a different variable:
<?php
include("server_connect.php");
mysql_select_db("rnissen");
$query = "SELECT column_one, column_two, column_four FROM tbltable;"
$results1 = mysql_query($query) or die(mysql_error());
$querytwo = "SELECT column_one, column_two, column_five FROM tbltable WHERE column_five = 1989";
$results2 = mysql_query($querytwo) or die(mysql_error());
$querythree = "SELECT COUNT(column_five) FROM tbltable WHERE column_five = 1989";
$results3 = mysql_query($querythree) or die(mysql_error());
?>
However, this is a more convenient way to do perform multiple queries using mysqli_multi_query:
Example from the docs:
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));
}
Edit:
For your updated question, you are missing a semicolon here:
$query = "SELECT column_one, column_two, column_four FROM tbltable";

Related

Foreach inside foreach only showing one result

$con=mysqli_connect("localhost","root","","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
error_reporting(E_ALL ^ E_NOTICE);
$query = "SELECT * FROM TT_posts WHERE post_status='publish' AND
ping_status='open'";
$result = $con->query($query);
while($row1 = $result->fetch_assoc())
foreach ($result as $row1){
$image = "SELECT * FROM TT_posts WHERE post_title='$row1[post_name]'";
$result1 = $con->query($image);
while($row2 = $result1->fetch_assoc())
foreach ($result1 as $row2){
echo "<img src='".$row2[guid]."'>";
echo "<p>".$row1[post_title]."</p>";
}}
?>
actually, below query returns 8 results.
$query = "SELECT * FROM TT_posts WHERE post_status='publish' AND
ping_status='open'";
When it executed the loop, it stops at the first result. I don't know what exactly stops the code.
I think you've got your variable names mixed up. Your first while assigns a row to $row1, then your foreach refers to $result, not $row1. The variable $row1 is actually being overwritten every time it loops around the foreach.
You don't actually need either foreach:
while ($row1 = $result->fetch_assoc()) {
$image = "SELECT * FROM TT_posts WHERE post_title='$row1[post_name]'";
$result1 = $con->query($image);
while ($row2 = $result1->fetch_assoc()) {
echo "<img src='".$row2[guid]."'>";
echo "<p>".$row1[post_title]."</p>";
}
}

Php Sql get first value of Array

How can I acces first value and second value of this foreach seperatly?
foreach($database->query('SELECT id,firstname,lastname FROM `staff` WHERE categorie_bit = 1') as $resultRandom) {
}
You could do something like this from what I think you are saying:
$query = "SELECT `id`, `firstname`, `lastname` FROM `staff` WHERE `categorie_bit` = 1";
$rows = [];
while ($result = mysqli_fetch_assoc($database->query($query)))
{
$rows[] = [
"id"=>$result['id'],
"firstName"=>$result['firstname'],
"lastName"=>$result['lastname']
];
}
var_dump($rows);
<?
$query= "SELECT id,firstname,lastname FROM `staff` WHERE categorie_bit = 1";
if ($result=mysqli_query($con,$query))
{
$rowcount=mysqli_num_rows($result);
print "<table width=600 border=1>\n";
while ($get_info = mysqli_fetch_row($result)){
print "<tr>\n";
foreach ($get_info as $field)
print "\t<td>$field</td>\n";
print "</tr>\n";
}
print "</table>\n";
mysqli_close($link);
?>

SQL query not showing more than 1 row

This is the entire code the error must be in query 3 or 4. As you can see query 3 just gets info to build query 4 which should return the results.
I've got query 1 & 2 working ok which have the correct data showing.
<?php
session_start();
//printf('<pre>%s</pre>', print_r($_SESSION, true));
require('includes/config.inc.php');
require('includes/session.php');
//WORKING
DB_Connect();
$query = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'product' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result = mysql_query( $query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$hash = $row['hash'];
$foreignid = $row['foreign_id'];
$qty = $row['cnt'];
}
$query2 = "SELECT * FROM food_delivery_products WHERE food_delivery_products.id = ".$foreignid."";
$result2 = mysql_query( $query2) or die(mysql_error());
while($row = mysql_fetch_array($result2))
{
$name = $row['name'];
$description = $row['description'];
}
//---------------------------------------------------------------------------------------------------------------
$query3 = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'extra' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result3 = mysql_query( $query3)or die(mysql_error()) ;
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
}
$query4 = "SELECT * FROM food_delivery_extras WHERE food_delivery_extras.id = ".$foreignidextra."";
$result4 = mysql_query( $query4) or die(mysql_error());
while($row = mysql_fetch_array($result4))
{
$nameextra = $row['name'];
}
echo $nameextra;
echo $qtyextra;
DB_Disconnect();
//$products = implode(", ",$_SESSION['pdf_quote']['product_arr']);;
//print $products
?>
print $row; is only valid inside the loop if you want to print all of them. Otherwise it will print only the last $row. Make it
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
print $row;
}
its because you are printing the $row after the while loop gets executed
So it only prints the final result set
Use something like this instead:
$query3 = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'extra' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result3 = mysql_query( $query3) ;
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
print_r($row);
}
you can also use the var_dump($row); instead of print_r($row);
this will output all the values stored in the $row array each time the loop iterates

How to connect php to navicat with 2 tables

$i = 1;
$sql = "
SELECT
heroes.char_id, characters.char_name, heroes.class_id, heroes.count,
heroes.played, heroes.active FROM heroes, characters
WHERE characters.obj_Id = heroes.char_id AND heroes.played = 1
";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query))
{
echo "
<tr>
<td><span id='lefttop'><b><font color='#007aa2'>".$i++." </font></td><td><b><font color='#f6ff00'>".$row['char_name']."</font></td></span><div style='float:right;'><td><b> ".$row['count']."</td></div> <br />
</tr>
";
}
echo "";
?>
Anyone can help? im trying to make a hero status script on a java server, and i need to connect into 2 tables which is "heroes"(this is where i get the hero) and "character" (this is where i get the hero names)
Try this Temple:
<?php
$sql1 = "SELECT * your table1";
$query1 = mysql_query($sql);
while($row1 = mysql_fetch_array($query1))
{
echo "<tr>";
$sql2 = "SELECT * your table2";
$query2 = mysql_query($sql2);
while($row2 = mysql_fetch_array($query2))
{
echo "<td>[yor Vars here]</td>";
}
echo "</tr>";
}
?>

MySQL insert row from HTML table into db table

I am using a for loop to construct a HTML table from the contents of a MySQL table select query. I have a link on the end of each row to copy that row into another table.
I'm unsure how to get the data from the table row for the MySQL insert query - I have marked the place where I'm struggling with XXX.
<?php
mysql_select_db("cardatabase");
$link = mysql_connect("localhost", "root", "password");
$query = "SELECT * from cars";
$result = mysql_query($query);
if($_GET['rent']) {
$rent = "INSERT INTO rentedcars VALUES('XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
echo "<table>";
echo "<tr><td>ID</td><td>Make</td><td>Model</td><td>Fuel Type</td><td>Transmission</td><td>Engine Size</td><td>Doors</td><td>Amount</td><td>Available</td><td>Date Added</td><td>Remove</td></tr>";
for ($i = 0; $i < mysql_num_rows($result); $i++) {
$row = mysql_fetch_object($result);
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
echo "</table>";
edit (updated code):
<?php
mysql_select_db ("cardatabase");
$link = mysql_connect ("localhost", "root", "password");
$query = "SELECT * from cars";
$result = mysql_query ($query);
if($_GET['rent']) {
$query_car = sprintf("SELECT * from cars WHERE ID=%s",$_GET['rent']);
$rslt = mysql_query($query_car);
$car = mysql_fetch_object ($rslt);
$rent = "INSERT INTO rentedcars VALUES('$car->ID','$car->CARMAKE','$car->CARMODEL','$car->FUELTYPE','$car->TRANSMISSION','$car->ENGINESIZE','$car->DOORS','$car->AMOUNT','$car->AVAILABLE','$car->DATEADDED')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
echo "<table>";
echo "<tr>";
echo "<td>ID</td><td>Make</td><td>Model</td><td>Fuel Type</td><td>Transmission</td><td>Engine Size</td><td>Doors</td><td>Amount</td><td>Available</td><td>Date Added</td><td>Remove</td>";
echo "</tr>";
while ($row = mysql_fetch_object($result)) {
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
echo "</table>";
mysql_* is deprecated as of PHP 5.5.0, you should use something like PDO.
try {
$DBH = new PDO('mysql:dbname=cardatabase;host=localhost', 'root', 'password');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$STH = $DBH->query("SELECT * FROM cars")->execute();
while ($row = $STH->fetch(PDO::FETCH_OBJ)) {
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=".$row->ID."'>Rent</a></td>
</tr>";
}
Edit: Just like #Skatox said!
I would do it like this:
<?php
$link = mysql_connect ("localhost", "root", "password");
mysql_select_db ("cardatabase");
$query = "SELECT * from cars";
$result = mysql_query ($query);
Get car information and store it
if($_GET['rent'])
{
$query_car = sprintf("SELECT * from cars WHERE ID=%s",$_GET['rent']); //Avoids sql injection
$rslt = mysql_query($query_car);
$car = mysql_fetch_object ($rslt)
Here you need to validate if there's no car
$rent = "INSERT INTO rentedcars VALUES('$car->ID','$car->CARMAKE','$car->CARMODEL','$car->FUELTYPE','$car->TRANSMISSION','$car->ENGINESIZE','$car->DOORS','$car->AMOUNT','$car->AVAILABLE','$car->DATEADDED')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
Change it to while like #Vinoth Babu said:
while ($row = mysql_fetch_object ($result))
{
$row = mysql_fetch_object ($result);
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
print "</table>";
?>
I would recommend you to switch to MySQL PDO, it's safer and you'll get a better and secure code.
you are missing the column names in your insert query
$rent = "INSERT INTO rentedcars (id ,carmake, carmodel,fueltype,transmission, enginesize,doors,amount ,available, dateadded)
VALUES('xxx','xxx','".$carmodel."','XXX','XXX','XXX','XXX','XXX','XXX','XXX')";
^^^^^-------------i showed u exempel under
those XXX are values you get the from the inputs values
exemple
<input name= "car_model" id= "car_model" value="mercedes" >
then you get this value
if (isset($_POST['car_model'])){ $carmodel = $_POST['car_model']}
and then use this value $carmodel in your sql

Categories