I want to make an alfabetic list of teams.
A
A.....
A..... A.....
B
B.....
B.....
C
C.....
C.....
C.....
Now I do it on this way, what means if there is no team beginning with an A I has to remove the code. Can you tell me who I have to do it?
$conn=mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_SCHEMA_NAME);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql="SELECT * FROM teams where active=1 AND l_teamname='A' ORDER BY f_teamname asc";
echo "<table id='adressen_table'><tr><td><b>A </b><hr></td></tr>";
if ($result = mysqli_query($conn, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_row($result)) {
echo "<tr><td><a href=adr_det?teamid=$row[0]>$row[2]</a></td></tr>";
}
echo "</table>";
}
$sql="SELECT * FROM teams where active=1 AND l_teamname='B' ORDER BY f_teamname asc";
echo "<table id='adressen_table'><tr><td><b>B </b><hr></td></tr>";
if ($result = mysqli_query($conn, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_row($result)) {
echo "<tr><td><a href=adr_det?teamid=$row[0]>$row[2]</a></td></tr>";
}
echo "</table>";
}
Considering your code is "correct" then you should just change it a bit to do it only once and not 26 times for the whole alphabet...
The code below is just one way to do it, there are probably (certainly!) more effective ways to do the job, without these if/else blocks I added. But this is a quick idea :
//Did not touch the first part of your code...
//But don't forget, to make it work "fine" you have to sort by 2nd column
//(name I guess) so the items are already alphabetic ordered. If you
//don't do that, you'll see undefined number of "A" arrays opened
//& so on...
//...
//...Here we go
//check if your query ran fine, AND if it returned at least one row
if (($result = mysqli_query($conn, $sql))&&($result->num_rows>0)) {
//declare a variable that will keep the last "first character" you found
$firstChar= '';
while ($row = mysqli_fetch_row($result)) {
//check if the last character you found is the same as actual
if($row[2][0] == $firstChar){
//if so, then just display your line
echo "<tr><td><a href=adr_det?teamid=$row[0]>$row[2]</a></td></tr>";
}else{
if($firstChar==''){
//if first character wasn't set yet, then you have to open the first table.
//A string is a char array, so $string[0] will return the first character of the string.
$firstChar= $row[2][0];
echo "<table id='adressen_table'><tr><td><b>".$firstChar." </b><hr></td></tr>";
echo "<tr><td><a href=adr_det?teamid=$row[0]>$row[2]</a></td></tr>";
}else{
//if first char was set but is not the same as the previous
//then you have to (update firstchar value and) close the actual table,
//open a new one, insert your row with your new 'firstchar' and insert the row you're fetching.
echo "</table>";
$firstChar = $row[2][0];
echo "<table id='adressen_table'><tr><td><b>".$firstChar." </b><hr></td></tr>";
echo "<tr><td><a href=adr_det?teamid=$row[0]>$row[2]</a></td></tr>";
}
}
}
//close last table you opened
echo "</table>";
}else{
//Your query failed or returned nothing
}
Hope it helps
Related
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();
?>
In this application I have a drop down so you can select what table you want to view. Using Ajax I push the variable $tbl as an integer and the code below prints out the table that corresponds with that integer. Something is not working though and I need an extra pair of eyes to help debug.
if($tbl == 9){$table = "person";}
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$query = mysqli_query($conn, "SELECT * FROM $table ") or die(mysqli_error($conn));
if($query){
echo '<table border="1"><thead><tr>';
$colnames = array();
while ($finfo = mysqli_fetch_field($query)) {
$name=$finfo->name;
array_push($colnames, $name);
echo "<th>".$name."</th>";
}
mysqli_free_result($query);
echo '</tr></thead><tbody>';
$count = 0;
echo $colnames[$count]; // this test prints the correct column name but it ends up being printed OUTSIDE the table for some reason
while ($row = mysqli_fetch_array($query, MYSQLI_BOTH)){
echo '<td>'.$row[$colnames[$count]].'</td>';
$count++;
}
echo "</tbody></table>";
}
The last while loop is suppose to echo out each field value but it isn't executing <tbody> is left blank.
You called mysqli_free_result($query) too early. So by the time you called mysqli_fetch_array, the sql result was already gone. Move mysqli_free_result after the last loop.
I'm not sure whether it's a typo or that the following is where the problem lies, but you're missing opening and closing <tr> tags around the column names after <tbody> and before </tbody>. This may help explain why stuff is being printed apparently "outside" the table.
I've been on this for some days now. At first I thought the problem was in binding the parameters but I've simplified back to a basic mysqli page and still can't find the error. I'm passing the key for one of the rows in the search page before this onto this page so that I can show more details of the item which was selected.
I added an echo to test the the isset which prints correctly, also it puts the Key into the URL. If I leave out the WHERE Key = '$Key' it prints out the entire dataset. If I replace $row['Key'] with $Key it prints the whole dataset but with the selected key on every row.
This tells me that it is passing the key correctly and the print function is correct. I've tried using WHERE Key = $_GET['Key'] as well as $Key but neither work. I must be doing something basicly wrong here but after three days of trying every variation on the code I can think of, I have no more ideas.
<?php
$mysqli = new mysqli('localhost','user','password','database');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
if(isset($_GET['Key'])){
$Key = $_GET['Key'];
echo "Got it";
}else{
echo "No input";
}
$results = $mysqli->query("SELECT * FROM engravers WHERE Key ='$Key'");
$img_url = "http://www.xxxxx.net/images/";
print '<table border="1" >';
while($row = $results->fetch_assoc()) {
print '<tr>';
print '<td>'.$row["Key"].'</td>';
print '<td>'.$row["Country"].'</td>';
print '<td>'.$row["Year"].'</td>';
print '<td>'.$row["Description"].'</td>';
print '<td>'.$row["Engraver1Surname"].'</td>';
print '<td>'.$row["Designer1Surname"].'</td>';
print '<td>'.$row["Printer"].'</td>';
print '<td>'.'<img src="'.$img_url.$row['Images'].'" />'.'</td>';
print '</tr>';
}
print '</table>';
$results->free();
$mysqli->close();
?>
</body>
There are many SQL column names you should avoid. Please read: http://technet.microsoft.com/en-us/library/ms189822.aspx
Same Reserved Keywords are in MySQL.
If you use one of those just cover it with ``
$results = $mysqli->query("SELECT * FROM `engravers` WHERE `Key`='$Key'");
In your query you are using column key which is not allowed because this is a reserved keyword.
Man, you're already using mysqli, why are you still interpolating variables in your query? This is the way to pass a string $Key to the parser
$results = $mysqli->prepare("SELECT * FROM engravers WHERE `Key`= ?");
$results->bind_param("s", $Key);
while($row = $results->fetch_assoc()) {
... stuff ...
}
If that doesn't work, I'm sure it's not because the prepared statement is the problem.
PD: key is a reserved word, so please note the fieldname is wrapped in backticks.
I'm having a problem with some specific PHP code that I've been working on for a few days. It's meant to be a reporting code where I can input a day and a month and it will list the total sales of that particular day.
But, I can't seem to make the last statement whereby, if there are no values(there are no data) in the query, it will display 'No Sales on this particular day'. Here's the code I've been working on. But the last echo statement is not executing. Any ideas?
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
$day=#$_POST['day'];
$month=#$_POST['month'];
echo "<center><h2>Sales report on " .$day. "." .$month. ".2013</h2></center>";
echo "<center><table style='border:2px solid black;' align=center width=600>";
echo "<tr><th colspan=12><center><h2>Sales Report</h2><hr size='2' color='black' /></center></th></tr>";
echo " <th width=400> Amount Collected</th>";
?>
<br>
<?php
$x = 1; //counter
//open a connection to a MySQL server using function mysql_connect
//returns a MySQL link identifier on success, or FALSE on failure.
$conn= mysql_connect("localhost","root","");
if (!$conn)
die ("Connection error: ".mysql_error());
else {
//select a MySQL database
//returns TRUE on success or FALSE on failurue.
$db=mysql_select_db("cqfos");
if(!$db)
die ("DB not found: ".mysql_error());
else {
//put query in a variable $query
$query= "select ROUND(sum(orderdetails.tprice),2)
from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '$day' AND MONTH(orders.date) = '$month'";
$result=mysql_query($query);
if(!$result)
die ("Invalid query: ".mysql_error());
//if record exists
else {
//fetch a result row as both associative array and numeric array
if(mysql_num_rows($result)== 1){
while ($row=mysql_fetch_array($result,MYSQL_BOTH)){
echo "<tr>";
echo "<td align='center'>RM ".$row[0]."</td></tr>";
$x++; //increase the counter
}
}
else {
echo "<tr><th colspan=12>No sales made.</td></tr>";}
}
}
}
echo"</table></center>";
?>
Several problems here
your HTML table syntax is incorrect, and your using an old sql library - and it dose not look like your SQL syntax is right... try this code (not tested as I don't have your data)
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
echo '<div style="margin:auto; textalign:center;">';
echo "<h2>Sales report on " .$_POST['day']. "." .$_POST['month']. ".2013</h2>";
echo "<h2>Sales Report</h2>"
echo "<table style='border:2px solid black;' align=center width=600>";
echo "<tr><th width=400> Amount Collected</th></tr>";
?>
<br>
<?php
$conn = new mysqli("localhost","root","","cqfos");///use mysqli, not mysql : mysql is depricated
if ($conn->mysqli)
exit ("Connection error: ".$conn->errno ." : " $conn->error);
else {
//put query in a variable $query
$eDay = $conn->mysql_real_escape_string($_POST['day']);//escape these to protect the database
$eMonth = $conn->mysql_real_escape_string($_POST['month']);;//escape these to protect the database
//your column name is probably not a rounded value, replaced it with * (return all columns)
$query= "select * from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '"
.$eDay."' AND MONTH(orders.date) = '".$eMonth."'";
$result=$con->query($query);
if($conn->errno)
exit ("Invalid query: ".$conn->errno ." : " $conn->error);
//if record exists
else {
$numericArray = $result->fetch_array(MYSQLI_NUM); //fetch a result row as numeric array
$associativeArray = $result->fetch_array(MYSQLI_ASSOC); //fetch as an associtive array this is not used, just an example
$bothArray = $result->fetch_array(MYSQL_BOTH); //both associtive and numeric this is not used, just an example
}
if(!empty($numericArray))
{
foreach ($numericArray as $value) {
echo "<tr><td>RM ".$value[0]."</td><tr>";//is there more then 1 col? if not you should consider an html list
}
} else {
echo "<tr><td>No sales made</td><tr>";
}
echo"</table></center>";
}
?>
Your SQL (likely) returns more than only one row, so change the line I mentioned before to this:
if(mysql_num_rows($result)>0){
Just letting you know your code is vulnerable to SQLi because you have not sanitized $day and $month. Also please consider using PDO.
If you haven't already - Try running the SQL statement into PHPMyAdmin and see where it outputs the error (if there is one), else it will output the data.*
*Manually inputting the day/month substituting for the variables.
ok i got this page working well but what would do i have to do to display data from a certain letter?
here is the code i got at present
<html>
<head>
<title>MySQLi Read Records</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = "select * from contacts";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results > 0){ //it means there's already a database record
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th>Username</th>";
echo "<th>Action</th>";
echo "</tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$name}</td>";
echo "<td>{$surname}</td>";
echo "<td>{$mobile}</td>";
echo "<td>";
//just preparing the edit link to edit the record
echo "<a href='edit.php?id={$id}'>Edit</a>";
echo " / ";
//just preparing the delete link to delete the record
echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
</body>
</html>
i am wanting to place multiple entries like the following to dislay under the right letter
<h1>A</h1>
echo "<td>{$name}</td>";
echo "<td>{$surname}</td>";
echo "<td>{$mobile}</td>";
<h1>b</h1>
echo "<td>{$name}</td>";
echo "<td>{$surname}</td>";
echo "<td>{$mobile}</td>";
ECT ECT
what i am trying to acchieve is to dispaly all the surnames that begin with a then b
i have found this bit of code on this page http://www.sitepoint.com/forums/showthread.php?303895-Display-Data-Beginning-with-a-Particular-Letter
but how would i make this work for me?
i am novice (extremly) so any help be fantastic i tried to read tutorials i find it better with hands on :)
Updated ***************************
this is working great but now it only lists one line this is my code
<html>
<head>
<title>MySQLi Read Records</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = " SELECT name,
surname,
mobile,
UPPER (LEFT(surname, 1)) AS letter
FROM contacts
ORDER BY surname";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results > 0){ //it means there's already a database record
echo "<table border='1'>";//start table
//creating our table heading
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
if (!isset($lastLetter) || $lastLetter != $row['letter'])
{
echo '<h1>', $row['letter'], '</h1>';
$lastLetter = $row['letter'];
echo "{$surname}";
}
}
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
</body>
</html>
Since you are learning, I will give you the idea of how you can archive what you want and the functions you can use.
As you have mentioned you want all records displayed on the same page with their own alphabet letter as the header.
There is a few ways of doing what you want, the most common is to return the data ORDERed BY the field you want on the order you want, in this case ASC.
This will list all your records in alphabetical order.
From there you can use the function LEFT to extract the first letter as another field.
Now here is where you will use some PHP, from the above you already have your records ordered and the first letter for each record.
You can use something like this inside your while:
if (!isset($lastLetter) || $lastLetter != $row['letter'])
{
echo '<h1>', $row['letter'], '</h1>';
$lastLetter = $row['letter'];
}
Basically the above will check if $lastLetter has been set/defined which is not for the first record so it will enter the if, print your first header and set $lastLetter to the first letter.
After the first record it will be matching the $lastLetter against the $row['letter'] and once they are not equal, it prints the header again and update the $lastLetter with $row['letter'] which is the current letter.
Your MySQL query would look like this:
SELECT *,
LEFT(firstname, 1) AS letter
FROM contacts
ORDER BY firstname
However it is always better to define all fields you need instead of catching all the fields in case you have more fields on the table in question:
SELECT firstname,
surname,
mobile,
LEFT(firstname, 1) AS letter
FROM contacts
ORDER BY firstname
NOTE in case your names are not normalize you can use the UPPER function to make the letter uppercase like this:
SELECT firstname,
surname,
mobile,
UPPER(LEFT(firstname, 1)) AS letter
FROM contacts
ORDER BY firstname
See more about the UPPER function here
I suggest you do the following steps.
Update your mysql query statement
$query = "select * from contacts order by name_field";
Name_field or whatever is the column name so that you get the result set sorted in dictionary order.
Keep $previous to keep track of what letter you added last time.
Use this function (refer startsWith() and endsWith() functions in PHP) at each row to find whether the name value starts with a different letter from $previous. If there is a change then update $previous and include "" tags with the letter as you desire.
function startsWith($haystack, $needle)
{
return $needle === "" || strpos($haystack, $needle) === 0;
}
First of all you should change your SQL query to:
SELECT * FROM contacts ORDER BY name ASC
this will sort all of the contacts from A to Z. Now, to able to determine an initial alphabet of a contact name use substr function...
$initial_letter = strtoupper(substr($name, 0, 1));