learning how to read data from MYSQL - php

I'm trying to learn php and mysql, I was trying to read data from my database where i was following something online and encounter an error(s) here is my code
<?php
include 'includes/conn.php';
$query =sprintf("Select * from customer");
$result = mysql_query($query);
if (!$result)
{
$message ='from you see this then it's not connecting!'.mysql_error() ."\n";
$message .= 'everything' .$query;
die($message);
}
while ($customer = mysql_fetch_assoc($result))
{
echo $row['cust_id'];
echo $row['fname'];
echo $row['lname'];
echo $row['gender'];
echo $row['dob'];
}
mysql_free_result($result);
?>
//this is where i was trying to make a connection with the database
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db ='telmar_php';
$con = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db);
?>

Replace
$message ='from you see this then it's not connecting!'.mysql_error() ."\n";
here your string is single quotation marks in it's is causing the problem
with
$message ="from you see this then it's not connecting!".mysql_error() ."\n";

...and to display your results change this:
while ($customer = mysql_fetch_assoc($result))
to this:
while ($row = mysql_fetch_assoc($result))

Please review the below example for reading data my mysql using php.
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}

Related

trying to check if user exists with php

hi i am trying to make a php script that checks if a user is in the database only it gives me the error
mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\stage\userExist.php on line 22
below is the code
<?php
$link = mysqli_connect('localhost', 'root', '', 'k3462_top-tree');
$query = "SELECT * FROM users";
$userName = $_GET['userName'];
$result = mysqli_query($link, $query);
echo "<table>";
while($row = mysqli_fetch_array($result)){
echo "<tr><td>" . $row['userName'] . "</td><td>" . $row['email'] . "</td></tr>";
}
echo "</table>";
$query1 = "SELECT * FROM users WHERE userName = $userName";
$result1 = mysqli_query($link, $query1);
if(mysqli_num_rows($result1)>=1){
echo "user exists";
}
else {
echo "user doesnt exist";
}
mysqli_close($link);
?>
You have a syntax error in your query that fill the variable $result1 with false. That occurs your error. Try my example below. I just added ' around $userName in your query and an if statement around your mysqli_num_rows function.
$link = mysqli_connect('localhost', 'root', '', 'k3462_top-tree');
$query = "SELECT * FROM users";
$userName = $_GET['userName'];
$result = mysqli_query($link, $query);
echo "<table>";
while($row = mysqli_fetch_array($result)){
echo "<tr><td>" . $row['userName'] . "</td><td>" . $row['email'] . "</td></tr>";
}
echo "</table>";
$query1 = "SELECT * FROM users WHERE userName = '$userName'";
$result1 = mysqli_query($link, $query1);
if( $result1 ) {
if(mysqli_num_rows($result1)>=1){
echo "user exists";
}
else {
echo "user doesnt exist";
}
} else {
echo "query or db error";
}
mysqli_close($link);
$query1 = "SELECT * FROM users WHERE userName = '$userName'";

how to php echo individual column values of a result row from mysql query?

The below code works perfectly and gives me the "id" "firstname" and "lastname". What I want is to use a loop to echo all the field values in the result row without having to quote each column name like
$row["id"]
below is the working code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " .
$row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
any thoughts please
This should work..
while($row = $result->fetch_array()) {
$i=0;
while($i<count($row)){
echo $row[$i];
$i++;
}
}
just use a foreach loop inside while like this
foreach($row as $key=>$value){
echo "<br> $key: ". $value. "<br>";
}
If I understand what you want to do is automate the output of the name of each column with its value (independent of the number of columns you get).
So do it like this :
if ($result->num_rows > 0) {
foreach($result->fetch_assoc() as $row) { // browse each records
foreach($row as $col => $value) { // browse each columns on a record
echo "<br>$col: $value<br>";
}
}
}
else {
echo "no result";
}

how to convert the text outputted from a database to links?

