problem with PHP looping through members - php

I am having a problem with my updation script, basically if I keep the line as mysql_fetch_row then it only seems to want to insert every other member into the database, but if I change it to mysql_fetch_array then it inserts each member twice, but still not all the users from the database. I have just shown the start of the script below as I am pretty sure this must be where the error is.
Any help with this would be fantastic. Cheers.
$result = mysql_query("SELECT member_id FROM members ORDER BY member_id");
while ($member = mysql_fetch_array($result)){
foreach ($member as &$member_id){
$results_query = mysql_query("SELECT driver1 as driver1, driver2 as driver2, driver3 as driver3, driver4 as driver4, team as team, engine as engine, total_points as total FROM members WHERE member_id = '$member_id'")
or die ("Failed to update" . mysql_error());
$userteam = mysql_fetch_assoc($results_query);
//this is the bottom of the script after calculations have take place and the insert into the database//
$results_query = mysql_query("INSERT INTO member_results (member_id, track_id, driver1, driver2, driver3, driver4, team, engine, driver1_points, driver2_points, driver3_points, driver4_points, team_points, engine_points, qualifying_points, race_points, total_points)
VALUES ('$member_id', '$track', '$userteam[driver1]', '$userteam[driver2]', '$userteam[driver3]', '$userteam[driver4]', '$userteam[team]', '$userteam[engine]', '$userpoints[driver1]', '$userpoints[driver2]', '$userpoints[driver3]', '$userpoints[driver4]', '$userpoints[team]', '$userpoints[engine]', '$userpoints[qualifying]', '$userpoints[race]', '$userpoints[total]')")
or die ("Failed to update" . mysql_error());
$userteam["total"] += $userpoints["total"];
$results_query = mysql_query("UPDATE members SET total_points = '$userteam[total]' WHERE member_id = '$member_id'")
or die ("Failed to update" . mysql_error());
}
}

You shouldn't need a foreach loop when using mysql_fetch_array. The reason your query is being entered twice is because mysql_fetch_array fetches both an associative array and a numerical array for the row data, so it's looking at both of them and inserting the data twice, one for each array.
$member doesn't require a foreach for this reason. $member is just one row being pulled, not the entire data set. An associative array returns the column names as array keys.
while ($member = mysql_fetch_array($result)){
$results_query = mysql_query("SELECT driv1 as drivone, driv2 as drivtwo,
driv3 as drivthree, driv4 as drivfour, team as teamone,
eng as engone, total_points as total FROM members WHERE member_id = '$member['member_id']'") // If member_id is the column name for the ID
or die ("Failed to update" . mysql_error());

mysql_fetch_array returns multiple arrays(associative array, a numeric array, or both)
thats why its inserting twicein your foreach, and could be the reason why your script is breaking.
try var_dumping $member to see what syntax you can use to refine your foreach
see documentation here:
http://php.net/manual/en/function.mysql-fetch-array.php

Use mysql_fetch_assoc($result) or mysql_fetch_array($result, MYSQL_ASSOC);
by default mysql_fetch_array return:
the NUM indexation ( array( 0 => ..., 1 => ...)),
but also merge-in the assoc indexation ( array( 'fieldname' => ... , 'colname' => ...))
So your code should look like:
** Note that've removed the foreach.
$result = mysql_query("SELECT member_id FROM members ORDER BY member_id");
while ($member = mysql_fetch_assoc($result)){
$member_id = $member['member_id'];
//foreach ($member as &$member_id){
$results_query = mysql_query("SELECT driver1 as driver1, driver2 as driver2, driver3 as driver3, driver4 as driver4, team as team, engine as engine, total_points as total FROM members WHERE member_id = '$member_id'")
or die ("Failed to update" . mysql_error());
$userteam = mysql_fetch_assoc($results_query);
//...

Related

Why the 2d array treatment in PHP isn't good?

I'm trying to build a 2d array in PHP with two loops using two different queries.
for some reason the page is not showing any message about any error that occurred.
It just reacts like the array doesn't exist.
Therefore I am assuming its because I did't handle the array right.
This is the code:
$stuarr= array(); ***//the 2d array initialization***
$query1 = "SELECT * FROM students WHERE userid= '$uid' ORDER BY name";
$stulist = mysqli_query($conn,$query1) or die ("cannot query the table1 " .mysqli_error($conn));
while ($students = mysqli_fetch_array($stulist)) {
${$students['name']}= array(); ******//the inside array initialization...the one that will insert to $stuarr***
$count=$_SESSION['counter'];
$sname=$students['name'];
$query3 = "SELECT * FROM ranks WHERE userid= '$uid' AND rankers='$sname' ORDER BY therate DESC";
$stur = mysqli_query($conn,$query3) or die ("cannot query the table1 " .mysqli_error($conn));
while ($sturank = mysqli_fetch_array($stur) && !$count==0) {
array_push(${$students['name']},$sturank['rated']);
$count=$count-1;
print_r(${$students['name']});
}
array_push($stuarr,${$stulist['name']});
print_r($stuarr); ***///this print is showing nothing***
}
I would love to hear your opinion about the code.
thank you!
Change
array_push($stuarr,${$stulist['name']});
into
array_push($stuarr,${$students['name']});

Retrieving the Last ID from the Database from a Specified Category in String Value

I am trying to retrieve the last ID from the database and increment it by one. My problem is that I am not able to retrieve it in a particular category. For instance, I have categories with a string value of A, B and C. The category with a string value of A will return only id starting from 1 as 10001, 10002 and the last ID to be retrieved is 10002 plus 1 so that the ID to be displayed is 10003.
Category "B" will return 20002 and category "C" will return 30002.
Here is my code:
<?php
$con = mysql_connect("server","username","password","db_name") or die (mysql_error());
mysql_select_db($con, 'db_name');
$sql = "Select `id` from `tbl_violation` WHERE `category` = 'A' ORDER BY `category` DESC LIMIT 1";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result, $con))
{
$i = $row['id'];
$i++;
echo "DLR - " .$i;
}
?>
The error is this:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in ...
Notice: Undefined variable: i in ...
First I must say again... Stay away from mysql_connect() and all other mysql_* functions. If you want a simple fix, just replace it with mysqli_ functions and make sure you escape ALL user provided input. A bit of reading But I would recommend to look into PDO.
That out of the way, your MYSQL problem is easy. You want to GROUP the elements so all the rows with same category column are groupped together and then select the maximum for each group. Your SQL would then be:
SELECT category, MAX(id) AS highest_id FROM tbl_violation GROUP BY category;
see this fiddle I made with a similar table.
You can then access the results you get from mysqli_query function the same way you do now...
while($row = mysqli_fetch_array($result, $con))
{
$i = $row['highest_id'];
$i++;
$category = $row['category'];
echo "$category - $i";
}
You can use SELECT MAX to get the highest id. I am assuming that id is not unique. If so, remove the WHERE statement from the query. Try the following.
<?php
$con = mysql_connect("server","username","password","db_name") or die (mysql_error());
mysql_select_db("database");
$sql = "Select MAX(`id`) from `tbl_violation` WHERE `category` = 'A";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result))
{
$i = $row['id'];
echo "DLR - " .$i++;
}
?>
Also I would like to add that I agree with flynorc. Use PDO or mysqli.
Use
ORDER BY `id` DESC
Instead of
ORDER BY `category` DESC

