PHP Fetch row data from Mysql via ID - php

I am new to php. I have the following code that auto fetches all the rows and columns from the db. I want to make the script to fetch a particular row using its ID column. for example: www.site.com/view.php?id=22
I am trying to get it work with the $_GET['link']; variable like this:
if (isset($_GET['id'])) {
$result = mysqli_query($connection,"SELECT * FROM $_GET['link']");
} else {
$result = mysqli_query($connection,"SELECT * FROM reservations");
}
But I am unable to get it work.
The complete code is as below:
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT * FROM reservations");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
Any help would be appreciated..

You can do this
Add
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
and change this
mysqli_query($connection,"SELECT * FROM reservations");
to this
$result = mysqli_query($connection, $query);
In the above code I added a bit of security so that if $_GET['id'] is not a valid integer it will revert to query where it fetches all the data. I added that because you should never put $_GET directly into your query.
Here is a your code I have modified it to your requirements
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
//get results from database
$result = mysqli_query($connection, $query);
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";

if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id=NULL;
}
$sql = "SELECT * FROM reservations WHERE id = '".$id."'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) == 1) {
dd($row);
} else {
echo "no records found with this id";
}
Hope this script meets your answer

Related

display mysql table with a field as the main header

I have a mysql data table that I am displaying on a php page. It works but I would like them be grouped under the departments they belong to. Also to remove all other field headers such as Name,Phone Email.
I tried using SORT BY but nothing happened.
eg. This is how I would like it to look like
Vehicle Department
Bob 3234234 bob#acas.com
Hanna 3434323 Hanna#asas.com
Workshop Department
Andrew 45454523 andrew#aasdasd.com
This is how it currently looks:
ID Name Phone Email Department
1 Bob 3234234 bob#asasdas.com Vehicle Department
2 Hanna 3434323 hanna#asasdas.com Workshop Department
my current code:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '*****';
$database = 'list';
$table = 'users';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
$temp = "";
while($row = mysql_fetch_row($result))
{
echo "<tr>";
if ($row['department'] != $temp){
echo "<td colspan=\"3\">" . $row['department'] . "</td></tr>\n<tr>";
$temp = $row['department'];
}
echo "<td>" . $row['name'] . "</td><td>" . $row['phone'] . "</td><td>" . $row['email'] . "</td>";
echo "</tr>\n";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?>
If you use
"SELECT name, phone, email, department FROM {$table} ORDER BY department"
as your query, it will return only your desired columns, ordered by the department column.
Then you can arrange them in your table depending on their department.
Note that you might have to adjust the column names.
Try this code:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '*****';
$database = 'list';
$table = 'users';
$conn = mysqli_connect($db_host, $db_user, $db_pwd) or die("Connecting to database failed");
mysqli_select_db($conn, $database) or die("Can't select database");
// sending query
$result = mysqli_query($conn, "SELECT name, phone, email, department FROM {$table} ORDER BY department");
if (!$result) {
die("Query to show fields from table failed");
}
echo "<table border='1'><tr>";
// printing table rows
$temp = "";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
if ($row['department'] != $temp){
echo "<td colspan=\"3\" align=\"center\">" . $row['department'] . "</td></tr>\n<tr>";
$temp = $row['department'];
}
echo "<td>" . $row['name'] . "</td><td>" . $row['phone'] . "</td><td>" . $row['email'] . "</td>";
echo "</tr>\n";
}
mysqli_free_result($result);
echo "</table>"
?>
First, you have to process the data to arrange in a structure you want for it.
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '*****';
$database = 'list';
$table = 'users';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<table border='1'><tr>";
// printing table headers
for ($i = 0; $i < $fields_num; $i++) {
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
//variable to store rearranged results;
$resultsModified = [];
// printing table rows
while ($row = mysql_fetch_row($result)) {
if (!isset($resultsModified[$result['department']]))
$resultsModified[$result['department']] = [];
$resultsModified[$result['department']][] = $row;
}
foreach ($resultsModified as $daptName => $results) {
echo "<caption> $daptName </caption>";
foreach ($results as $row) {
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach ($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
}
mysql_free_result($result);
However I have not tested it but this should work.

PHP Array ForEach SQL Query

I am trying to use a FOREACH loop to query a database based on each value in the $userid array below. I am also looping through the $grade array as I need the corresponding value for the sql query to then put into a HTML table.
//Decode JSON file to an Object
$json_d = json_decode(file_get_contents("results.json"));
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<table><tr><th>First Name </th><th>Last Name </th><th>Grade </th></tr>";
foreach($userid as $id) {
foreach($grade as $grd) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["firstname"]. "</td><td>" . $row["lastname"]. "</td><td> " . $grd . "</td></tr>";
}
} else {
echo "ERROR!";
}
}
}
echo "</table>";
mysqli_close($conn);
I have checked the $grade and $userid array and they do contain the correct values however running the PHP file I only get the first record outputted in the table. E.G.
FirstName LastName Grade
Student 1 85
Whereas I need the other 2 records that are supposed to appear.

