I want to create an array with the help of MYSQL and display it the following way:
while ($array = mysqli_fetch_assoc($res))
{
echo $array["first_name"] . ", "
. $array["last_name"] . ", "
. $array["personal_id"] . ", "
. $array["salary"] . ", "
. $array["birthday"] . "<br />";
}
To improve usability, I only want to display 10 results, put a link to the next 10 results at the bottom and display these on another page.
How do I have to change the while-condition in order to only display the first 10 results of my result?
I tried searching for a solution but I couldn't find anything that fits my needs, so any help is appreciated!
Thanks in advance!
Check offset and limit conditions in mysql.
Example: to show 16 - 26 records from result query.
$sql = "SELECT * FROM Table LIMIT 10 OFFSET 15"
If what you want is just a way to break out of the loop after the first 10 results.
$counter = 1;
while (($array = mysqli_fetch_assoc($res)) || ($counter < 10))
{
echo $array["first_name"] . ", "
. $array["last_name"] . ", "
. $array["personal_id"] . ", "
. $array["salary"] . ", "
. $array["birthday"] . "<br />";
$counter++;
}
Related
Hello all! This is my first question in stackoverflow so I hope I follow the rules good enough. :)
For my PHP class I have an exercise that makes it difficult for me: Text with about 4 variables in it, all are stored in arrays (one array for each variable, 3 values for each variable).
Position [0] of each array goes in the first echo text, position [1] of each array goes in the second text and so on.
How to echo the text 3 times using all values stored in the array? In the code I must use the main text only 1 time.
$u_name = array('student' => 'Joe','lecturer' => 'Kate', 'assistant' => 'Martin');
$course_name = array('PHP', 'CSS', 'HTML');
$role = array('student', 'lecturer', 'assistant');
echo "Hi," . $u_name['student'] . "! You've been approved to take part in course " . $course_name[0] . " as a " . $role[0] . ". The course " . $course_name[0] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['lecturer'] . "! You've been approved to take part in course " . $course_name[1] . " as a " . $role[1] . ". The course " . $course_name[1] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['assistant'] . "! You've been approved to take part in course " . $course_name[2] . " as a " . $role[2] . ". The course " . $course_name[2] . " will last for two days.";
This is what I did by myself, but as you see in the code I have 3 times the main text.
Thank you in advance.
Normally you go trough arrays with some type of a loop.
To name a few types of loops:
for
while
foreach
In this case the perfect fit is a foreach loop.
It simply goes through each element of the array, but because you have a associative array and two indexed array you also need a counter.
$counter = 0;
foreach($u_name as $key=>$value){
echo "Hi, " . $value . "! You've been approved to take part in course " . $course_name[$counter] . " as a " . $role[$counter] . ". The course " . $course_name[$counter] . " will last for two days.";
echo "<br>";
$counter++;
}
If still are any questions left, don't mind to ask.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I'm looping through some data to display on my page, and then insert each loop to a row in a database (personal learning exercise for PHP and MySQL).
The for loop runs 5 times (for example, sometimes it may loop more/less), and I am able to successfully insert the data for the first 4 loops, but am having difficulty figuring out why the last loop won't insert into the database.
All 5 loop iterations display on my page, I'm not quite sure why the last loop won't insert into the database.
Here is my for loop that includes the MySQL code:
$artworksIterations = 1
count($artworksTitle[$x]) = 5
for ($x = 0; $x < $artworksIterations; $x++) {
for ($y = 0; $y < count($artworksTitle[$x]); $y++) {
$savedartworksTitle = $artworksTitle[$x][$y];
echo "TITLE: " . $savedartworksTitle . "<br>";
$savedartworksArtist = $artworksArtist[$x][$y];
echo "ARTIST: " . $savedartworksArtist . "<br>";
$savedartworksYear = $artworksYear[$x][$y];
echo "YEAR: " . $savedartworksYear . "<br>";
$savedartworksMedium = $artworksMedium[$x][$y];
echo "MEDIUM: " . $savedartworksMedium . "<br>";
$implodeGene = implode(", ", $artworksGene[$x][$y]);
echo "GENRES: " . $implodeGene;
$savedartworksDisplay = $artworksDisplay[$x][$y];
echo "<br><img src='" . $savedartworksDisplay . "'><br>";
echo "<br>----<br>";
$sql = "INSERT INTO Artworks (title, artist, year, medium, display, genres) VALUES ('$savedartworksTitle', '$savedartworksArtist', '$savedartworksYear', '$savedartworksMedium', '$savedartworksDisplay', '$implodeGene');";
mysqli_query($conn, $sql);
} // end of y
} // end of x
Any help would be deeply appreciated. Thank you :)
Thank you to everyone who helped dissect my issue!
It turns out, by mere coincidence, the data from the last loop of each iteration contained an apostrophe ('), which was why they weren't inserted into the database (syntax error).
Thank you to Jacques for pointing out that I should be checking for errors, that is where it informed me of a syntax error (also, thank you for jeff who clued in on my apostrophe issue).
To fix this, I used the mysqli_real_escape_string() function save the data as a safe format for the database (probably something I should have done in the first place, learning experience!).
Updated working code:
for ($x = 0; $x < $artworksIterations; $x++) {
for ($y = 0; $y < count($artworksTitle[$x]); $y++) {
// display the information on the web page
echo "TITLE: " . $artworksTitle[$x][$y] . "<br>";
echo "ARTIST: " . $artworksArtist[$x][$y] . "<br>";
echo "YEAR: " . $artworksYear[$x][$y] . "<br>";
echo "MEDIUM: " . $artworksMedium[$x][$y] . "<br>";
echo "GENRES: " . implode(", ", $artworksGene[$x][$y]);
echo "<br><img src='" . $artworksDisplay[$x][$y] . "'><br>";
// save data to MySQL safe format
$savedartworksTitle = mysqli_real_escape_string($conn, $artworksTitle[$x][$y]);
$savedartworksArtist = mysqli_real_escape_string($conn, $artworksArtist[$x][$y]);
$savedartworksYear = mysqli_real_escape_string($conn, $artworksYear[$x][$y]);
$savedartworksMedium = mysqli_real_escape_string($conn, $artworksMedium[$x][$y]);
$savedartworksDisplay = mysqli_real_escape_string($conn, $artworksDisplay[$x][$y]);
$implodeGene = mysqli_real_escape_string($conn, implode(", ", $artworksGene[$x][$y]));
// insert data into database
$sql = "INSERT INTO Artworks (title, artist, year, medium, display, genres) VALUES ('$savedartworksTitle', '$savedartworksArtist', '$savedartworksYear', '$savedartworksMedium', '$savedartworksDisplay', '$implodeGene');";
if (mysqli_query($conn, $sql) === FALSE) {
printf("ERROR: %s\n", mysqli_error($conn));
}
echo "<br>----<br>";
} // end of y
} // end of x
I have searched everywhere, but nothing I find seems to help solve this. I have a html web form (in a PHP document) that writes data to a CSV file, and below the form is a table that filters the CSV data back in based on a key word. I have no problems with my existing code for that part. However, I need to have an auto-number function that assigns a number to each form. I need help on even where to start. I'm still relatively new to coding, so any help would be great.
Edit: Here is the code I use to write my data to the csv file.
if($_POST['formSubmit'] == "Submit")
{
$fs = fopen("fixturerequests.csv","a");
fwrite($fs,$varFixNum . ", " . $varRequester . ", " . $varDept . ", " . $varSupervisor . ", " . $varDesc . ", " . $varParts . ", " . $varWC . ", " . $varAddinfo . ", " . $varDateReq . ", " . $varDateNeed . ", " .$varStatus . "\n");
fclose($fs);
header("Location: successfullysubmitted.php");
exit;
}
Any guidance would be excellent. Thank you.
You can use this function
function next_available_form_id(){
$rows = file('fixturerequests.csv'); //put our csv file into an array
if(empty($rows)) return 1; //if our csv is empty we start from 1
$data = str_getcsv(array_pop($rows)); //array_pop gets the last row
return $data[0]+1; //we get first field and add 1 to it
//Just use the field where you store the form number
//e.g if you store the form number in the
//4th field replace $data[0] with $data[3]
}
Based on the code you provided you can use the function I provided to get the next form_id before storing it in the csv file.Just make this modification to your code after opening the csv file :
$fs = fopen("fixturerequests.csv","a");
$form_id=next_available_form_id(); //ADD THIS to get the next available id
//And insert $form_id as the first field in your csv file
fwrite($form_id,$fs,$varFixNum . ", " . $varRequester . ", " . $varDept . ", " . $varSupervisor . ", " . $varDesc . ", " . $varParts . ", " . $varWC . ", " . $varAddinfo . ", " . $varDateReq . ", " . $varDateNeed . ", " .$varStatus . "\n");
Notice:
Of course since the csv you have now does not have form_id as the first field you should either create your csv file from scratch or add form numbers in your existing records.In the example I use awk to do that:
awk '{printf "%d,%s\n", NR, $0}' < fixturerequests.csv
Good eve everyone!
For some reason Database::fetchArray() is skipping the first $row of the query result set.
It prints all rows properly, only keeps missing out the first one for some reason, I assume there's something wrong with my fetchArray() function?
I ran the query in phpMyAdmin and it returned 4 rows, when I tried it on my localhost with the php file (code below) it only printed 3 rows, using the same 'WHERE tunes.riddim'-value ofcourse. Most similiar topics on google show that a common mistake is to use mysql_fetch_array() before the while(), which sets the pointer ahead and causes the missing of the first row, unfortunately I only have one mysql_fetch_array() call (the one within the while()-head).
<?php
$db->query("SELECT " .
"riddims.riddim AS riddim, " .
"riddims.image AS image, " .
"riddims.genre AS genre, " .
"tunes.label AS label, " .
"tunes.artist AS artist, " .
"tunes.tune AS tune, " .
"tunes.year AS year," .
"tunes.producer AS producer " .
"FROM tunes " .
"INNER JOIN riddims ON tunes.riddim = riddims.riddim " .
"WHERE tunes.riddim = '" . mysql_real_escape_string(String::plus2ws($_GET['riddim'])) . "'" .
"ORDER BY tunes.year ASC");
$ar = $db->fetchArray();
for($i = 0; $i < count($ar) - 1; $i++)
{
echo $ar[$i]['riddim'] . " - " . $ar[$i]['artist'] . " - " . $ar[$i]['tune'] . " - " . $ar[$i]['label'] . " - " . $ar[$i]['year'] . "<br>";
}
?>
Database::fetchArray() looks like:
public function fetchArray()
{
$ar = array();
while(($row = mysql_fetch_array($this->result)) != NULL)
$ar[] = $row;
return $ar;
}
Any suggestions appreciated!
You should remove -1 from the for loop
The problem's in your while loop:
for($i = 0; $i < count($ar) - 1; $i++)
if count ($ar) is 1, because there's one entry, your loop will never be called; try tweaking the check part:
for($i = 0; $i < count($ar) ; $i++)
You can also use a simple foreach:
foreach($db->fetchArray() as $row)
{
echo $row['riddim'] # ...
}
It'll make your code more readable too.
I need to round a result of a SQL round in a table array output. I can't figure out the syntax...
$result = mysql_query("SELECT `Energ_Kcal`*`yield`*`qty` AS `cal` FROM allinnot a
WHERE `own_id` = $user->id");
echo "<tr><td>" . $row['Shrt_Desc'] . "</td><td> " . $row['desc'] . "</td><td>" . $row['cal'] . " cal</td></tr>";
cal returns a value with many numerals beyond the decimal. I just need it to show a whole rounded integer. I tried ROUND(), but I must be putting it in the wrong place.
general syntax
ROUND( expression, 2 )
The ROUND should go around the values, try this:
$result = mysql_query("SELECT ROUND(`Energ_Kcal`*`yield`*`qty`,2) AS `cal` FROM allinnot a
WHERE `own_id` = $user->id");
echo "<tr><td>" . $row['Shrt_Desc'] . "</td><td> " . $row['desc'] . "</td><td>" . $row['cal'] . " cal</td></tr>";
You could also check out PHP's round() or, possibly from your description int_val().