Iam class 11th..recently I started learning php and mysqliI have been facing a problem. I am trying to create a database which has a small list of movies.when the page loads, it displays the list of those movies from database..but the problem is, it displays them as a simple text..i Want them to be like links so that whenever it is clicked it displays the info about that particular movie..but i dont want to write anchor tag links for each movie..Is there any other way?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, title FROM movies";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
According to your code.
if ($result->num_rows > 0) {
$htmlLink = '';
while($row = $result->fetch_assoc()) {
$id = $row["id"];
$title = $row["title"];
$htmlLink .= "<a href='movie.php?{$id}'>id: {$id} - Name: {$title}</a><br>";
echo $htmlLink;
}
} else {
echo "0 results";
}
Then on your movie.php page use $_GET[] to get the query string data
Replace:
echo "id: " . $row["id"]. " - Name: " . $row["title"]. "<br>";
With:
$id = $row["id"];
$title = $row["title"];
echo "<a href='/movie/{$id}'>id: {$id} - Name: {$title}</a><br>";

If 0 items in DB table, return error

I am looking for a way to display an error message if there is nothing listed in the table.
I have a photos table.
If this tables is empty, id like to echo something.
else, show the pictures.
inside of that table I have
id, name, url
id = id
name = name of image
url = url of image.
If there are no rows, we have an error.
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
mysql_fetch_array($query1);
if(empty($query1)) {
echo "nothing";
} else {
echo "good";
}
Try this,
$query = "SELECT * FROM photos";
$result= mysql_query($query);
$length= mysql_num_rows($result);
if($length>0)
{
while($rows = mysql_fetch_array($result))
{
echo $rows['name'];
echo "<img src='$rows[url]' />";
}
}
else
{
echo "Nothing to display";
}
Hope this will work
What about something like...
$sql = "SELECT COUNT(*) AS amountPhotos FROM photos";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row["amountPhotos"] == 0) {
echo "There are no photos in the photo table.";
}
or
$sql = "SELECT * FROM photos LIMIT 1";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "There are no photos in the photo table.";
}
Try this
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
$result = mysql_fetch_array($query1);
if(empty($result)) {
echo "nothing";
} else {
echo "good";
}
This pretty much sums up the answer for this question: http://www.w3schools.com/php/php_mysql_select.asp
They even provided a sample code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //<--- here they check if number of rows returned is greater than 0 (so there is data to display)
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results"; //<----- nothing found
}
$conn->close();
?>
Just modify this and you'll be good to go.

Data from database is not showing

How can I get data from my database to show. I am not very experienced with PHP or MySQL.
I do not get an error message but no data shows so what am I doing wrong?
PHP
<?php
if(strlen(trim($_POST['search'])) > 0) {
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
mysql_connect ("cust-mysql-123-03", "", "");
mysql_select_db ("weezycouk_641290_db1");
if (!empty($_POST["search_string"]))
{
}
$query = "SELECT name,lastname,email FROM contact WHERE name LIKE '%$search%' AND
lastname LIKE '%$searchterm%'";
$result = mysql_query ($query);
echo mysql_error();
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
echo $row["name"];
echo $row["lastname"];
echo $row["email"];
} ?>
<?php echo $row["name"]; ?>
<br>
<?php echo $row["lastname"]; ?>
<br>
<?php echo $row["email"]; ?>
<?php
}
}
?>
It should be like this:
<?php
if(strlen(trim($_POST['search'])) > 0) {
mysql_connect ("cust-mysql-123-03", "", "");
mysql_select_db ("weezycouk_641290_db1");
$query = "SELECT name,lastname,email FROM contact WHERE name LIKE '%" . mysql_real_escape_string($_POST['search']) . "%' AND lastname LIKE '%" . mysql_real_escape_string($_POST['searchstring']) . "%'";
$result = mysql_query ($query);
echo mysql_error();
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
echo $row["name"];
echo $row["lastname"];
echo $row["email"];
} ?>
<?php echo $row["name"]; ?>
<br>
<?php echo $row["lastname"]; ?>
<br>
<?php echo $row["email"]; ?>
<?php
}
}
?>
The mysql_real_escape_string is to prevent mysql injection which is a serious risk.
Make sure the query you are executing returns record(s). You can check this by adding an echo statement which will print the query in your screen. Copy that and run it againist the database.You can use any mysql front end tools(php myadmin,mysqlyog to run the query. If there is any error in the query, you can see that then.
$query = "SELECT name,lastname,email FROM contact WHERE name LIKE '%$search%' AND
lastname LIKE '%$searchterm%'";
//the below line will print the query on the screen
echo $query;
$result = mysql_query ($query);

Categories