<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
if (!mysql_select_db('database'))
die("Can't select database");
// choose id 31 from table users
echo $id; //31
echo $name; //id31's name
echo $surname //id31's surname
echo $blablabla //id31's blablabla
mysql_close($link);
?>
Give this a shot:
$id = mysql_real_escape_string(31);
$result = mysql_query('SELECT * FROM `users` where `id` = ' . $id . ' LIMIT 1');
$row = mysql_fetch_assoc($result);
echo $row['id']; // 31
echo $row['name']; // name
// etc..
// If you wanted to output ALL the fields you could loop through
foreach($row as $field_name => $value) {
echo $field_name . ': ' . $value . '<br />';
}
// The output would look something like
// id: 31
// name: John Smith
// ...
Functions Used:
mysql_real_escape_string() - Escapes special characters in a string for use in an SQL statement
mysql_query() - Send a MySQL query
mysql_fetch_assoc() - Fetch a result row as an associative array
Related
Recently I've bought webhosting at names.co.uk and I'm trying to set up something simple which will display the name from a table named Team if the id = 1.
This is my code
<?php
$q = "SELECT * FROM `Team` WHERE id =1";
$result = mysql_query($q);
echo '<br />Query is send';
echo '<br />Result is true';
$row = mysql_fetch_array($result);
echo '<br />tryed fetching row';
if ($row === FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
echo( mysql_error());
}
echo $name;
?>
This is the output:
Query is send Result is true tryed fetching rowNo such file or
directory
UPDATE:
I have changed to msqli:
$q = "SELECT * FROM `Team` WHERE id =1";
$result = mysqli_query($q);
echo '<br />Query is send';
echo '<br />Result is true';
$row = mysqli_fetch_array($result);
echo '<br />tryed fetching row';
if ($row !== FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
echo( mysqli_error());
}
echo $name;
and now I'm getting this output:
Query is send Result is true tryed fetching row $row is not false.
$name now is ""
You need to fist establish a connection. For example: $connection = mysqli_connect($servername, $username, $password);.
See this link on how to use MySQLi: https://www.w3schools.com/PHP/php_mysql_connect.asp (but note that w3schools is a bad resource, with outdated information and bad practices - I'm only linking to it because this tutorial is basic and clear).
Be sure to check later, if you still haven't, on how to properly sanitize your queries. See this, for example: How can I prevent SQL injection in PHP?
Use function:
$result = mysqli_query($q);
mysql_query() have been deprecated in PHP7 onwards.
I am trying to get my PHP script to print all rows i have in my database in a neat order. Currently Im not getting anything. My table has 4 columns, Name, Address, Long and Lat, and 2 rows with data. The table is called Locations. I am using the following code but im not getting to to work:
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
Here is a simple example using pdo instead of mysqli
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS); // create connection
$stmt = $pdo->prepare("SELECT Name, Address, Long, Lat FROM Locations");
//you should never use *, just call each field name you are going to use
$stmt->execute(); // run the statement
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC); // fetch the rows and put into associative array
print_r($arr); // print all array items, unformatted
and you can echo out the data and format it yourself using a for loop like so
for($i=0; $i<sizeof($arr); $i++) { // this will loop through each row in the database. i prefer this method over while loops as testing has shown this is much faster for large scale tables
echo 'Name: ' . $arr[$i]['Name'] . '<br />'; // $arr is the array name, $i is the number of the array item, or iterator, ['Name'] is the field name
echo 'Address: ' . $arr[$i]['Address'] . '<br>';
echo 'Long: ' . $arr[$i]['Long'] . '<br>';
echo 'Lat: ' . $arr[$i]['Lat'] . '<br>';
}
If the names are correct, this would echo out your row ID and row CITY. Just change the names to your field names. If you want further assistance, feel free to ask.
However, if you want to stick with mysqli, give the following code a wirl.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$mysqli = mysqli_connect($dbHOST, $dbUSER, $dbPASS, $dbNAME);
$query = "SELECT Name, Address, Long, Lat FROM Locations";
$result = mysqli_query($mysqli, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
echo 'Name: ' . $row['Name'] . '<br />';
echo 'Address: ' . $row['Address'] . '<br>';
echo 'Long: ' . $row['Long'] . '<br>';
echo 'Lat: ' . $row['Lat'] . '<br>';
}
}
change fieldname to the field you want to display
EDIT: Paste the following code. It will echo out the number of rows. This will tell you if the query statement is correct.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS);
$stmt = $pdo->query("SELECT Name, Address, Long, Lat FROM Locations");
echo $stmt->rowCount();
Fetch query result as associative array and use for each to print all results
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
while($rows = mysqli_fetch_assoc($result)) {
foreach($rows as $key => $val)
{
echo $val;
}
}
}
mysqli_close($con);
?>
I have to print customer name once and all the products for each customer.My code is below.
<div id="Allproducts">
<?php
$AllprodsRes = $conn -> query("select * from sepproducts");
if($AllprodsRes ->num_rows > 0){
$result = $AllprodsRes -> fetch_array();
?>
<label for="name"><?php echo $result['name'] . " " . $result['surname']; ?></label>
<?php } ?>
<?php do{ ?>
<p><?php echo $result['product_name'] . " " //$result['count']; ?></p>
<?php }while($result = $AllprodsRes -> fetch_array()); ?>
</div>
view sepproducts
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`#`localhost`
SQL SECURITY DEFINER
VIEW `sepproducts` AS
select
`customers`.`name` AS `name`,
`customers`.`surname` AS `surname`,
`custproducts`.`product_name` AS `product_name`,
count(0) AS `count`
from
(`custproducts`
join `customers` ON ((`custproducts`.`custid` = `customers`.`custid`)))
group by `custproducts`.`product_name`
Any help is welcome and appreciated.
Thanks in advance.
What you can use is something like the following (assuming you use MySQLi):
<?php
$con = new mysqli('localhost', 'username', 'password', 'db');
$query = $con->query('SELECT * FROM...');
$currentCustomer = null;
while ($result = $query->fetch_array()) {
$name = $result['name'] . ' ' . $result['surname'];
// Check to see if we're working with a new customer.
if ($currentCustomer != $name) {
echo $name . '<br />';
$currentCustomer = $name;
}
echo $result['product_name'] . '<br />';
echo $result['product_type'] . '<br />';
// ETC.
}
?>
Or if you only have one customer to worry about, use the following:
<?php
$con = new mysqli('localhost', 'username', 'password', 'db');
$query = $con->query('SELECT * FROM...');
if ($query->num_rows > 0) {
$result = $query->fetch_array();
echo $result['name'] . ' ' . $result['surname'] . '<br />';
do {
echo $result['product_name'] . '<br />';
echo $result['product_type'] . '<br />';
// ETC.
} while ($result = $query->fetch_array());
}
?>
In effect, it checks if records have been found and if so, writes one result to our array $result. We then output the customer's name OUTSIDE of the loop (so this only occurs once), then use a do...while() loop to continue through the rest of the result array.
I hope this helps!
Depending on the databse you use you could join multiple rows into a single column. Ultimately this is a display problem. I say keep doing what you are doing and in your view keep track of the current name in the loop and compare to the next name - if the name is the same ignore it, when the name differs set current_name to this new name and continue. This way each name only shows once.
i created a script that connects to my database called mysqlconnecter:
<?php
define("DB_USERNAME", "root");
define("DB_PASSWORD", "pass");
define("DB_DATABASE", "adventure_of_dragons");
define("DB_SERVER", "127.0.0.1");
$db_handle = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
$db_found = mysql_select_db(DB_DATABASE, $db_handle);
if ($db_found || true) {
$SQL = "SELECT * FROM members";
$result = mysql_query($SQL) or die(mysql_error());
while ( $row = mysql_fetch_assoc($result) ) {
$id = $row['member_id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
}
mysql_close($db_handle);
} else {
echo "Database NOT Found " . $db_handle;
}
?>
And then I created another script that includes mysqlconnecter.php and posts the data inside the database:
<?php
include "mysqlconnecter.php";
echo 'ID = ' . $id . '<br>';
echo 'RANK = ' . $rank . '<br>';
echo 'USERNAME = ' . $username . '<br>';
echo 'PASSWORD = ' . $password . '<br><br>';
// two <br>'s, so we get an empty line between users
?>
but the output displays the data inside the database twice:
ID = 4
RANK = 100
USERNAME = user
PASSWORD = password
ID = 4
RANK = 100
USERNAME = user
PASSWORD = password
I only want it displaying the text once,
What do I do?
Your logic is slightly the wrong way round.
This is because your loop is finished then you are echoing the data so it will always be the last row.
You need to echo whilst in the loop or create an array then loop the array later.
while ( $row = mysql_fetch_assoc($result) ) {
$id = $row['member_id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
//this will echo for EVERY row the loop iterates.
echo 'ID = ' . $id . '<br>';
echo 'RANK = ' . $rank . '<br>';
echo 'USERNAME = ' . $username . '<br>';
echo 'PASSWORD = ' . $password . '<br><br>';
}
For your double output i suspect you have included the file twice. But thats guessing as i don't see all of your code.
If you want to keep the display code outside your mysqlconnecter.php file, you could do this in your loop:
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data[] = array(
'id' => $row['member_id'];
'username' => $row['username'];
'password' => $row['password'];
'rank' => $row['rank'];
}
And then in your script:
include "mysqlconnecter.php";
foreach ($data as $key => $value)
{
echo 'ID = ' . $value['id'] . '<br>';
// etc
}
For your "double print" problem, I would try to put a var_dump($data); right after your while() in mysqlconnecter.php, to see what happens exactly.
If the var_dump display correctly reflects the expected result of your query, the problem is elsewhere, possibly that you include mysqlconnecter.php twice, as Dave suggested. To be sure it's included only once throughout your whole code, simply replace include() with include_once().
Are you sure you don't have any mistake? is that all code you show us?
Because logically your script will print once and will print the last data from your members table
I have try it
Version 4:
I have taken away the pull down menu for now, I just want the info to be posting correctly.
As it shows with the first line fab1 shows #2, in the second line it shows 1, --None-- instead of 2, Andy Khal. If anyone can figure out why, it be appreciated. I've done about as much as I can to figure this out and I'm lost.
<?php
// Connect to the database.
require_once('tb/connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
die("MySQL failed to connect: " . mysqli_connect_error());
}
// Create the SQL query
$testbed = "SELECT * FROM testbed";
$user = "SELECT * FROM user";
// Execute the SQL query and store the result set in
// the $result variable.
$testbed = mysqli_query($dbc, $testbed) or die("Failed to execute query on tesbed table: " . mysqli_error($dbc));
$user = mysqli_query($dbc, $user) or die("Failed to execute query on user table: " . mysqli_error($dbc));
// Read the results.
$row = mysqli_fetch_assoc($testbed);
if(!$row)
{
echo 'Query failed<br />';
}
else
{
echo "Query for Testbed Fabricator is : " . $row["fab1"] . "<br />";
}
$row = mysqli_fetch_assoc($user);
if(!$row)
{
echo 'Query for Testbed Fabricator failed<br />';
}
else
{
echo "Query for User ID # is : " . $row["userid"], $row["user"] . "<br />";
}
// Free the result set.
mysqli_free_result($testbed);
mysqli_free_result($user);
?>
Yes it is. You can specify the selected value with the selected keyword as a html attribute.
<option value="Username" selected>Username</option>
That makes this:
while($row = $result->fetch_assoc())
{
$user = $row['user'];
echo '<option value="' . $user . '"';
if($user is known)
{
echo ' selected';
}
echo '>' . $user . '</option>\n';
}
Update
In this snipped $choosen is the selected user's name.
echo'<div id="fab1">';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$mysqli->select_db('user');
$result = $mysqli->query("SELECT * FROM user");
echo "<select name='fab1'>\n";
while($row = $result->fetch_assoc())
{
echo '<option value="' . $row['user'] . '"';
if($row['user'] == $choosen)
{
echo ' selected';
}
echo '>' . $row['user'] . '</option>\n';
}
echo "</select>\n";
echo '</div>';