link to specific user profile php

I'm creating a search bar feature on my website where the user can search for users using a name.The search result may come up with multiple users with similar names (ex. if I search "Jenna", my database may have multiple users with the name "Jenna" so multiple results will show).I want the user to be able to click on one of the profiles and see that specific "Jenna's" user profile. Kind of like Twitter, where I can search for accounts and view different profiles. Right now I have code that returns the search and also makes the search result a clickable link. However, when I try to save the user id, it only saves the latest user id.
home.php (where the search bar for users is0
<form method="GET" action="search.php" id="searchform">
Search for users:
<input type="text" name="search_user" placeholder="Enter username">
<input type="submit" name="submit" value="Search">
</form>
search.php (prints out the users with the name that the user is searching for)
session_start();
$user = '';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$search_user = $_GET['search_user'];
$sql = "SELECT * FROM users WHERE username LIKE '%$search_user%'";
$result = mysqli_query($link, $sql);
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a';
$b = ' href="';
$c = 'user_profiles.php';
$d = '">';
$e = $row['username'];
$f = '</a';
$g = '>';
$_SESSION['user'] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a.$b.$c.$d.$e.$f.$g;
header("Location: user_profiles.php");
}
}
user_profiles.php (supposed to be where a specific user's profile is shown, based on the link the user clicks with the specific userID)
session_start();
$userID=$_SESSION['user'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '</div>';
}
I get where my mistake is, the while loop in search.php will only save the latest userID so the link will always take me to the user profile with that useriD. I'm just not sure how to implement it so that when the user views the list of profiles, the link they click will take them to a specific profile based on the user id.
You need to do changes in search and user.php files :
Search.php :
<?php
session_start();
$user = '';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link, "GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$search_user = $_GET['search_user'];
$sql = "SELECT * FROM users WHERE username LIKE '%$search_user%'";
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['user_id'];
?>
<a href="user_profiles.php?id=<?php echo $id; ?>" >
<?php echo $row['username']; ?>
</a>
<?php
$_SESSION['user'] = $row['user_id'];
$userID = $_SESSION['user'];
header("Location: user_profiles.php");
}
}
User_profile.php:
$userid = $_GET['id'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query = "SELECT * FROM dataTable WHERE user_id='$userid'";
$results = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output = $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . "<br>" . "<br>";
$output = $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . " hrs" . "<br>" . "<br>";
$output = $row["date_"];
echo "Date: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . "<br>" . "<br>";
echo '</div>';
}
Very first thing, you are saving multiple user ids to a string.
Another thing, you are saving it in while loop.
Therefore, latest value updates old value.
In your case, it will always save the last value. That is prime issue.
You can take array of user ids and save them in it.
$userIds = array();
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a';
$b = ' href="';
$c = 'user_profiles.php';
$d = '">';
$e = $row['username'];
$f = '</a';
$g = '>';
$userIds[] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a.$b.$c.$d.$e.$f.$g;
header("Location: user_profiles.php");
}
$_SESSION['user'] = $userIds;
And in your user_profiles.php, loop over the array or use MySQL IN() condition to get all user profiles.
Also, why did you take too many variables for html link. You can do it in single variable using concatenation like following:
$userIds = array();
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a'
. ' href="';
. 'user_profiles.php';
. '">';
. $row['username'];
. '</a';
. '>';
$userIds[] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a;
header("Location: user_profiles.php");
}
$_SESSION['user'] = $userIds;
Another mistake is that you are echo ing HTML link and doing redirection.
That will cause headers already sent... error.
This will display list of users with searched string
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_assoc($result)) {
$link="<a href='user_profiles.php?user_id=".$row['user_id']."'>".$row['username']."</a>";
}
}
After clicking on link it will redirect to user_profiles.php (no need to header. header is used for automatic redirection)
In user_profiles.php
session_start();
$userID=$_GET['user_id'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '</div>';
}

