I have a simple my-sql table:
+----+----------+----------+-------------+-----------+
| id | Name | Father | National | Value |
+----+----------+----------+-------------+-----------+
| 1 | Daniel | David | American | 0 |
| 2 | Rebbeka | Craig | American | 0 |
| 3 | Robert | John | American | 0 |
| 4 | Arjun | Daneil | Indian | 0 |
| 5 | Ana | Peter | British | 0 |
+----+----------+----------+-------------+-----------+
I need to a php-script to query and fetch new single row every time it is executed. It may be based on ID.
About code/framework, i am using simple php5 with mysql on ubuntu server.
This is my code, the probelem is that it outputs whole of the Name,Father columns every time on call, i just want to print a single row everytime it is executed. and on every php script execution a new row should be printed based on id in ascending order.
<?php
$con = mysqli_connect('localhost','user','pass','database');
$result = mysqli_query($con,"select * from table");
while($row = mysqli_fetch_array($result)) {
echo "Name:" . $row['name'] . " " . "Father's Name:" . $row['father'];
echo "<br>";
}
mysqli_close($con);
?>
Every help is much appreciated.
the below code will help you get the output.
from next time when you ask any question pls add your code.
$link = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM `emp` ORDER BY RAND() LIMIT 0,1;" or die("Error in the consult.." . mysqli_error($link));
$result = mysqli_query($link, $query);
//display information:
$row = mysqli_fetch_array($result);
echo $row["name"].$row["Father"].$row["National"].$row["Value"];
As i have no much details of what type of code/framework you have I am giving you a answer on the basis of what I understand
There will be two ways I can think of to fetch the data
1.
Change the Table Structure and add one more column called lastFetched and every-time you fetch the row update the particular row by 1 and else everything else to 0 so that next time when you fetch the row you already know which is the last row fetched by you. and you can do an increment to it.
2.
On the page you are fetching the result would have a hidden input where you can store the last data number letz say first time it is 0 when page loads
then your query will be
SELECT * from <tablename> LIMIT 0,1
and increase the value of the hidden input to +1
so next time you fetch the result will gives the query
SELECT * from <tablename> LIMIT 1,2
From the discussion we had in the comments I came to a conclusion that you are looking for this.
<table>
<tr>
<?php
if(isset($_POST['pullNextRecord'))
{
$whtrec=$_POST['whatrecord'];
$con = mysqli_connect('localhost','user','pass','database');
$result = mysqli_query($con,"select * from table LIMIT $whtrec, ++$whtrec");
echo "<input type='hidden' name='whatrecord' value=".$whtrec." />";
echo "<th>Name</th><th>Fathers Name</th></tr><tr>";
while($row = mysqli_fetch_array($result))
{
echo "<td>$row['name']</td><td>$row['father']</td>";
}
mysqli_close($con);
}
?>
<input type="submit" name="pullNextRecord" />
Related
I have a dance contest site and each user can login and add dance moments,
in my html table with all moments from all users i have all the data but i want in a html column to add "number of dancers for each moment added by the logged user id".
I have this:
$c = mysql_query("SELECT * FROM moments");
$dancers = 0;
while($rows = mysql_fetch_array($c)){
for($i = 1; $i <= 24; $i++){
$dan_id = 'dancer'.$i;
if($rows[$dan_id] != "" || $rows[$dan_id] != null )
$dancers++;
}
}
echo "<th class="tg-amwm">NR of dancers</th>";
echo "<td class='tg-yw4l'>$dancers</td>";
phpMyAdmin moments table: has id, clubname, category, discipline, section, and this:
But this process is count all the dancers names from all users moments.
Example for this process: You have a total of 200 dancers !
I want the process to count for me all dancers names for each moment added in the form not a total of all entire users moments, something like this: if user john has two moments added: Moment 1: 5 dancers - moment 2: 10 dancers, and so on for each user.
Let me try to put you in the right way (it seems a long post but I think it's worth the beginners to read it!).
You have been told in the comments to normalize your database, and if I were you and if you want your project to work well for a long time... I'd do it.
There are many MySQL normalization tutorials, and you can google it your self if you are interested... I'm just going to help you with your particular example and I'm sure you will understand it.
Basically, you have to create different tables to store "different concepts", and then join it when you query the database.
In this case, I would create these tables:
categories, dance_clubs, users and dancers store "basic" data.
moments and moment_dancers store foreign keys to create relations between the data.
Let's see the content to understand it better.
mysql> select * from categories;
+----+---------------+
| id | name |
+----+---------------+
| 1 | Hip-hop/dance |
+----+---------------+
mysql> select * from dance_clubs;
+----+---------------+
| id | name |
+----+---------------+
| 1 | dance academy |
+----+---------------+
mysql> select * from users;
+----+-------+
| id | name |
+----+-------+
| 1 | alex |
+----+-------+
mysql> select * from dancers;
+----+-------+
| id | name |
+----+-------+
| 1 | alex |
| 2 | dan |
| 3 | mihai |
+----+-------+
mysql> select * from moments;
+----+--------------+---------------+-------------------+
| id | main_user_id | dance_club_id | dance_category_id |
+----+--------------+---------------+-------------------+
| 1 | 1 | 1 | 1 |
+----+--------------+---------------+-------------------+
(user alex) (dance acad..) (Hip-hop/dance)
mysql> select * from moment_dancers;
+----+-----------+-----------+
| id | moment_id | dancer_id |
+----+-----------+-----------+
| 1 | 1 | 1 | (moment 1, dancer alex)
| 2 | 1 | 2 | (moment 1, dancer dan)
| 3 | 1 | 3 | (moment 1, dancer mihai)
+----+-----------+-----------+
Ok! Now we want to make some queries from PHP.
We will use prepared statements instead of mysql_* queries as they said in the comments aswell.
The concept of prepared statement can be a bit hard to understand at first. Just read closely the code and look for some tutorials again ;)
Easy example to list the dancers (just to understand it):
// Your connection settings
$connData = ["localhost", "user", "pass", "dancers"];
$conn = new mysqli($connData[0], $connData[1], $connData[2], $connData[3]);
$conn->set_charset("utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Here we explain MySQL which will be the query
$stmt = $conn->prepare("select * from dancers");
// Here we explain PHP which variables will store the values of the two columns (row by row)
$stmt->bind_result($dancerId, $dancerName);
// Here we execute the query and store the result
$stmt->execute();
$stmt->store_result();
// Here we store the results of each row in our two PHP variables
while($stmt->fetch()){
// Now we can do whatever we want (store in array, echo, etc)
echo "<p>$dancerId - $dancerName</p>";
}
$stmt->close();
$conn->close();
Result in the browser:
Good! Now something a bit harder! List the moments:
// Your connection settings
$connData = ["localhost", "user", "pass", "dancers"];
$conn = new mysqli($connData[0], $connData[1], $connData[2], $connData[3]);
$conn->set_charset("utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to read the "moments", but we have their main user and dancers in other tables
$stmtMoments = $conn->prepare("
select
moments.id,
(select name from users where users.id = moments.main_user_id) as main_user,
(select name from dance_clubs where dance_clubs.id = moments.dance_club_id) as dance_club,
(select name from categories where categories.id = moments.dance_category_id) as dance_category,
(select count(*) from moment_dancers where moment_dancers.moment_id = moments.id) as number_of_dancers
from moments
");
// Five columns, five variables... you know ;)
$stmtMoments->bind_result($momentId, $momentMainUser, $momentDanceClub, $momentDanceCategory, $momentNumberOfDancers);
// Query to read the dancers of the "moment" with id $momentId
$stmtDancers = $conn->prepare("
select
dancers.name as dancer_name
from
dancers join moment_dancers on dancers.id = moment_dancers.dancer_id
where
moment_dancers.moment_id = ?
");
$stmtDancers->bind_param("i", $momentId);
$stmtDancers->bind_result($momentDancerName);
// Executing the "moments" query
$stmtMoments->execute();
$stmtMoments->store_result();
// We will enter once to the while because we have only one "moment" right now
while($stmtMoments->fetch()){
// Do whatever you want with $momentId, $momentMainUser, $momentDanceClub, $momentDanceCategory, $momentNumberOfDancers
// For example:
echo "<h3>Moment $momentId</h3>";
echo "<p>Main user: $momentMainUser</p>";
echo "<p>Dance club: $momentDanceClub</p>";
echo "<p>Category: $momentDanceCategory</p>";
echo "<p>Number of dancers: $momentNumberOfDancers</p>";
echo "<p><strong>Dancers</strong>: ";
// Now, for this moment, we look for its dancers
$stmtDancers->execute();
$stmtDancers->store_result();
while($stmtDancers->fetch()){
// Do whatever you want with each $momentDancerName
// For example, echo it:
echo $momentDancerName . " ";
}
echo "</p>";
echo "<hr>";
}
$stmtUsers->close();
$stmtMoments->close();
$conn->close();
Result in browser:
And that's all! Please ask me if you have any question!
(I could post the DDL code to create the database of the example with the content data if you want)
Edited: added dancers table. Renamed moment_users to moment_dancers. Changed functionality to adapt the script to new tables and names.
Let's assume I have a table like this:
+------+---------+--------------+-------------+---------------+
| id | tstamp | product_id | name | configuration |
+------+---------+--------------+-------------+---------------+
| 3 | 15 | 02 | bike | abc |
| 2 | 16 | 03 | car | dfg |
| 1 | 11 | 04 | tree | ehg |
+------+---------+--------------+-------------+---------------+
When I run a simple query like
SELECT id, tstamp, product_id, name, configuration
FROM tl_iso_product_collection_item
ORDER BY `id` DESC
It returns 3 rows. As expected. Works, right? BUT, if I implement this query into a PHP script and try to fetch rows, theres always ONE missing. Always. Even in the most simple query. Where did I make a mistake?
Script looks like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$connection = mysqli_connect('localhost', 'user', 'pw', 'db');
mysqli_set_charset($connection,"utf8");
$query = "SELECT id, tstamp, product_id, name, configuration
FROM table
ORDER BY `id` DESC "
$result = mysqli_query($connection, $query);
while ($row=mysqli_fetch_row($result)) {
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
echo $row[4];
}
mysqli_close($connection);
?>
This will result in displaying only 2 out of 3 rows. My question is, why tho? If I insert the query above directly into phpmyadmin it shows 3 results, not 2. What is wrong here? Am I missing something? Thanks in advance.
$fetch_allgemein = mysqli_fetch_array($result_allgemein);
$fetch_configuration = mysqli_fetch_array($result_configuration);
You are fetching the first record for each query result here already – so the internal “pointer” to the current record gets advanced to the second record in each result set, and therefor when you loop over the result using
while ($row=mysqli_fetch_row($result_allgemein)) {
later on, the first record is of course omitted.
You will need to reset the “pointer” using mysqli_result::data_seek if you want to get all records in your loops after you’ve already fetched the first record each.
I'm trying to return 5 unused values from the codes column of the table below and then set used in the related row to 1.
|--- codes ---| | used |
| FIomQVu71l | | 0 |
| 4TW0lwLWNK | | 0 |
| SjzLB2Shzr | | 0 |
| uTWJrtCgh4 | | 0 |
| tLwOwYGz5R | | 0 |
| byEhzYMWJG | | 0 |
| XFBmGzDGIR | | 0 |
I've managed to get the code working to output 5 random values from codes where used = 0
<?php
$sql = "SELECT codes FROM code_table WHERE used =0 ORDER BY rand() LIMIT 5";
$records = mysql_query($sql, $connection);
while($rows = mysql_fetch_array($records)){
echo "Code: " . $rows['codes'] . "<br />";
?>
But now I'm lost as to how to update the used value for each output codes. All of my attempts have updated every single instance of used to 1 rather than just the instances associated with the 5 codes
You could store the rows in a temporary table. Note that this is not entirely concurrency safe. If another query comes between the insert and the update, it might grab the same rows.
CREATE TEMPORARY TABLE IF NOT EXISTS tmp_codes (codes varchar(50));
-- Get five new rows
INSERT INTO tmp_codes
(codes)
SELECT codes
FROM code_table
WHERE used = 0
ORDER BY
rand()
LIMIT 5;
-- Update the five rows
UPDATE code_table
SET used = 1
WHERE codes in
(
SELECT codes
FROM tmp_codes
);
-- Return to application
SELECT codes
FROM tmp_codes;
DROP TABLE tmp_codes;
Example at SQL Fiddle.
You should execute an update query:
$sql = "SELECT codes FROM code_table WHERE used =0 ORDER BY rand() LIMIT 5";
$records = mysql_query($sql, $connection);
$codes = array();
while($rows = mysql_fetch_array($records)){
echo "Code: " . $rows['codes'] . "<br />";
$codes[] = "'" . $rows['codes'] . "'";
}
$updateSql = "UPDATE code_table SET used = 1 WHERE codes in(" . implode (',' , $codes ) . ")";
$res = mysql_query($updateSql, $connection);
I have a stored value from one table called user_id. I have another table as such:
client_projects:
+------------------+-------------+-------------+-------------+
| project_codename | client_id_1 | client_id_2 | client_id_3 |
+------------------+-------------+-------------+-------------+
| Alpha | 1 | 2 | 3 |
+------------------+-------------+-------------+-------------+
| Beta | 2 | 1 | 0 |
+------------------+-------------+-------------+-------------+
| Gamma | 3 | 1 | 0 |
+------------------+-------------+-------------+-------------+
If the user_id = (client_id_1 or client_id_2 or client_id_3) then I want to print the corresponding project_codenames in a dropdown list. This is the php I have but is not returning the right results. I have marketed the areas I am unsure of.
PHP(updated and solved):
<?php
$con = mysqli_connect("localhost","****","****","db") or die("Connection error: " . mysqli_error($con));
//stored sample value from another table
$user_id = "1";
//Build query: Not sure if this is correct format
$query = "SELECT * FROM client_projects WHERE client_id_1 = $user_id OR client_id_2 = $user_id OR client_id_3 = $user_id";
$result = mysqli_query($con, $query) or die("Query error: " . mysqli_error($con));
//Drop down list
echo '<select id="Projects" class="input">';
echo '<option value="" selected="selected" disabled="disabled">Choose a Project...</option>';
// Loop through the query results, outputing specific options one by one
// Not sure of the loop for the options
while ($row = mysqli_fetch_array($query)) {
echo '<option value="'.$row['project_codename'].'">'.$row['project_codename'].'</option>';
}
echo '</select>';
mysqli_close($con);
?>
You're feeding the $query directly into mysqli_fetch_array(), but this function expects a result resource as an input. You're missing the mysqli_query() call. See Example #2 at manual page
Ok, this is the last part I'm having trouble with in this project (my first php/mysql attempt). The trouble comes in the last 'while' loop. I haven't been able to find a way of assigning values to my array of variables. While when working with one row in the table this format works to get multiple columns, I am looking for a way to get one field from multiple (3) rows. Thoughts?
$x=1;
do{
$sql = "SELECT * FROM`".$tableName."` WHERE `StopId`=".$stopId." AND `Time` >='". $time. "' LIMIT 3";
$result = mysql_query($sql, $conn);
if (!$result){
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
This is the part that is causing me the trouble. It assigns the last result (because it's limited to 3 results) to all of the values. If I change the limit to 1 or 2, it makes all the values either the first or second results. I want the first one in time1, the second one in time2 and the third in time3.
while ($row = mysql_fetch_array($result)) {
$time1[$routeName[$x]] = $row[Time];
$time2[$routeName[$x]] = $row[Time];
$time3[$routeName[$x]] = $row[Time];
}
$x++;
}while(!is_Null($routeName[$x]));
EDIT:
The table is in the format:
| IdNum | StopId | Time |
| 1 | 1 | 12:44 |
| 2 | 2 | 13:15 |
| 3 | 1 | 12:55 |
| 4 | 2 | 14:15 |
| 5 | 1 | 13:20 |
and so on. If I was to have $stopId = 1 and $time = 12:30 I would want to be able to assign:
"12:44" to $time1[$routeName[$x]]
"12:55" to $time2[$routeName[$x]]
"13:20" to $time3[$routeName[$x]]
Also I should add that the query statement is functional.
Edit:
Sorry about that I changed $routeNum to $routeName after the original posting to help clarify what the variable contained. It's just a string title that forms part of the table name.
Well you are looping over only one row at a time remember. So, if you set all three variables at once, they are all going to be the values of the last row. I don't know where your $routeName variable is coming from?? try:
$x = 0;
while ($row = mysql_fetch_array($result)) {
$routeName[$x] = $row['Time'];
$x++;
}
I don't know how you want to format it? If you must have it formatted into separate variables instead of an array, I think you can do this, however I don't know why you would want to format it like that.
$x = 0;
while ($row = mysql_fetch_array($result)) {
${time.$x[$routeName[$x]]} = $row['Time'];
$x++;
}
If you