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));
Related
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
How can I update a database with the values from an array? For example, let’s say we got a database with three tables:
Meals:
mealnr(PK), name, sort
Ingredients: ingredientnr(PK), name, stock
Structure: mealnr(FK), ingredientnr(FK), amount
I filled the database with some meals and ingredients. Every meal consists of multiple ingredients. The chef decides you only need 75g of ingredient x instead of 100g for meal y, so it needs to be changed in the database. Of course it can be done with SQL-commands, but I want to do it using a form in PHP.
First I made a page where all the meals are displayed. A meal can be edited using the edit-button next to it and based on the mealnr, you can change the amount of one or multiple ingredients for that particular meal. On the edit-page all the ingredient names and amounts are displayed in a table. The amount fields are textfields, those can be edited.
I made this script, but I don’t know exactly how I can update my database with the values of an array. I tried it with a foreach-loop, but it doesn't work.. yet. Can somebody help me?
<?php
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db("eatit", $conn);
$id = $_REQUEST['mealnr'];
$result = mysql_query("SELECT meals.name AS mealname, structure.amount, ingredients.name AS ingredientname
FROM Meals, Structure, Ingredients
WHERE meals.mealnr = structure.mealnr
AND structure.ingredientnr = ingredients.ingredientnr
AND meals.mealnr = '$id'");
if(isset($_POST['save']))
{
$new_amount = $_POST['amount[]'];
foreach ($new_amount as $value) {
mysql_query("UPDATE structure SET amount ='$value', WHERE mealnr = '$id'")
or die(mysql_error());
}
}
mysql_close($conn);
?>
<p><strong>Ingredients:</strong></p>
<?php
echo "<table>";
echo "<tr>";
echo "<th>Ingredient</th>";
echo "<th>Amount (gr)</th>";
echo "</tr>";
while($ingredient = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>";
echo $ingredient['ingredientname'];
echo "</td>";
echo "<td>";
echo '<input type="text" formmethod="post" name ="amount[]" value="' . $ingredient['amount'] . '" />';
echo "</td>";
echo "</tr>";
}
?>
<input type="submit" name="save" value="save" />
In your HTML markup you have declared the elements holding the name amount as an array by using amount[].
So, in your php code that receives the data it's enough to just refer to the amounts this way:
$new_amount = $_POST['amount'];
instead of:
$new_amount = $_POST['amount[]']; // in fact, this is wrong
Your foreach is fine, you should add some checks so that the $value actually contains a value that you expect, for example an int, float or not less than zero (or whatever checks you find necessary).
foreach($new_amount as $value){
if($value != '' && $value >= 1){
//sql statements goes here.
}
}
Receiving form data this way and then directly injecting the result to your SQL statement is always dangerous:
$id = $_REQUEST['mealnr'];
If you declare that you expect an integer (as the id's should be) before you directly inject the code to your SQL statement you have already written safer code.
$id = (int)$_REQUEST['mealnr'];
Also, just for the record - the mysql_* library is deprecated. As pointed out in the comments, try using PDO or mysqli instead - really!
I have a table in Oracle with this columns: IMGPOSX, IMGPOSY and IDIMG. Each row of the table has a different X Y value positions and an ID to identify witch of this values correspond to an specified ID.
For example: IDIMG = image1 > IMGPOSX = 20 IMGPOSY = 50
With this value then I build a html map image and load the image with an specified ID and put the results of the IMGPOSX and IMGPOSY on the margin-top and margin-left css properties.
I have found several example of how to get the values of the first line of the row but i don't know how to get the another ones (the table has 12 rows)
With the next code I get the first row of each column (IMGPOSX, IMGPOSY and IDIMG) but i don't know how to get the rest of the rows of the table. If I put row1[1] the parser get an error.
<?php
$conn = oci_connect('TEST', 'TEST', 'ORCL');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT IMGPOSX, IMGPOSY, IDIMG FROM TESTTABLE ');
if(oci_execute($stid))
{
$row=oci_fetch_row($stid) ;
"<table border='2'>";
print"<tr><td><p>posx: </td><td>$row[0] </td></tr>";
print"<tr><td>posy: </td><td>$row[1] </td></tr>";
print"<tr><td>idimg: </td><td>$row[2] </td></tr>";
print"</table></br>";
}
oci_free_statement($stid);
oci_close($conn);
?>
Also I like to filter the results of the fetch by the idimg, for example, some code that says "showme only the IMGPOSX and IMGPOSY from the IDIMG='image2'.
A rough example could be appending a WHERE clause to your query:
$id = 'image2';
$stid = oci_parse($conn, "SELECT IMGPOSX, IMGPOSY, IDIMG FROM TESTTABLE WHERE IMDIMG = $id;");
or, with the same query, you can filter with IF:
if ($row[2] == $id) {
//show
}
The sentence before your code states that you could need more than one row, so if you are not filtering, you will recieve more, to get them you need a proper fetch. Your current one if fetch_row, maybe you need fetch_array in order to recieve array with all values.
I would suggest oci_fetch_assoc http://php.net/manual/en/function.oci-fetch-assoc.php so you can access the column via their names. Also the filtering will use a named column.
if ($row['IDIMG'] == $id) {
//show
}
Have in mind the following sentence of the function description:
This function is typically called in a loop until it returns FALSE
You'd need something like:
<?php
//all the code here
// ...
// ...
?>
<table border="2">
<?php while ($row = oci_fetch_assoc($stid)): ?>
<tr><td><p>posx:</p></td><td><?=$row['IMGPOSX'];?></td></tr>
<tr><td><p>posy:</p></td><td><?=$row['IMGPOSY'];?></td></tr>
<tr><td><p>idimg:</p></td><td><?=$row['IDIMG'];?></td></tr>
<?php endwhile; ?>
</table><br />
<?php
oci_free_statement($stid);
oci_close($conn);
?>
All the whole day I'm trying to solve this problem but still no luck.
The scenario is: I am developing a vertical menu which should query groups and items of those groups in a menu respectively, but groups are being populated without its items.
Code was written in the following way:
$data1 = mysql_query(select groupnames from groups where categoryy='Agriculture');
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$data2==mysql_query(select itms from groupitems where categoryy='Agriculture' and groupname='$info1[0]');
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
In the above code, groups are being populated nicely but no items from groupitems table are being populated. If I write Grain (Grain is one of the group of agriculture in my database) instead of groupname=$info1[0] then it works. But it should be got dynamically from the query.
Please help, I'm in trouble.
at last its solved! here's the code:
<?php
include "aPannel/dbconn.php";
$query="select GroupName from categorygroup where categoryy='Agriculture'";
$i=0;
$result=mysql_query($query);
$num=mysql_num_rows($result);
$groupname=mysql_result($result ,$i ,"GroupName");
mysql_close();
if ($num=="0") echo "<p>Sorry, there are no groups to display for this Category.</p>";
else
{
echo "<p>There are currently <strong>$num</strong> groups represented in our database.</p><br>";
while($i < $num)
{
$groupname=mysql_result($result ,$i ,"GroupName");
include("aPannel/dbconn.php");
$query2 = "SELECT subcategory FROM groupsubcategory WHERE groupname='$groupname'"; // count number of items in each group
echo $query2 . "<br/>";
$resultt=mysql_query($query2);
$countt=mysql_num_rows($resultt);
mysql_close();
echo $countt . "subcategories" . "<br/>"; // display number of items
$i++;
}
} // end if results
?>
Your queries are not wrapped around double-quotes (" ") . Always remember that what you pass to mysql_query method is a string argument. And also $data2==.... seems wrong.
So, change the code like this
$data1=mysql_query("select groupnames from groups where categoryy='Agriculture'");
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$infoTemp=$info1[0];
$data2=mysql_query("select itms from groupitems where categoryy='Agriculture'
and groupname='$infoTemp'");
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
I hope it should work
EDIT: Also are you sure column itms in second query or items ?
EDIT: added temporary variable
I need some help with some PHP and MySQL code. At the moment I have a php file which displays the contents of a table in my database. I would like it to omit results that match "Not Booked". So the file only shows me slots which are booked. Here is my code:
<link href="../css/pagestyle.css" rel="stylesheet" type="text/css" />
<?php
include("../config.php");
include("functions.php");
if($logged["level"] == "HDJ" OR $logged["level"] == "SA") {
echo "<div class=\"head\">View Booked Slots</div>
<img src=\"../images/spacer.png\" width=\"5\" height=\"5\">
<div class=\"board\">Here you can view booked slots.</div>
<img src=\"../images/spacer.png\" width=\"5\" height=\"5\">
<table width=\"580px\" class=\"board\" border=\>";
$order = "SELECT * FROM timetable";
$result = mysql_query($order);
while ($row=mysql_fetch_array($result)){
echo ("<tr><td>$row[username]</td>");
</tr>");
}
echo "
</table>
";
} else {
echo ("<div class=\"caution\">Access is denied.</div>");
}
?>
Modify the query not to pull them in the first place.
$order = "SELECT * FROM timetable WHERE <the column> <> 'Not Booked';
Replace <the column> with the correct column name in your table where Not Booked appears.
It is often not advisable to intermix database logic and display logic as you have done here. Instead, you ought to do the query before outputting your table, and store its results in an array. Then loop over the array to display your table.
$order = "SELECT * FROM timetable WHERE somecolumn <> 'Not Booked'";
$result = mysql_query($order);
// Error checking
if (!$result) {
// output error, take other action
}
else {
while ($row=mysql_fetch_array($result)){
// Append all results onto an array
$rowset[] = $row;
}
}
Later, loop over the array to output your values. Dont' forget to escape it for HTML output with htmlspecialchars().
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td></tr>";
}
In your mySQL code:
SELECT * FROM timetable WHERE myvariable <> 'Not Booked'
Michael's answer will only pull out results that MATCH 'Not Booked' rather than omit them. Tweak the code to:
$order = "SELECT * FROM timetable WHERE <the column> <> 'Not Booked';
And you'll get all the booked ones (assuming there are only two states)