Query MySQL using Joomla syntax

The following query is returning the result I expected:
$link=mysqli_connect('localhost','user','pass');
if(!$link){
echo "No connection!";
exit();
}
if (!mysqli_set_charset($link, 'utf8'))
{
echo 'Unable to set database connection encoding.';
exit();
}
if(!mysqli_select_db($link, 'database')){
echo "No database";
exit();
};
$res = $link->query("SELECT rules FROM xmb9d_viewlevels WHERE id=10");
while ($row = $res->fetch_array()) {
echo " cenas = " . $row['rules'] . "\n";
};
But, since I'm using Joomla 2.5.16 and I'm trying to keep its syntax, I tried:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$res = $db->query("SELECT rules FROM #__viewlevels WHERE id=10");
while ($row = $res->fetch_assoc()) {
echo " cenas = " . $row['rules'] . "\n";
};
This isn't working. It is only displaying the text " cenas =".
What is wrong with this code?
Try the following:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('rules'))
->from($db->quoteName('#__viewlevels'))
->where($db->quoteName('id')." = ".$db->quote('10'));
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result) {
echo " cenas = " . $result->rules;
}

SELECT * FROM Table Where ID

I am trying to retrieve information from my database depending on the ID a user types into my URL.
For example: If USER A went to www.exampleurl.com/index.php?id=1 it would echo out the user's information which has an ID of 1. Same thing if the id was 2, 3, etc. Users are entering their information via a form in a different file called submit.php.
Here is my code to retrieve data depending on ID :
<?php
$id = $_GET['id'];
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
echo "Hello, " . $result['name'];
?>
Any ideas on if my SELECT request is wrong?
EDIT
Here is my code for showing the data altogether in a table. This works fine.
<?php
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "!";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query, $con);
echo "<table border=1>
<tr>
<th> ID </th>
<th> Name </th>
<th> Age </th>
</tr>";
while($record = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['name'] . "</td>";
echo "<td>" . $record['age'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
→ Try This:
You should consider using PHP PDO as it is safer and a more object oriented approach:
$usertable = "";
$database = new PDO( 'mysql:host=localhost;dbname=DB_NAME', 'DB_USER_NAME', 'DB_USER_PASS' );
$statement = $database->prepare('SELECT * FROM $usertable');
$statement->execute();
$count = $statement->rowCount();
if( $count > 0 ) {
$R = $statement->fetchAll( PDO::FETCH_ASSOC );
for( $x = 0; $x < count($R); $x++ ) {
echo "<tr>";
echo "<td>" . $R[ $x ]['id'] . "</td>";
echo "<td>" . $R[ $x ]['name'] . "</td>";
echo "<td>" . $R[ $x ]['age'] . "</td>";
echo "</tr>";
}
}
else { echo "Error!"; }
you need to use mysql_fetch_assoc function for retrieve the results.
$result = mysql_fetch_assoc(mysql_query($query, $con));
echo "Hello, " . $result['name'];
You should be error checking your mysql_querys:
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
if(!result)
echo mysql_error();
You should also retrieve the results:
$array = mysql_fetch_assoc($result);
I'll consider some secure features like
Check if $_GET['id'] is set and if is int
Apply Mysql escape with mysql_escape_string() function

Categories