Updating PHP shows double data where it shouldn't - php

So me and my group of students are making a web application for a company. On this page we're trying to show different startup companies with different group numbers. We'd also want to have the option to update this number. The update part works fine and it shows the right group number behind someone his/her name. The real problem here is, if I update one of the different group numbers and reload the page, all of the groups have the same number as shown on the webpage, but in the database it shows the correct number that i've updated.
So I would like to have the right update number shown right away. This is my php code down below.
<?php
session_start();
require 'header.php'; //
require 'includes/dbh.inc.php';
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$update = mysqli_real_escape_string($conn, $_POST['group']);
$sql = "SELECT user_uid, user_name, group_id, active FROM groups";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
if(!isset($_POST['groupnumber'])) {
$gnum = $row['group_id'];
}
else {
$gnum = $update;
}
echo "<br> Name : " . $row["user_name"] . " - Group number:" . $gnum . "<br> Select new group" .
"<form method='post'>
<input type='text' name='group'>
<button name='groupnumber' value='". $row['user_uid'] ."'> Update </button>
</form>". "<br>";
}
} else {
echo "0 results";
}
if(isset($_POST['groupnumber'])){//if the submit button is clicked
$id = mysqli_real_escape_string($conn, $_POST['groupnumber']);
$update = mysqli_real_escape_string($conn, $_POST['group']);
$query="UPDATE groups SET group_id='$update' where user_uid = $id";
$conn->query($query) or die("Cannot update");//update or error
}
$conn->close();
?>
Sorry if it's kinda messy, I'm still a student and i'm just a basic PHP guy :)

Of course it does, that's what you have in your while-loop, here:
if(!isset($_POST['groupnumber'])) {
$gnum = $row['group_id'];
}
else {
// On a POST always show the posted value for all groups
$gnum = $update;
}

Related

Creating An Array from MYSQLI query

I am updating all my code to Mysqli, before I did I had this code and it worked:
while($row = mysql_fetch_assoc($WildHorses)){
$InWild[] = $row['id'];
}
$RandomWild = array_rand($InWild);
$RandomHorse = $InWild[$RandomWild];
This is my SELECT statement:
$sql = "SELECT Horse.id, Horse.Name, Horse.Age, Horse.Image_name, Horse.Owner, Horse.Barn, Images.Image_path, Images.Image_name FROM Horse, Images WHERE Horse.Owner = '$colname_WildHorseList' AND Images.Image_name = Horse.Image_name";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " Name: " . $row["Name"]. " ImageName: " . $row["Image_name"]. "<br>";
}
} else {
echo "0 results";
}
The SELECT statement ends up echoing all of the correct information, but I want to make an array of only the Id's so that I can pick one at random each time a button is clicked.
I have tried multiple different copies and pastes of code to try and get what I want, but nothing seems to come out right.
Can someone point me in the right direction or explain what I'm doing wrong?
In your while loop you can simply do this :-
$i=0;
$animals=array();
$animals[$i]=$row["id"]; //puts id in array
And then you can create a random number by "rand()" between the length of 0-$i
and can get the job done.

Selecting rows between two dates in SQL with PHP

I'm trying to get rows from my database between two dates. I've used other questions here to get to this point, but I don't know how to move forward from here.
Here is the code, and underneath are the screenshots of the output and a photo running the query in SQL.
Thanks for the help in advance!
--
This first section of code outputs the ID, name, etc.
<?php
$sql = "SELECT * FROM songs ";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["ID"] . " - Name: " . $row["name"] . " " . $row["released"]. "<br>";
}
} else {
echo "0 results";
}
/* close connection */
$link->close();
?>
This section of code outputs "0 Results"
<?php
$from_date = '2015-01-01';
$to_date = '2017-04-04';
$sql = "SELECT * FROM songs WHERE released BETWEEN '" . $from_date . "' AND '" . $to_date . "' ";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["ID"] . " - Name: " . $row["name"] . " " . $row["released"]. "<br>";
}
} else {
echo "0 results";
}
/* close connection */
$link->close();
?>
This is what the page looks like with the above code.
I've successfully selected the rows in SQL.
EDIT: I made a mistake when writing the code into the question for the IF ELSE statement on the 2nd block of code. I just updated it to what I actually have on the site. I didn't change anything based on the solutions, and am still not getting the rows to print.
You done everything right, except using while/else ;
Your code (2-nd) section should look like this:
if ($result->num_rows > 0) {
while () {
//print your rows
}
} else {
//Say that there's 0 results
}
Your results are listed - as you can see from your screenshot. Problem: While along with else does not make sence.
your last example is missing a } so it says: while { } else { echo "0 results"}
But the echo "0 results" should be related to the num_rows-check, not to the while.
Ah man, I just needed to had to comment out this line from the first block:
$link->close();
I apologize to everyone who answered if it wasn't clear that the blocks of code followed one another. Anyways, for anyone else with the same problem, don't close the connection -_-
Here's what is output when I comment out the line from the first block

