I'm writing a php file, and I want to show two tables by executing 2 seperate queries, and store them in $result and $result_bike. However, when I try to open the html page for this action form, it only shows the table for the first query, and gives the error " Commands out of sync; you can't run this command now" at the place of the second table.
Also, I don't want to combine these two tables, as they show entirely different information and I want to insert some text explaining each table.
I think there might have something to do with not able to print two tables for php (which I doubt)? What change should I make?
Thank you in advance for the help!
$result = mysql_query("CALL CrashTypeRate_Ped('$city')", $conn);
if (!$result){
echo "Fail to retrieve result for pedestrian crashes!\n";
print mysql_error();
} else {
echo "<table border=1>\n";
echo "<tr><td>CrashType</td><td>Count</td><td>TotalCount</td></tr>\n";
while ($myrow = mysql_fetch_array($result)) {
printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>\n", $myrow["crash_type"], $myrow["type_count"], $myrow["total_count"]);
}
echo "</table>\n";
}
$result_bike = mysql_query("CALL CrashTypeRate_Bike('$city')", $conn);
if (!$result_bike) {
echo "Fail to retrieve result for bike crashes!\n";
print mysql_error();
} else {
echo "got here!!!!!!";
echo "<table border=1>\n";
echo "<tr><td>CrashType</td><td>Count</td><td>TotalCount</td></tr>\n";
while ($myrow = mysql_fetch_array($result_bike)) {
printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>\n", $myrow["crash_type"], $myrow["type_count"], $myrow["total_count"]);
}
echo "</table>\n";
}
Here is from PHP Documentation user comments. Hope this helps
Link to PHP Documentation
When calling multiple stored procedures, you can run into the following error: "Commands out of sync; you can't run this command now".
This can happen even when using the close() function on the result object between calls.
To fix the problem, remember to call the next_result() function on the mysqli object after each stored procedure call. See example below:
<?php
// New Connection
$db = new mysqli('localhost','user','pass','database');
// Check for errors
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
// 1st Query
$result = $db->query("call getUsers()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$user_arr[] = $row;
}
// Free result set
$result->close();
$db->next_result();
}
// 2nd Query
$result = $db->query("call getGroups()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$group_arr[] = $row;
}
// Free result set
$result->close();
$db->next_result();
}
else echo($db->error);
// Close connection
$db->close();
?>
Related
First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";
I had a very random problem in an IIS class, it has stumped my tutor so here I am and I'll try my best to explain it well!
I'm running Xampp with Apache and MySQL, I run the query I want and get the expected output to a table, but I have a problem with the outputting of pictures. I have the right file type, extention and path selected, because I can get pictures to show up, but as long as at least one picture in the query result has the extension removed, and this picture will not load.
Database
Website
If I have each query result with the correct name and extension, which is the same as when it shows up, none of them show up at all!
PHP:
<?php
// set server access variables
include 'db2.inc';
// open connection
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
// select database
mysql_select_db($databaseName) or die ("Unable to select database!");
// create query
//$query = "SELECT * FROM products";
$query = "SELECT * FROM products WHERE CategoryName = 'Surfboards'";
//Check initial letter
//if (!$initialLetter=="")
//{
// $query = $query." Where country like '$initialLetter%' ";
//}
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=20 border=1>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['ProductID']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['Description']."</td>";
echo "<td>".$row['Brand']."</td>";
echo "<td>".$row['Model']."</td>";
echo "<td>".$row['BoardLength']."</td>";
echo "<td>".$row['BoardType']."</td>";
echo "<td>".$row['Colour']."</td>";
echo "<td>"."<img src=images/".$row['Image']."> </td>";
echo "<td>".$row['UnitPrice']."</td>";
echo "<td>".$row['CategoryName']."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
Any help or direction would be greatly appreciated!
Thanks
Will
On this line:
echo "<td>"."<img src=images/".$row['Image']."> </td>";
Your image src is not enclosed in quotes. If this is a direct copy/paste of your code then that is definitely a problem, but may not be the only one.
As other people have said, look at pdo, or mysqli. The mysql_ functions you are using are deprecated for multiple reasons.
I want to insert a html code in between MySQL results.
My query
if($sql = $mysqli->query("SELECT * FROM table Limit 20")){
$row = mysqli_fetch_array($sql);
//Results display here
$sql->close();
}else{
printf("There seems to be an issue. Please Trey again");;
}
Above query is pulling 20 results at a time. I want to insert <div class="block"></div>after pulling 3rd result and continue other results after that div (using a single query)
Can anyone point me how to do this.
As it simple as it gets.
You just have to count each iteration and when it reaches 3 you print out the div element.
<?php
$mysqli = new mysqli("localhost","","","");
if ($mysqli->connect_errno){
echo "Failed to connect to MySQL";
}
if ($result = $mysqli->query("SELECT * FROM table")) {
$counter = 0;
while ($row = $result->fetch_assoc()) {
echo $row["______"];
if((++$counter) == 3) {
echo '<div class="block"></div>';
}
}
$result->close();
}
$mysqli->close();
?>
Simple Login Form Using PDO .The Output of echos works fine .Enters inside the else case But does not go inside the foreach loop.
The output of var_dump gives this .
echo output
1rows SelectedEntered successfull loop
var_dump output
object(PDOStatement)[3] public 'queryString' => string 'select *
from tour_login where username='admin' and password='admin' and
status=1' (length=81)
if(isset($_POST['login']))
{
$un=$_POST['un'];
$pass=$_POST['pass'];
$res=DB::getInstance()->query("select * from tour_login where username='$un' and password='$pass' and status=1");
$num_rows = $res->fetchColumn();
echo $num_rows."rows Selected";
if($num_rows<=0)
{ echo "Entered error loop";
echo "<script>alert('invalid username and password');document.location='index.php';</script>";
return false;
}
else
{
echo "Entered successfull loop";
foreach ($res as $row) {
echo "Entered successfull for loop";
if($row['type']==0)
{
$_SESSION['admn']=$un;
echo "<script>alert('welcome admin...');document.location='adminhome.php';</script>";
}
else
{
$_SESSION['usr']=$un;
echo "<script>alert('welcome user...');document.location='userhome.php';</script>";
}
}
}
}
What I am not understanding is why foreach is not working with number of rows showing one.New to Php.I found alternative of using mysql_num_rows() in pdo in this StackOVerflow Question
https://stackoverflow.com/questions/11305230/alternative-for-mysql-num-rows-using-pdo
Your first problem is that, being a novice, you just snatched one line from the code you found, having no idea what does it do. This line would never return number of rows found, yet this line is responsible for your confusion, as it fetches all the data you selected, leaving nothing for the foreach loop. Though you don't need the latter as well.
Your second problem is that you are under a very common delusion, thinking you need number of returned rows at all. In fact, you don't actually need it.
Your third problem is that you ought to be using prepared statements but you aren't.
The code you need is
$sql = "select * from tour_login where username=? and password=? and status=1";
$res = DB::getInstance()->query($sql);
$res->execute(array($un, $pass));
$row = $res->fetch();
if(!$row) {
echo "Entered error loop";
echo "<script>alert('invalid username and password');document.location='index.php';</script>";
return false;
}
and so on. Just remove useless foreach loop and you're set.
I'm making a PHP/MySQL(i) website application, and I am getting this dreaded error, "Commands out of sync; you can't run this command now".
I have a connection to a database.
(P.S. - This is different from all other questions with similar titles -- I have gone through them all. What I want to do is OPEN first query, CLOSE first query, then OPEN second query. I do not want to execute multiple statements at once, or open multiple result-sets simultaneously)
Here is what I am doing:
<?php
$sql = 'CALL spSelectProductAndVendor(1, 1)';
$rs = $mysqli->query($sql);
echo($mysqli->error);
if ($rs->num_rows > 0) {
while ($row=$rs->fetch_assoc()) {
echo '<h1 class="page-header">' . $row["productname"] . '<small> pertaining to vendor: ' . $row["vendorname"] . '</small></h1>';
}
}
$rs->close();
?>
HTML/CSS
<?php
$sql = 'CALL spSelectRecentDocumentScores();';
$rs = $mysqli->query($sql);
echo($mysqli->error);
if ($rs->num_rows > 0) {
while ($row=$rs->fetch_assoc()) {
if($row["totalwarnings"]>50) { echo '<tr class="danger">'; } else { echo '<tr class="active">'; }
?>
<td><?php echo $row["documentid"]; ?></td>
<td>etc...</td>
</tr>
<?php
}
}
?>
Why does this error only occur upon the SECOND call?
$rs = $mysqli->query($sql);
The first one works fine. The second does not. But I am closing the first $rs. So what is missing?
Figured it out.. need to add $conn->next_result(); after the first resultset is closed:
$rs->close();
$mysqli->next_result();
Then the second $rs may be safely opened.