SQL query in PHP script keeps "losing" one row - php

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.

Related

Php/Mysql count dancers from each moment added issue

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.

PHP MySQL Query to check if record exists or not

I have following data in the table..
+-------------+---------------+--------------+
| activity_id | activity_name | main_unit_id |
+-------------+---------------+--------------+
| 1 | DEA | 67 |
| 2 | DEB | 68 |
| 3 | DEC | 68 |
| 4 | fasdfsadf | 74 |
+-------------+---------------+--------------+
i want to add another activity, but before adding i have to make sure that same activity name is not there against an main_unit_id...
I write following query,
$SQL_CHECK_ACTIVITY = mysql_query(
"SELECT count(*) FROM activities " .
"WHERE main_unit_id = '67' and activity_name = 'DEA'"
);
$RESULT_SQL_CHECK_ACTIVITY = mysql_num_rows($SQL_CHECK_ACTIVITY);
echo $RESULT_SQL_CHECK_ACTIVITY;
then it print 1 which means a activity against this project already exists...
$SQL_CHECK_ACTIVITY = mysql_query(
"SELECT count(*) FROM activities " .
"WHERE main_unit_id = '78' and activity_name = 'afsdaf'"
);
$RESULT_SQL_CHECK_ACTIVITY = mysql_num_rows($SQL_CHECK_ACTIVITY);
echo $RESULT_SQL_CHECK_ACTIVITY;
then it print 1 which means a activity against this project already exists...
but there is no record in this case....
If you want to add another activity, but do not want duplicates on main_unit_id, then the right approach is to create a unique index (or constraint) on the field:
create unique index idx_activities_mainunitid on activites(main_unit_id);
If you attempt to insert a duplicate, the insert will fail.
mysql_num_rows will return the number of rows, not the count(*) result.
In the first test, count(*) will return 1 in one row, so the result will be 1.
In the second test, count(*) will return 0 in one row, so the result would still be 1.
You will need to use a fetch function to get the result of count(*) rather than mysql_num_rows.
Edit
I.e. from:
$RESULT_SQL_CHECK_ACTIVITY = mysql_num_rows($SQL_CHECK_ACTIVITY);
To:
list ($RESULT_SQL_CHECK_ACTIVITY) = mysql_fetch_row($SQL_CHECK_ACTIVITY);
Note: The use of the mysql_* functions are considered deprecated and you should instead use something that offers better security and more functionality, such as MySQLi or PDO.
$SQL_CHECK_ACTIVITY = mysql_query("SELECT * FROM activities WHERE main_unit_id = '".$project."' and activity_name = '67' limit 1");
if(mysql_fetch_row($SQL_CHECK_ACTIVITY)) {
echo 'a activity against this project already exists...';
}
else{
}

PHP Script to fetch new row from mysql on every script execution

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" />

How to increment the search count in php/mysql?

