I am a beginner learning PHP and MySQL and have gotten to chapter 5 of Head First PHP & MySQL and am attempting a self made project in which I created a database and a index.php page where I can see the results printed out. When I go to my index.php page I see the HTML title but the PHP code is not printing out my submissions. I have to assume my code syntax is correct or I would end up with a blank page. Can someone please tell me what I have coded wrong to wind up with no output?
<?php
$dbc = mysqli_connect(localhost, root, root, itmyfamily);
$query = "SELECT * FROM itsmyfamily ORDER BY last_name ASC, first_name DESC, date ASC";
$data = mysqli_query($dbc, $query);
$i = 0;
while ($row = mysqli_fetch_array($data))
{
if ($i == 0)
{
echo '<strong>First Name:</strong> ' . $row['first_name'] . ' <br />';
echo '<strong>Last Name:</strong> ' . $row['last_name'] . ' <br />';
echo '<strong>Spouse Name:</strong> ' . $row['spouse_name'] . ' <br />';
echo '<strong>Email:</strong> ' . $row['email'] . ' <br />';
}
else
{
echo 'There is no info in the database';
}
$i++;
}
mysqli_close($dbc);
Set this on top of the source code to display errors.
<?php error_reporting( E_ALL ); ?>
Or set display_erros in php.ini as follows:
display_errors = On
error_reporting = E_ALL | E_STRICT
Also try to replace your source code with following,
<?php
//Establish connection with database
$dbc = mysqli_connect(localhost,root,root,itmyfamily);
//Order the data to be retrieved
$query = "SELECT * FROM itsmyfamily ORDER BY last_name ASC, first_name DESC, date ASC";
//Execute the connect command and the query
$data = mysqli_query($dbc,$query);
while ($row = mysqli_fetch_array($data)) {
//Loop through the array of family submissions, formatting it as html
$i = 0;
//Display family submissions
if ($i == 0) {
echo '<strong>First Name:</strong> ' .$row['first_name']. ' <br />';
echo '<strong>Last Name:</strong> ' .$row['last_name']. ' <br />';
echo '<strong>Spouse Name:</strong> ' .$row['spouse_name']. ' <br />';
echo '<strong>Email:</strong> ' .$row['email']. ' <br />';
}
else{
echo 'There is no info in the database';
}
$i++;
}
mysqli_close($dbc);
?>
If you can write it this way, I think you don't even need the $i.
$result = mysql_query("SELECT id, first_name FROM mytable");
if($result){
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf("ID: %s Name: %s", $row["id"], $row["first_name"]);
}
}
else
echo 'There is no info in the database';
Read here for more information about PHP mysql_fetch_array http://www.php.net/mysql_fetch_array
Read here for more information about iterations. http://webcheatsheet.com/php/loops.php
Please note that the method you have used is deprecated from PHP 5.5.0. So I suggest you consider mysqli or PDO. Examples can be found in below PHP manual links
http://www.php.net/manual/en/mysqli.query.php
http://www.php.net/manual/en/pdo.query.php
Related
I am creating a website and would like to allow an admin to add an image that is being pulled from a MySQL database and have it display above the news blog text that is being added as well. I can get it to display the images, as well as the text, but they are grouped together (images with images and text with text). How can I have my website display a the last image entered above the last text entry added?
<?php
$sql = "SELECT imageId FROM output_images ORDER BY imageId DESC";
$result = mysqli_query($dbc, $sql);
?>
</BODY>
</HTML>
<div class="brown-container-fluid text-left">
<div class="text-home">
<h2><strong>Pine Lane News</strong></h2><br/>
<?php
if ($row = mysqli_fetch_array($result)) {
?>
<div style="text-align:center;">
<img style="max-width:300px; max-height:300px;"
src="imageView.php?image_id=<?php echo $row["imageId"]; ?>"/><br/>
</div>
<?php
}
$query = 'SELECT * FROM entries ORDER BY date_entered DESC';
if ($r = mysqli_query($dbc, $query)) { // Run the query.
// Retrieve and print every record:
while ($row = mysqli_fetch_array($r)) {
print
"<dl><dt><h3><strong>{$row['title']}</strong></h3></dt>
<dd>{$row['entry']}<br /><br />\n</dd></dl>";
}
} else { // Query didn't run.
print '<p style="color: red;">Could not retrieve the data because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
} // End of query IF.
mysqli_close($dbc); // Close the database connection.
?>
</div>
</div>
Something I came up with real quick, not tested.
<?php
while($row = mysqli_fetch_array($result)){
echo '<div style="text-align:center;">';
echo '<img style="max-width:300px; max-height:300px;"';
echo 'src="imageView.php?image_id="'.$row["imageId"].'"/><br/>';
echo '</div>';
$query = 'SELECT * FROM entries ORDER BY date_entered DESC LIMIT 1';
if ($r = mysqli_query($dbc, $query)) { // Run the query.
while ($row = mysqli_fetch_array($r))
{
print
"<dl><dt><h3><strong>{$row['title']}</strong></h3></dt>
<dd>{$row['entry']}<br /><br />\n</dd></dl>";
}
} else { // Query didn't run.
print '<p style="color: red;">Could not retrieve the data because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
} // End of query IF.
mysqli_close($dbc); // Close the database connection.
?>
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 want to use a variable that comes from a table i MySQL and pass it to Another SQL-Query with PHP. Can´t get it to work and I can´t find out why.
Here is the code:
<html>
<head><title></title></head>
<body>
<div>
<?php
if (isset($_GET['read_blog_posts_scrolling']))
{
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date
FROM blog
INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID
WHERE blog.BlogID='$blogs_profile_id' // Here it is, it says undefined variable
ORDER BY blogpost.Date DESC")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<p>';
echo "Titel: " . "<strong>" . $row['Blogpost_title'] . "</strong>" . " - Bloggare " . $row['Blogwriters_name'] . " " . $row['Date'] . '<br />';
echo '<hr />';
echo '</p>';
}
}
?>
<?php
$result = mysql_query("SELECT BlogID, Blogwriters_name FROM blog")
or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$blogs_profile_id = $row['BlogID']; // I want to pass this value to above and use it in the query
echo '<p>';
echo $row['Blogwriters_name'] . '<br />';
//When clicking in this link I want the query to execute and values in BlogID to be passed
echo 'Choose blogwriter';
echo '</p>';
?>
</div>
</body>
</html>
it says the variable is undefined. How can I define it and pass the value when the a href-link is clicked?
Error is clear. Undefined variable:
You didn't defined this variable anywhere
before select statement
$blogs_profile_id
I think you need to add this variable in query string and get from $_GET.
UPDATE 1:
You have following issues in your code.
Missing blog_profile_id in your query string.
Undefined variable means you are using a variable but didn't defined.
Using mysql_* extension its deprecated
Solution:
Replace this:
echo 'Choose blogwriter';
With:
echo 'Choose blogwriter';
And than use that:
if (intval($_GET['blog_id']) > 0)
{
$blogs_profile_id = intval( $_GET['blog_id']);
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date FROM blog INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID WHERE blog.BlogID=".$blogs_profile_id." ORDER BY blogpost.Date DESC")
or die(mysql_error());
.....
Change the order of your queries. The second query code has to be coming first in order as below
<html>
<head><title></title></head>
<body>
<div>
<?php
$result = mysql_query("SELECT BlogID, Blogwriters_name FROM blog")
or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$blogs_profile_id = $row['BlogID']; // I want to pass this value to above and use it in the query
echo '<p>';
echo $row['Blogwriters_name'] . '<br />';
//When clicking in this link I want the query to execute and values in BlogID to be passed
echo 'Choose blogwriter';
echo '</p>';
?>
<?php
if (isset($_GET['read_blog_posts_scrolling']))
{
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date
FROM blog
INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID
WHERE blog.BlogID='"+$blogs_profile_id+"' // Here it is, it says undefined variable
ORDER BY blogpost.Date DESC")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<p>';
echo "Titel: " . "<strong>" . $row['Blogpost_title'] . "</strong>" . " - Bloggare " . $row['Blogwriters_name'] . " " . $row['Date'] . '<br />';
echo '<hr />';
echo '</p>';
}
}
?>
</div>
</body>
</html>
I'm trying to populate a dropdown list in my web page from a mysql database table which has only one column (pathology_id). I know there is test data in there but the best I can do is populate the box with the field name, not the row values. The code I have thus far is below, can anyone suggest how to get more than just the column name? Thanks in advance.
<?php $con = mysql_connect("localhost","dname","dbpass");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
$fields = mysql_list_fields("dbname","PATHOLOGY",$con);
$columns = mysql_num_fields($fields);
echo "<form action = newcase.php method = POST><select name = Field>";
for($i = 0; $i < $columns ; $i++)
{
echo "<option value = $i>";
echo mysql_field_name($columns , $i);
}
echo "</select></form>";
if(!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
echo "1 record added";
}
mysql_close($con) ?>
Try this:
<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
From PHP: mysql_query().
mysql_list_fields just returns information about a given table, NOT the data contained.
Select option should has close tag.
echo '<form action="newcase.php" method="POST"><select name"="Field">';
for($i = 0; $i < $columns ; $i++)
{
echo '<option value="' . $i . '">';
echo mysql_field_name($columns , $i);
echo '</option>';
}
echo '</select></form>';
Heres my code
<?php
session_start();
include('config.php');
if(isset($_GET['search_word']))
{
// echo $_GET['search_word'] . '<br />'; // debugging
$search_word = $_GET['search_word'];
$search_word = mysql_escape_string($search_word);
$search_word_fix = str_replace(" ","%",$search_word);
$query = "SELECT * FROM article WHERE article_title LIKE '%" . $search_word . "%' AND article_live = '1' ORDER BY article_id DESC";
// echo $query . '<br />'; // debugging
$sql = mysql_query($query);
$count = mysql_num_rows($sql);
// echo $count . '<br />'; // debugging
// echo mysql_num_rows($sql) . '<br />'; // debugging
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$msg=$row['article_title'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $msg);
echo $final_msg;
}
}
else
{
echo "No Results";
}
}?>
Can anyone see an issue with it? I cant pick out what is not working with this script and ive been staring at it for a while. It never makes it to the WHILE loop only the "No Results" and the count returns blank when i uncomment my debugging.
Count returning blank means your query failed for some reason.
Are you connecting to the db properly? Try using mysql_error() right after your query:
$error_msg = mysql_error();
Use mysql_real_escape_string() instead of mysql_escape_string() - it respects the character set so that you don't have UTF8 issues
If you're using this publicly, you may want to learn about using binds to eliminate the possibility of SQL injection via a library like PDO.
Here's a pretty good tutorial/introduction to PDO explaining why it's important!