How to retrieve the name of a link?

I have a database and I generated a code that creates links depending on the name of the person in the database and I want the names to be
"sent" in the next page ( link's page). So I used the method "get" to do that but it does not work and I don't know why.
$sql = "SELECT * FROM table_personne; ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo ("<a href=\"traitement.php?firsname=".$row["firsname"]."%"."&lastname=".$row["lastname"]."%".">".$row["firsname"]. " ".$row["lastname"]);
echo "<br>";
}
} else {
echo " 0 results";
}
The URL that is created is: traitement.php?prenom=paul%&nom=vincent%>paul%20vincent
Problems: The URL does not match the name of the person displayed and the lastname is "vincent%>paul" meaning lastname=$GET["lastname"]= "firstname%lastname<" and there is no $GET["firstname"].
Thanks a lot.
What about this :
echo (''.$row["firstname"]. " ".$row["lastname"]).'';
Maybe You have to change this :
$row["firsname"]
to
$row["firstname"]

Return Specific Row From DB

I have multiple links on a page where each link is suppose to return a specific row of data from a database. When the link is clicked, the user is forwarded to another page where the info associated with that link is displayed. Here is the code:
//db connection: (using xampp)
mysql_connect('localhost', 'root', '');
mysql_select_db('db_name');
$sql = "SELECT * FROM user_input";
$records = mysql_query($sql);
//code:
<div>
$open_report = mtsql_fetch_assoc($records);
echo "Error Report# {$open_report['id']};
echo "<p>" .$open_report['comments'] . "</p>";
</div>
The problem is it always returns the same row of data. Each row in the db is associated with a link and when that link is clicked I want to return the associated row of data in the db. I think it may have to do with this line: $sql = "SELECT * FROM user_input"; but I'm not sure how to fix it. If anyone can help it would be greatly appreciated.
I have restructured my answer to give it a better flow. I also noticed you are using mysql_ not mysqli_ . You need to use mysqli_ as mysql is depreciated.
EDIT: This would be the page that displays all the error reports. You would want to output them in the form of a hyperlink that passes a GET parameter to the page that shows the details.
$sql = "SELECT ID, Description, etc, etc from reports";
$open_reports = mysqli_query($sql);
//error check here as well if ANY results were returned
while($row = mysqli_fetch_array($open_reports, MYSQLI_ASSOC)) {
echo ''' . $open_reports['Description'] . '';
}
This will give you links that look like
detailspage.php?id=1 detailspage.php?id=2
etc...
On the "detailspage.php" You can capture that ID and display dynamic information on that same page.
if (isset($_GET['ID'])){
$sql = "Select * from user_input where ID='" . $_GET['id'] . "'";
$records = mysqli_query($sql)
while($open_report = mysqli_fetch_array($records, MYSQLI_ASSOC)) {
echo "Error Report# " . $open_report['id'] . "<br/>";
echo "<p>" .$open_report['comments'] . "</p>";
}
}

no results shown when I enter the if statement

This is the part of the PHP code I am having the issue:
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_fetch_array($result) == False) echo "Sorry, no clients found";
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo "<br />";
echo $list;
}
Even if I insert an existing idcard value I get no output when there is the if statement, an incorrect idcard displays "Sorry, no clients found" fine. However if I remove the if statement if I enter an existing idcard the data displays ok.
Can you let me know what is wrong with the code please ?
Thanks
Use mysqli_num_rows to count the results:
if(mysqli_num_rows($result) == 0) echo "Sorry, no clients found";
mysqli_fetch_array() fetches an item from the database.
This means your if() code fetches a first item from the database.
Then, when you call mysqli_fetch_array() again from the while() condition, the first item has already been fetched, and you are trying to fetch the second one ; which does not exist.
You must ensure that you use the result from mysqli_fetch_array() and not call it one time just for nothing ; or, as an alternative, you could use the mysqli_num_rows() function (quoting) :
Returns the number of rows in the result set.
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
}else{
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo $list . "<br />";
}
}
Try this.
EDITED: Added closing bracket.
Use mysqli_num_rows() to test if there is anything returned.
Imagine you put some money in your pocket.
Eventually an idea came to your mind to see if you are still have the money.
You are taking it out and count them. All right.
Still holding them in hand you decided to take them from pocket. Oops! The pocket is empty!
That's your problem.
To see if you got any rows from the database you can use mysqli_num_rows(). It will return the number of bills, without fetching them from the pocket.
The problem is, that you try to use mysqli_fetch_array to queck for the number of results. mysqli_fetch_array will fetch the first result, compare it to false and then discard it. The next mysqli_fetch_array will then fetch the second result, which is not existing.
If you want to check if any clients where found, you can use mysqli_num_rows like this:
$idcard = mysqli_escape_string($dbc, $idcard); // See below: Prevents SQL injection
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query) or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
} else {
while($row = mysqli_fetch_array($result)) {
// Do whatever you want
}
}
If $idcard is a user supplied value, please look out for SQL injection attacks.

Categories