display all data from my User table in my database - php

My question is how to display all data from my users table in my database?
I have this.
$loop = mysql_query(“SHOW users FROM $dbname”) or die (‘cannot select tables’);

You want to SELECT the users, not SHOW them.

Basic SQL loop example:
$sql = mysql_query("SELECT * FROM `users`");
while ($row = mysql_fetch_object($sql)) {
echo $row->id . ' ' . $row->nickname . '<br />';
}

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_query(“SELECT * FROM Users”, $link) or die (‘cannot select tables’);
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
mysql_free_result($result);

$loop = mysql_query('SELECT * FROM `users`') or die();
You don't want your database name to be in the query, and you want to be using SELECT
If you haven't connected to the database earlier then you need to add this before your query:
mysql_connect($mysql_host, $mysql_user, $user_password);

Related

can't get the data from database PHP

i created a function to get data from the database but it's not working i don't know what's wrong
here is the code :
<?php
function Connect_Show($server_name,$server_user,$server_pass,$db,$db_table){
$connect = mysql_connect($server_name,$server_user,$server_pass) or die ('error , can not connect to database ') ;
$select = mysql_Select_db($db) or die (' error , can not select the database ');
$query = mysql_query("SELECT * FROM $db_table order by id ")
while ($rows = mysql_fetch_assoc($query)) {
echo $rows['id'];
echo $rows['name'];
echo $rows['emails'];
echo $rows['password'];
}}
echo Connect_Show("localhost","root","root","learn","users");
?>
Instead of
echo Connect_Show("localhost","root","root","learn","users");
Just use this:
Connect_Show("localhost","root","root","learn","users");
Connect_Show is a function, with echo commands in it, its not returning anything.

Take a single value from a MySQL field and store it in a variable

I am a beginner to PHP and MySql. What I wish to do is take a single field value from a MySql table and store it into a php variable. I tried this code but it does not seem to work:
//Get Role ID
$con= mysqli_connect("localhost","root","","darrenvellaedp2");
$result = mysqli_query($con,"SELECT userRoleID FROM tbl_users");
while($row = mysqli_fetch_array($result)) {
echo $row['userRoleID'];
echo "<br>";
}
//make the connection
$con = mysqli_connect("localhost","root","","darrenvellaedp2") or die("Error: " . mysqli_error($con));
//create the query
$result = "SELECT userRoleID FROM tbl_users" or die("Error: " . mysqli_error($con));
//execute the query
$res = $con->query($result);
while($row = mysqli_fetch_array($res)) {
//this will print the userroleid out to the screen
echo $row['userRoleID'];
//this will store it in a variable
$UserRoleID = $row['userRoleID'];
}
It would have been easier for you to just google it as there's a whole section about this on PHP.NET

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

Querying UserID from database

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.

MySQL insert row from HTML table into db table

I am using a for loop to construct a HTML table from the contents of a MySQL table select query. I have a link on the end of each row to copy that row into another table.
I'm unsure how to get the data from the table row for the MySQL insert query - I have marked the place where I'm struggling with XXX.
<?php
mysql_select_db("cardatabase");
$link = mysql_connect("localhost", "root", "password");
$query = "SELECT * from cars";
$result = mysql_query($query);
if($_GET['rent']) {
$rent = "INSERT INTO rentedcars VALUES('XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
echo "<table>";
echo "<tr><td>ID</td><td>Make</td><td>Model</td><td>Fuel Type</td><td>Transmission</td><td>Engine Size</td><td>Doors</td><td>Amount</td><td>Available</td><td>Date Added</td><td>Remove</td></tr>";
for ($i = 0; $i < mysql_num_rows($result); $i++) {
$row = mysql_fetch_object($result);
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
echo "</table>";
edit (updated code):
<?php
mysql_select_db ("cardatabase");
$link = mysql_connect ("localhost", "root", "password");
$query = "SELECT * from cars";
$result = mysql_query ($query);
if($_GET['rent']) {
$query_car = sprintf("SELECT * from cars WHERE ID=%s",$_GET['rent']);
$rslt = mysql_query($query_car);
$car = mysql_fetch_object ($rslt);
$rent = "INSERT INTO rentedcars VALUES('$car->ID','$car->CARMAKE','$car->CARMODEL','$car->FUELTYPE','$car->TRANSMISSION','$car->ENGINESIZE','$car->DOORS','$car->AMOUNT','$car->AVAILABLE','$car->DATEADDED')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
echo "<table>";
echo "<tr>";
echo "<td>ID</td><td>Make</td><td>Model</td><td>Fuel Type</td><td>Transmission</td><td>Engine Size</td><td>Doors</td><td>Amount</td><td>Available</td><td>Date Added</td><td>Remove</td>";
echo "</tr>";
while ($row = mysql_fetch_object($result)) {
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
echo "</table>";
mysql_* is deprecated as of PHP 5.5.0, you should use something like PDO.
try {
$DBH = new PDO('mysql:dbname=cardatabase;host=localhost', 'root', 'password');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$STH = $DBH->query("SELECT * FROM cars")->execute();
while ($row = $STH->fetch(PDO::FETCH_OBJ)) {
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=".$row->ID."'>Rent</a></td>
</tr>";
}
Edit: Just like #Skatox said!
I would do it like this:
<?php
$link = mysql_connect ("localhost", "root", "password");
mysql_select_db ("cardatabase");
$query = "SELECT * from cars";
$result = mysql_query ($query);
Get car information and store it
if($_GET['rent'])
{
$query_car = sprintf("SELECT * from cars WHERE ID=%s",$_GET['rent']); //Avoids sql injection
$rslt = mysql_query($query_car);
$car = mysql_fetch_object ($rslt)
Here you need to validate if there's no car
$rent = "INSERT INTO rentedcars VALUES('$car->ID','$car->CARMAKE','$car->CARMODEL','$car->FUELTYPE','$car->TRANSMISSION','$car->ENGINESIZE','$car->DOORS','$car->AMOUNT','$car->AVAILABLE','$car->DATEADDED')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
Change it to while like #Vinoth Babu said:
while ($row = mysql_fetch_object ($result))
{
$row = mysql_fetch_object ($result);
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
print "</table>";
?>
I would recommend you to switch to MySQL PDO, it's safer and you'll get a better and secure code.
you are missing the column names in your insert query
$rent = "INSERT INTO rentedcars (id ,carmake, carmodel,fueltype,transmission, enginesize,doors,amount ,available, dateadded)
VALUES('xxx','xxx','".$carmodel."','XXX','XXX','XXX','XXX','XXX','XXX','XXX')";
^^^^^-------------i showed u exempel under
those XXX are values you get the from the inputs values
exemple
<input name= "car_model" id= "car_model" value="mercedes" >
then you get this value
if (isset($_POST['car_model'])){ $carmodel = $_POST['car_model']}
and then use this value $carmodel in your sql

Categories