I have a table consists of several fields (id, firstname, surname, username, search_count)
I've build a small search engine that search my table to find any match exists either in the firstname or in the surname and I am getting the results with no problems.
Now, what I am trying to do is to increment the search_count field by 1 every time there is a match!
For example let's say we have the following table users:
id | firstname | surname | username | search_count
1 | John | Mike | un1 | 0
2 | John | Jeff | un2 | 0
3 | Dale | John | un3 | 0
4 | Mike | Gorge | un4 | 0
and let's say we are searching for Jeff as a keyword
so, the query will return 1 record
what I want to do is to increment the search_count by 1 for match record
so the results will be something like as:
id | firstname | surname | username | search_count
2 | John | Jeff | un2 | `1`
and if we make a new search (e.g. John) the results should be something like:
id | firstname | surname | username | search_count
1 | John | Mike | un1 | 1
2 | John | Jeff | un2 | 2
3 | Dale | John | un3 | 1
I've tried several approach but with no luck.. So I appreciate any hints and help
here is my code...
<?php
// open the HTML page
include 'html_open.php';
// require the db connection
require '/inc/db.inc.php';
// require the error messages
require '/inc/echo.inc.php';
if (isset($_GET['keyword'])) {
$keyword = $_GET['keyword'];
if (!empty($keyword)) {
// build our search query
$search_query = "SELECT * FROM `users` WHERE `firstname` = '".mysql_real_escape_string($keyword)."' OR `surname` = '".mysql_real_escape_string($keyword)."' ORDER BY `search_count` DESC";
// run the search query
$search_query_run = mysql_query($search_query);
// search results
$search_results_num = mysql_num_rows($search_query_run);
// check query return results
if ($search_results_num>0) {
echo 'Search engine returns <strong>[ '.$search_results_num.' ]</strong> result(s) for <strong>[ '.$keyword.' ]</strong>:<br>';
// retrieving the information found
echo '<ol>';
while ($search_result_information = mysql_fetch_assoc($search_query_run)) {
//$current_search_count = ;
echo '<li>'.$search_result_information['username'].'. This user has been searched: '.$search_result_information['search_count'].' times before.</li>';
}
echo '</ol><hr>';
include 'search_form.php';
} else {
echo '<hr>Search engine returns no result for <strong>[ '.$keyword.' ]</strong>, please try another keyword.<hr>'; // hint: no result found
include 'search_form.php';
}
} else {
echo $err20_002; // hint: must insert input
include 'search_form.php';
}
} else {
echo $err20_001; // hint: form has not been submitted
include 'search_form.php';
}
// close the HTML page
include 'html_close.php';
?>
P.S. I am new to PHP / MySQL and this is my first code :)
...
while ($search_result_information = mysql_fetch_assoc($search_query_run)) {
# add this following line
mysql_query('UPDATE `users` SET search_count=search_count+1 WHERE id='.$search_result_information['id']);
# Edit. Change result to show new number
$search_result_information['search_count']++; # this adds 1 to the value (does not affect stored data in database)
echo '<li>'.$search_result_information['username'].'. This user has been searched: '.$search_result_information['search_count'].' times before.</li>';
}
...
In your case you need to fetch the found values and perform an update statement adding +1 to the search_count column
$search_query = "SELECT id, firstname, surname, username, search_count FROM `users` WHERE `firstname` = '".mysql_real_escape_string($keyword)."' OR `surname` = '".mysql_real_escape_string($keyword)."' ORDER BY `search_count` DESC";
$search_query_run = mysql_query($search_query);
// search results
$search_results_num = mysql_num_rows($search_query_run);
// check query return results
if ($search_results_num>0) {
echo 'Search engine returns <strong>[ '.$search_results_num.' ]</strong> result(s) for <strong>[ '.$keyword.' ]</strong>:<br>';
// retrieving the information found
echo '<ol>';
while ($search_result_information = mysql_fetch_assoc($search_query_run)) {
//$current_search_count = ;
$update_search = "UPDATE users SET search_count = search_count + 1 WHERE id = {$search_result_information['id']}"; // so every `id` will increment its search_count with 1. You will need to select the rows once again, to take this count, or to manually increment in PHP
mysql_query($update_search);
echo '<li>'.$search_result_information['username'].'. This user has been searched: '.$search_result_information['search_count'].' times before.</li>';
P.S.: Using mysql_* lib is strongly NOT recommended. As you can see from the red box in the official documentation http://www.php.net/manual/en/function.mysql-query.php you should choose one of the current actually supported APIs

What is the correct way to join two tables in SQL?

I have two tables. The first table holds simple user data and has the columns
$username, $text, $image
(this is called "USERDATA").
The second table holds information about which users "follow" other users, which is set up with the columns
$username and $usertheyfollow
(this is called "FOLLOWS").
What I need to do is display the data individually to each user so that it is relevant to them. This means that userABC for instance, needs to be able to view the $text and $image inputs for all of the users whom he/she follows. To do this, I believe I need to write a sql query that involves first checking who the logged in user is (in this case userABC), then selecting all instances of $usertheyfollow on table FOLLOWS that has the corresponding value of "userABC." I then need to go back to my USERDATA table and select $text and $image that has a corresponding value of $usertheyfollow. Then I can just display this using echo command or the like...
How would I write this SQL query? And am I even going about the database architecture the right way?
With tables like so:
userdata table
______________________________
| id | username | text | image |
|------------------------------|
| 1 | jam | text | image |
+------------------------------+
| 2 | sarah | text | image |
+------------------------------+
| 3 | tom | text | image |
+------------------------------+
follows table
_____________________
| userId | userFollow |
|---------------------|
| 1 | 2 |
+---------------------+
| 1 | 3 |
+---------------------+
and use the following SQL:
SELECT userdata.text, userdata.image FROM follows LEFT JOIN userdata ON follows.userFollow = userdata.id WHERE follows.userId = 1
will get all the text and images that user with id '1' follows
As it turns out, neither of these answers were right. #jam6459 was closest.
The correct answer is the following:
SELECT userdata.text, userdata.image, follows.userFollow
FROM userdata
LEFT JOIN follows ON follows.userFollow = userdata.username
WHERE follows.userId = $username
I also found it easier to not have a username correspond to an Id as in jam's table example. This is because the same user can have multiple entries in "USERDATA". I instead used username as the Id.
function get_text_image($username)
{
$sql = "SELECT * FROM USERDATA where username='".$username."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['text'];
echo $row['image'];
}
}
function display_data_of_followers($userid)
{
$sql = "SELECT usertheyfollow FROM follow WHERE userid = ".$userid."";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
get_text_image($row['usertheyfollow']);
}
}
display_data_of_followers($userid);

Categories