Get last entry in MYSQL database table using PHP

I know this question has been asked multiple times on here but each one is a little different.
I have a table in my database with the columns entry_id(INT- Auto_Increment), user_id(INT), firstname(VARCHAR), lastname(VARCHAR) and comment(VARCHAR).
My script is pretty much a very basic timesheet I have tried creating, the user_id, firstname and lastnames are set when the user visits the script. So what I need to do is check the last comment cell for that user to see if the comment is either "in" or "out".
Whenever I try building my query and checking if the last comment in that users field is either in or out, I visit my script and it doesn't print the comment, what am I doing wrong?
$userid = $_SESSION['user_id'];
$query = mysqli_query($mysqli, "SELECT entry_id, user_id FROM timesheet WHERE user_id = '$userid' ORDER BY entry_id DESC LIMIT 1") or die('Error: ' . mysqli_error($mysqli));
if(mysqli_num_rows($query)>0){
while ($row = mysqli_fetch_array($query, MYSQL_ASSOC)) {
echo '<pre>';
print_r($row);
echo '</pre>';
$clock = $row['comment'];
echo $clock . ' Last entry';
}
Couple of notes:
I AM connected to the database and get a simple query to work.
The userid session is set.
Prior to asking this question I looked at the answers here and here.
Here is what $row is printing, notice how comment is empty although I know I have a value in the database.
Array
(
[entry_id] => 4
[user_id] => 3
[comment] =>
)
Just as you seen on comments, you trying to access an index which is not included with the one you queried that's why you dont get any results.
$userid = $_SESSION['user_id'];
$query = mysqli_query($mysqli,
"SELECT
entry_id,
user_id,
comment <-- you're trying to access comments, but didn't include that column in the query
FROM timesheet
WHERE user_id = '$userid' ORDER BY entry_id DESC LIMIT 1")
or die('Error: ' . mysqli_error($mysqli));
if(mysqli_num_rows($query) > 0){
while ($row = mysqli_fetch_assoc($query)) {
echo $row['comment'] . ' Last entry <br/>';
}
}
If you've had turn on error reporting:
error_reporting(E_ALL);
ini_set('display_errors', '1');
You should have seen that undefined index comment.

PHP SQL query error - Unknown array column in WHERE clause

My page displays the name of players of a certain sports team using drop down menus. The coach can log in to pick his team and select the opposition which his team will play against.
When user has selected the team and opposition he clicks submit and the isset function is triggered.
Now I capture the values from the drop down menus and upload it to the correct table in the DB. Everything is pretty straight forward however when I click submit I get the error in the tittle. Any help would be appreciated
if ( isset($_POST['submit']) ) {
$player_ids = array_map('intval', $_REQUEST['players']);
$opponents_id = $_REQUEST['players'];
var_dump($player_ids);
var_dump($opponents_id);
$query = 'SELECT `name`, `position`
FROM `player_info`
WHERE `player_id` IN (' . implode(',', $player_ids) . ')';
$return_names = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_assoc($return_names) )
{
$selected[] = $row['name'];
$position[] = $row['position'];
}
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` = $opponents_id")
or die (mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($query))
{
$fixture_id[] = $row['fixture_id'];
}
for ($i=0; sizeof($selected) > $i; $i++){
$sql = mysql_query("INSERT INTO `team` (`selection_id`, `fixture_id`, `player_position`,`player_name`)
VALUES ('$fixture_id[$i]','$position[$i]','$selected[$i]')")
or die(mysql_error());
echo $selected[$i];
echo $position[$i];
echo $fixture_id[$i];
echo'<br>';
}
The Unknown column 'Array' in 'where clause' error means literally what it says -- you tried to put an array value into your where clause.
In this line:
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` = $opponents_id")
or die (mysql_error());
You are using the $opponents_id variable which your var_dump shows is an array containing five values. So, you need to use the IN clause and list them out (just like you did for $player_ids):
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` IN (" . implode(",", $opponents_id) . ");")
or die (mysql_error());
Note: Hopefully you are aware of the tiring subject of the mysql_* family of functions. These are being deprecated and are insecure. I wrote about it a while back: http://www.jorble.com/2012/06/you-are-vulnerable-for-sql-injection/
bodi0 is right, your $opponents_id is an array , if it must be an array so do some things like that
$opponents_id_text=implode(',',$opponents_id);
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` in ($opponents_id_text)")
or die (mysql_error());
The problem is in your second SQL query:
WHERE `fixture_id` = $opponents_id" -
Here the $opponents_id is array (it is converted automatically to array when you assign the value to it from the $_REQUEST, because the HTML component select sends the options as array).
Just implode() it also, like you did for $player_ids.
you did not specified Array properly in sql query.
when we use Arrays we have to specify array number in query

'Counting' the number of records that match a certain criteria and displaying the numbers (using PHP and MySQL)

I have a MySQL database containing a user's country and whether they are an individual or an organisation. The field names are 'country' and 'type'.
Using PHP, I'd like to 'count' the number of countries, the number of individuals and the number of organisations in the database and then display the numbers in the following example format:
<p>So far, <strong>500</strong> individuals and <strong>210</strong> organisations from <strong>40</strong> countries have registered their support.</p>
I am currently listing the total number of records using the below code if this helps:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$result = mysql_query("SELECT * FROM table_name", $link);
$num_rows = mysql_num_rows($result);
echo " $num_rows\n ";
?>
My PHP / MySQL skills are very limited so I'm really struggling with this one.
Many thanks in advance!
Ben
To get the number of countries:
SELECT COUNT(DISTINCT country) AS NumCountries FROM tableName
To get the number of individuals, or the number of organisations:
SELECT COUNT(*) AS NumIndividuals FROM tableName WHERE type = 'individual'
SELECT COUNT(*) AS NumOrganisations FROM tableName WHERE type = 'organisation'
What you are looking for is a count based on a grouping. Try something like this:
$sql = "SELECT type, count(*) as cnt FROM users GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
This will give you an array like
Array (
'individual' => 500,
'organization' => 210
)
For counting the countries, use the first statement as posted by Hammerite.
EDIT: added a verbose example for counting the countries
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM users";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
This altogether you can then print out:
printf('<p>So far, <strong>%d</strong> individuals and <strong>%d</strong> '.
'organisations from <strong>%d</strong> countries have registered '.
'their support.</p>', $counts['individual'], $counts['organization'],
$number_of_countries);
The answer is to retrieve the answer by using the COUNT(*) function in SQL:
SELECT COUNT(*) AS individual_count FROM user WHERE type = 'individual';
SELECT COUNT(*) AS organization_count FROM user WHERE type = 'organization';
SELECT COUNT(*) AS country_count FROM user GROUP BY country;
The last will group your query set by the country name, and will result in one row for each country. Using COUNT on this result set will give the count of distinct coutries.
You can then fetch this value by using mysql_fetch_assoc on your $result from mysql_query, and the answer will be contained in 'invididual_count', 'organization_count' and 'country_count' for each query.
Thank you for all of your help with this (especially Cassy).
I think it's worthwhile displaying the full code in case anybody else comes across a similar requirement in the future:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$sql = "SELECT type, COUNT(*) as cnt FROM table_name GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM table_name";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
printf('<p><strong>So far, <em class="count">%d</em> individuals and <em class="count">%d</em> organisations from <em class="count">%d</em> countries have registered their support.', $counts['Individual'], $counts['Organisation'], $number_of_countries); ?>
If you're just looking for the number of rows returned try this:
$result = mysql_db_query($db, $query);
$num_rows = mysql_num_rows($result);
Another option would be to execute a separate query with the mysql count function and use the result from that.

Categories