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
Related
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
i have 2 html table one is table.php and anther one is viewdata.php. In frist table there arenumber of rows and data is extracting from mysql database. If i will click on serial no 1 of my html table data then the detail of serial no 1 must show in another table and i tried so. But i dont understand how to do it.
table.php
this is the html table
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass)
or die ('Error connecting to mysql');
$dbname = 'form_db';
mysql_select_db($dbname);
$query = "SELECT * FROM form";
$result = mysql_query($query)
or die(mysql_error());
print "
<table id=\"AutoNumber2\" border=\"1\">
<tr>
<th>S.no</th>
<th>Title of thesis:</th>
<th>View detail:</th>
</tr>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
print "<tr>";
print "<td>" . $row['s_no'] . "</td>";
print "<td>" . $row['title of thesis'] . "</td>";
print "</tr>";
}
print "</table>";
?>
dataview.php another table
<?php
$query = "SELECT * FROM form";
$result3 = mysql_query($query)
or die(mysql_error());
$result3 = mysql_query("SELECT * FROM form where s_no='11'");
while($row3 = mysql_fetch_array($result3, MYSQL_ASSOC)){
$s_no=$row3['s_no'];
$obs_time=$row3['obs_time'];
$title=$row3['title'];
$type=$row3['type'];
$thesis=$row3['thesis'];
$year=$row3['year'];
$proposer=$row3['proposer'];
$institute=$row3['institute'];
$email=$row3['email'];
$present=$row3['present'];
$date=$row3['date'];
}
?>
Here I have mannualy select the s_no'11'. I dont know how i can pass the s_no automatically simply clicking on the row (view detail) which i want to show in another table with its detail. thank you so much./!!
send the variable via the URL using $_GET
dbconnect.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'form_db';
mysql_select_db($dbname);?>
table.php
include('dbconnect.php');
$query = "SELECT * FROM form";
$result = mysql_query($query) or die(mysql_error());
print "
<table id=\"AutoNumber2\" border=\"1\">
<tr>
<th>S.no</th>
<th>Title of thesis:</th>
<th>View detail:</th>
</tr>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
print "<tr>";
print "<td>". $row['s_no'] . "</td>";
print "<td>" . $row['title of thesis'] . "</td>";
print "</tr>";
}
print "</table>";?>
dataview.php
<?php
include('dbconnect.php');
$sn= $_GET['s_no'];
$sql = "SELECT * FROM form where s_no=". $sn;
$result3 = mysql_query($sql);
while($row3 = mysql_fetch_array($result3, MYSQL_ASSOC)){
$s_no=$row3['s_no'];
$obs_time=$row3['obs_time'];
$title=$row3['title'];
$type=$row3['type'];
$thesis=$row3['thesis'];
$year=$row3['year'];
$proposer=$row3['proposer'];
$institute=$row3['institute'];
$email=$row3['email'];
$present=$row3['present'];
$date=$row3['date'];
}
?>
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.
I'm trying to compose an estimate formula, and I stucked with value of dropdown list populated by MySQL.
The idea of this formula is when a user select a service from dropdown list and put the quantity in textfield the program will compute the price for the service.
The value of the prize is selected from MySQL table.
$query="SELECT $con_tent FROM services WHERE $id;
$con_tent= 'price'. '*'. $qunatity
But I don't know how to get the value from dropdwon list.
Probably with Ajax but still don't know how.
I solved this by modyfing code from http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
<?php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_user, $db_password);
mysql_select_db($db_database) or die("unable to select database:" . mysql_error());
echo "<form action=licz.php method='post'>";
echo " <label for=\"select\"><select name=\"\" value=\"Select\" size=\"1\">";
$query = "SELECT * FROM uslugi ORDER BY id ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
global $ff;
$ajdi = $row['id'];
$nazwa = $row['nazwa'];
$options.= "<option value=\"$ajdi\" name=\"oko\">" . $nazwa . $ajdi;
}
echo "<option>";
echo $options;
echo "</option></select>";
echo " <input type=\"submit\" name=\"Submit\" value=\"Submit\">";
echo "</form>";
function wybor() {
global $id;
global $con_tent;
$var = 'price' . '*';
$quantity = 3;
//quantity will by from textfield but now it constant
$id_value = 1;
// here i need to make it dynamic
$id = "id={$id_value}";
$con_tent = $var . $quantity;
}
echo wybor();
$query = "SELECT $con_tent FROM services WHERE $id";
//query
if (!$query) Die("Unable to query: " . mysql_error());
$result = mysql_query($query);
if (!$result) Die("Unable to query: " . mysql_error());
$rows = mysql_num_rows($result);
for ($a = 0; $a < $rows; ++$a) {
$row = mysql_fetch_row($result);
echo $row[0] . " ";
echo $row[1] . " ";
echo $row[2] . " ";
echo $row[3] . "$br";
}
?>
You should apply ajax call to get value for database when there is a change in select box through calling a function on onchange event of javascript.
Read More for jquery AJAX
http://www.sitepoint.com/ajax-jquery/
http://www.tutorialspoint.com/jquery/jquery-ajax.htm
I've been trying for ages to figure this out, but I can't do it.
$sqluser = "--";
$sqlpass = "--";
$hostname = "localhost";
$clientuser = $_COOKIE['user'];
//connection to the database
$dbhandle = mysql_connect($hostname, $sqluser, $sqlpass)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("clhtechn_si1",$dbhandle)
or die("Could not select database!");
//execute the SQL query
$idfinder = mysql_query("SELECT id FROM `si_customers` WHERE username='$clientuser'") or die(mysql_error());
$clientid = mysql_fetch_assoc($idfinder);
$query = "SELECT invoice_id, date, SUM(total) as invoiceTotal
FROM si_invoices
LEFT JOIN si_invoice_items ON si_invoices.id = si_invoice_items.invoice_id
WHERE si_invoices.customer_id='$clientid'
GROUP BY invoice_id
ORDER BY invoice_id";
$result = mysql_query($query);
$row=0;
while ($record = mysql_fetch_assoc($result))
{
$class = 'd' . ($row % 2);
$inv_date=substr($record['date'], 0, -9);
$inv_total=$record['invoiceTotal'];
$invoice_total=number_format($inv_total, 2);
echo "<tr class=\"{$class}\">";
echo "<td valign='top'>{$inv_date}</td>";
echo "<td valign='top'>{$record['invoice_id']}</td>";
echo "<td valign='top'>$invoice_total</td>";
echo "<td><a href='invoices/Invoice_{$record['invoice_id']}.pdf' target='_blank'>";
echo "<img src='urlhere' width='17' height='17' alt='PDF File' border='0' /></a></td>";
echo "</tr>";
$row++;
}
//close the connection
mysql_close($dbhandle);
Here is how my customers table is aligned:
Link to picture.
What is wrong with my code, and what code can I use to fix it?
Help is appreciated.
$clientid is an array as mysql_fetch_assoc() returns this type.
$row = mysql_fetch_assoc($idfinder);
$clientid = $row['id'];
also, you need to format $clientuser properly before placing it in a query.
So, the full code would be
$user = mysql_real_escape_string($_COOKIE['user']);
$sql = "SELECT id FROM `si_customers` WHERE username='$user'";
$res = mysql_query($sql) or trigger_error(mysql_error());
$row = mysql_fetch_assoc($res);
$clientid = $row['id'];
To make it the way you want, you have to use some abstraction library
With which you will have your id in one line (it's actually 2 lines just for sake of readability)
$sql = "SELECT id FROM si_customers WHERE username=?s";
$clientid = $db->getOne($sql,$_COOKIE['user']);
Here you can see an example of such a Mysql abstraction library.