• 0

Help integrating php/mysql with existing html page.


Question

<p>Hello, I know little about web design so I hope this makes sense.

I am trying to integrate a very basic php site into an existing html website to create a blog. I have one page where I can enter info which is then published onto a page called blogentries.php which works fine on it's own. I want the info to be published into the blogentries div on my website that says "I WANT BLOG ENTRIES HERE" close to the bottom.

I thought it would be a simple case of making the connection to the database in the header and put the rest of the php into the div, but obviously there is more to it than that.

I was wondering if someone could look at the code for the two pages and explain how it should be done?

Thank you

blogentries.php


<?php
mysql_connect("localhost:8889","root","root");
mysql_select_db("Alexweb");
echo "<html><head><link rel='stylesheet' href='style.css' type='text/css'></head><body>";
$query = "select * from content";
echo "<p>Query: ".$query;
$result = mysql_query($query);

$rows = mysql_num_rows($result);
for($i=0;$i<$rows;$i++) {
$row = mysql_fetch_array($result);
echo "<div class='".$row['class']."'>";
echo "<p> Date: ".$row['date']."</p>";
echo "<p><h3>".$row['title']."<?h3></p>";
echo "<p><img src='".$row['image']."'></p></div><p></p>";
echo "<p>".$row['text']."</p>";

}

echo "</body></html>";
?>
[/CODE]

[b]blogpage in html[/b]

[CODE]
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJWatson - Blog</title>
<meta name="keywords" content=" art design, digital media design, graphic design, logo design, ">
<link rel="shortcut icon" href="favicon.ico" />
<!-- Load CSS -->
<link href="css/style.css" rel="stylesheet" type="text/css" />
<!-- Load Fonts -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Droid+Serif:regular,italic,bold,bolditalic" type="text/css" />
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Droid+Sans:regular,bold" type="text/css" />
</head>

<body>

<!--This is the START of the header-->
<div id="topcontrol" style="position: fixed; bottom: 5px; left: 960px; opacity: 1; cursor: pointer;" title="Go to Top"></div>
<div id="header-wrapper">
<div id="header">
<div id="logo"><a href="index.html"><img src="images/logo.png" width="100" height="80" alt="logo" /></a></div>
<div id="header-text">
<h4>Blog</h4>
<h6><a href="index.html">Home</a> ? Blog</h6>
</div>
</div>
</div>
<!--END of header-->


<!--This is the START of the menu-->
<div id="menu-wrapper">
<div id="main-menu">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="portfolio.html">Portfolio</a></li>
<li><a class="selected" href="blog.html">Blog</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>

<!--This is the START of the footer-->
<div id="footer">
<div id="social-box">
<ul>
<li>
<div class="facebook"><a href=""></a></div>
</li>
<li>
<div class="twitter"><a href=""></a></div>
</li>
<li>
<div class="linkedin"><a href=""></a></div>
</li>
</ul>
</div>
<h6></h6>
</div>
<!--END of footer-->

</div>
<!--END of menu-->

<!--This is the START of the content-->
<div id="content">

<!--This is the START of the blog-->

<div id="blogentries">


I WANT BLOG ENTRIES HERE


</div>
<!--END of blog-->

</div>
<!--END of content-->

</div>
</body>
</html>
[/CODE]

Recommended Posts

  • 0

You know....There was a time when people here would answer questions and help people out quite promptly. I don't know what the reasoning is, but it seems to me like that time has passed! I joined this site because the community was helpful honestly, but I certainly don't get the feeling that anybody wants to help anyone now! I apologize that I am unable to help Brodel. If I could remember how to do that, I would be glad to help out. I just wish someone else would at least acknowledge when people post asking for help. :( If anybody can clarify why that seems like it has changed, I would be grateful!

  • 0

My thread is only about 10 minutes old and people were very helpful the last time I made a post here. Thanks for taking the time to check it out too. :)

Yeah, I figured it wasn't very old. I was just saying that I have run across many instances where the post just sat and sat and sat with no response (including my own posts). That is what concerns me. There should at least be a response saying that someone doesn't know or something like that so people aren't left hanging. :) You are very welcome. Sorry that I couldn't be of more assistance.

EDIT: I am not saying that everyone that sees it should post that they don't know, but at least somebody should take the time to come in and reply is all.

  • 0

Change this:

for($i=0;$i<$rows;$i++) {
$row = mysql_fetch_array($result);[/CODE]

to

[CODE]
while($row = mysql_fetch_array($result)){

//whatever you want to echo from the array here

}
[/CODE]

See the PHP manual on mysql_fetch_array, it's very helpful. Basically, the while loop will run whenever $row evaluates to true, so as it iterates through the array that was returned, you can do whatever you want with each result. This is how most blog systems work. Also, you're going to have to include the blogentires.php code in the other file (either through include() or by pasting it in where you want it to appear).

It might help to download wordpress and take a look at how they do it. They use an object oriented approach, but it might help you understand where to make mysql connections, and where to call posts, etc.

Also, look into using mysqli, it can often be used in place of mysql, and is the newer/better implementation of it.

  • 0

Thanks guys, I managed to get it working with your help :) Just trying to figure the right way to set a maximum width for the images to be displayed at now. Seems trickier than I thought, as usual, lol.

  • 0

Yeah, I figured it wasn't very old. I was just saying that I have run across many instances where the post just sat and sat and sat with no response (including my own posts). That is what concerns me. There should at least be a response saying that someone doesn't know or something like that so people aren't left hanging. :) You are very welcome. Sorry that I couldn't be of more assistance.

EDIT: I am not saying that everyone that sees it should post that they don't know, but at least somebody should take the time to come in and reply is all.

The post was only 10 minutes old when you started posting this and what you are saying doesn't make sense because then someone would post "Nobody knows" after X amount of days (which in itself is a useless post) and then someone else who does know could then come later so how would anyone know that "Nobody knows" when they don't know who else could potentially see it.

  • 0

The post was only 10 minutes old when you started posting this and what you are saying doesn't make sense because then someone would post "Nobody knows" after X amount of days (which in itself is a useless post) and then someone else who does know could then come later so how would anyone know that "Nobody knows" when they don't know who else could potentially see it.

Alright, point taken. I guess it is just my frustration getting to me when it comes to trying to solve an urgent issue and not being able to find any help. I apologize.

Thanks guys, I managed to get it working with your help :) Just trying to figure the right way to set a maximum width for the images to be displayed at now. Seems trickier than I thought, as usual, lol.

No problem. I was glad to be able to help. :)

  • 0

You can set max-width with CSS. You can also set them to a % and set a max and min on the column that contains them.

Yea, I understand how it's done in CSS and tried that but couldn't get it to work. I'm still trying to get my head around integrating the html within the php properly. I'll take a look in the morning with fresh eyes.

  • 0

Yea, I understand how it's done in CSS and tried that but couldn't get it to work. I'm still trying to get my head around integrating the html within the php properly. I'll take a look in the morning with fresh eyes.

Just as a bit of help, I find it's much easier to look at php code with html mixed in when using alternative syntax. For example,


<?php
while($row = mysql_fetch_array($result)){
echo "<div class='".$row['class']."'>";
echo "<p> Date: ".$row['date']."</p>";
echo "<p><h3>".$row['title']."<?h3></p>";
echo "<p><img src='".$row['image']."'></p></div><p></p>";
echo "<p>".$row['text']."</p>"
}
?>
[/CODE]

can also be written as:

[CODE]
<?php while($row = mysql_fetch_array($result)) : ?>
<div class="<?php echo $row['class']; ?>">
// whatever else you want to call
}
<?php endwhile; ?>
[/CODE]

It's easier to figure out what's being generated by php, and what's in the html, and it becomes even easier to read if you ever switch over to object oriented php, as you can call things like:

[CODE] <?php $post::title(); ?> [/CODE]

  • 0

Thanks, I can see why that is probably easier. I'll take a look at it next time I work with php. I've actually changed it a bit and added an option to upload a photo rather than to use a URL so now I'm just trying to figure out how to set it to resize it once it reaches a maximum width.

  • 0

I feel totally lost now. I've been looking online and there are a lot of really long scripts for resizing images. I'm not fussed about actually resizing images and saving them to another folder, just limit the width so it doesn't mess up my page. Modifying this a bit was the closest I got, but it resized and then displayed the entire directory. The thing is I can't do it for a specific file name because obviously it'll change with each upload. This is what I have so far.

php for adding title, date, text and uploading image.


<?php

//This is the directory where images will be saved
$target = "blogimages/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$title=$_POST['title'];
$date= date("d F Y H:i:s");
$photo=($_FILES['photo']['name']);
$text=$_POST['text'];

//This keeps the formatting of text entered into the text area
$text=nl2br($text);
// Connects to your Database
mysql_connect("localhost:8888","root","root") or die(mysql_error()) ;
mysql_select_db("Alexweb") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `blogentries` VALUES ('$title', '$date', '$photo', '$text')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The photo ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your entry has been added to the blog";
}
else {
//Gives an error if its not
echo "Sorry, there was a problem uploading your photo.";
}

?>
[/CODE]

php for pushing the posts to my blog

[CODE]
<?php

// Connects to your Database
mysql_connect("localhost:8888","root","root") or die(mysql_error()) ;
mysql_select_db("Alexweb") or die(mysql_error()) ;

echo "<html><head><link rel='stylesheet' href='style.css' type='text/css'></head><body>";

//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM blogentries ORDER BY date DESC") or die(mysql_error());

//Puts it into an array
while($info = mysql_fetch_array( $data ))
{

//Outputs the image and other data
Echo "<h4></b> ".$info['title'] . "</h4>";
Echo "<b><h6></b> ".$info['date']."</h6><br>";
Echo "<p><img src=http://localhost:8888/uploadtest/blogimages/".$info['photo'] . "></p><br>";
Echo "<b><p></b> ".$info['text'] . "<p><br>";
Echo "<br>";

}

Echo "</body></html>";

?>
[/CODE]

  • 0

one last question...

I have the option to upload an image, however if nothing is uploaded I get a broken image icon in my post. Is there a way to echo the image if it's present but otherwise leave blank? This is what I have at the moment. I've looked at the !empty function but I'm not sure how to implement it or if it's the right way to do it in this case.


//Outputs the image and other data
echo "<h4></b> ".$info['title'] . "</h4>";
echo "<b><h6></b> ".$info['date']."</h6><br>";
echo "<p><img src=/blogimages/".$info['photo'] . "></p><br>";
echo "<b><p></b> ".$info['text'] . "<p><br>";
echo "<div class='blogspacer'></div>";
[/CODE]

  • 0

you could do something like

if(isset($info['photo']))
{
	echo "&lt;p&gt;&lt;img src='/blogimages/" . $info['photo'] . "' /&gt;&lt;/p&gt;&lt;br /&gt;";
}
else
{
	echo "&lt;p&gt;&lt;img src='/blogimages/noimage.png' /&gt;&lt;/p&gt;&lt;br /&gt;";
}

That would echo "noimage.png" instead if no image is there.

That's assuming the $info['photo'] var is empty when there's nothing uploaded.

Else you'll need a file_exists() call.

Also, some of your HTML in the post above is incorrect. You are closing the <b> before closing the tag inside, like here:

echo "&lt;b&gt;&lt;h6&gt;&lt;/b&gt;" . $info['date'] . "&lt;/h6&gt;&lt;br&gt;";

Should probably be this:

echo "&lt;b&gt;&lt;h6&gt;" . $info['date'] . "&lt;/h6&gt;&lt;/b&gt;&lt;br&gt;";

  • 0

Thanks, so I could just make a small noimage.png that is just the same colour as my background, right? Then there would technically be an image there, but it would look blank.

thanks for pointing out the mistake also :)

  • 0

Or you could just not write anything out, save loading a blank image from the server.

Edit: Also, the mysql_ API is deprecated (and for an old version of MySQL), if you're writing brand new code now either use the mysqli library, or PDO.

  • 0

I have added a transparent noimage.png to the blogimages folder and tried the above code as well as a blank div, but each time I make a post with no image there is still a broken image link. Am I adding it incorrectly or something?


//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
//Outputs the image and other data
echo "<h4></b> ".$info['title'] . "</h4>";
echo "<b><h6>".$info['date']."</h6></b><br>";
if(isset($info['photo']))
{
echo "<p><img src=/blogimages/" . $info['photo'] . " /></p><br />";
}
else
{
echo "<p><img src='/blogimages/noimage.png' /></p><br />";
}
echo "<b><p></b> ".$info['text'] . "<p><br>";
echo "<div class='blogspacer'></div>";
}
[/CODE]

If it makes any difference, in chrome and ie the broken image icon shows. In firefox it doesn't.

Is it a change I need to make to my addblog.php also?

[CODE]
//This gets all the other information from the form
$title=$_POST['title'];
$date= date("d F Y H:i:s");
$photo=($_FILES['photo']['name']);
$text=$_POST['text'];


//This keeps the formatting of text entered into the text area
$text=nl2br($text);

// Connects to your Database
mysql_connect("localhost:8888","Alexweb","*****") or die(mysql_error()) ;
mysql_select_db("Alexweb") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO `blogentries` VALUES ('$title', '$date', '$photo', '$text')") ;


//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{


//Tells you if its all ok
echo "<h4>The photo ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your entry has been added to the blog" ;
echo '<br><a href="http://www.mywebsite.com/blog2.php"> Click here to view</a>';
}
else {
//Gives an error if its not
echo "<h4>thanks for your entry .";
echo '<br><a href="http://www.mywebsite.com/blog2.php"> Click here to view</a>';
}
[/CODE]

  • 0

I assume it doesn't work if you post an image, either, as you've got quotes all over the place there. This line:


echo "<p><img src=/blogimages/" . $info['photo'] . " /></p><br />";
[/CODE]

Should be

[CODE]
echo '<p><img src="/blogimages/' . $info['photo'] . '"/></p><br />';
[/CODE]

To make things easier to read, you might want to use single quotes with PHP, double quotes with HTML.

Also, is the noimage.png in the correct place?

  • 0

if I include an image it does work and uploads it to blogimages. There is definitely a noimage in the correct place.

Yea, I really need to tidy things up. It's getting a bit of a mess, still getting he hang of integrating the html and php, as you can tell, lol.

  • 0

I suspect that $photo=($_FILES['photo']['name']); does not return FALSE if there is no image. You should check if $_FILES['photo'] is set, and then assign it to $photo, which should by default be set to FALSE.

i'm not entirely sure what you mean. i don't want to keep bugging people with basic questions though so i'll do a bit of googling. thanks again for your help :)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Wow, imagine you dump hundreds of hours into completing things and unlocking stuff and you lose it all. Back in the day when cheats were built into games, you could at least unlock things again that way without spending hundreds of hours again. But those days are long gone for some reason as no one builds cheats into games anymore. So it's even more painful that studio that's on its 6th installment **** it up so badly.
    • Spotify finally removes the disco ball app icon in the latest update by Ivan Jenic Image: Spotify Spotify has just released an update that removes its now infamous disco ball icon. The update reverts the app icon to the familiar flat green logo after weeks of mixed reactions online. The icon arrived on May 13 as part of the company's 20th anniversary celebration and was always intended to be temporary, though Spotify only confirmed that after the backlash started. The disco ball took the internet by storm, as the reception was split. A vocal group of users called it ugly and disorienting, with some iOS users noting that the 3D glowing effect made the app look like it was stuck mid-update. On the other end, the icon picked up a following of its own. Its retro, three-dimensional look immediately stood out against the flat, minimalist aesthetic that has dominated app design for years. It even started a small movement, spawning what people started calling "discomorphism," a mashup of disco and skeuomorphism. Other brands started posting disco ball versions of their own logos, probably in an effort to ride the wave of memes that flooded the internet during late May. Spotify has had a turbulent relationship with its user base lately. Besides the disco ball icon, which certainly wasn't appreciated by everyone, the company has also received backlash for its willingness to include AI-generated music on its platform. On May 17, Spotify promised the old icon would return “in a few weeks.” And now it looks like that time has finally arrived. So, whether you liked the disco ball or it made you uncomfortable, it’s now gone for good. The next time you update the Spotify app on your phone, the old, flat-design icon will return.
    • Playground Games confirms Forza Horizon 6 save wipe bug by Taras Buria Forza Horizon 6 was launched last month to critical acclaim (check out our review here), and it became a smash hit in an instant. Now, weeks into the launch, with die-hard fans clocking hundreds of hours, Forza Horizon 6 is facing a serious issue: save wipes. After multiple complaints on Reddit and social media, the studio issued a statement. The problem with missing saves came shortly after Playground Games promised the initial batch of gameplay tweaks and improvements. Unfortunately, there seems to be no temporary fixes for those affected by unexpected save wipes. However, the studio published a new support document with a few important steps users should try. First, affected gamers should open a support ticket immediately (go here to file one) so that the support team can try recovering the lost progress by reverting to an earlier save. Playground Games says this should be done the same day the issue occurs. Meanwhile, gamers are urged not to start new play sessions or create new saves. The studio also published a few things gamers should try to avoid to prevent potential progress loss: Ensure your Gaming Services app on PC or XBOX Series X|S console is fully up to date. On XBOX Series X|S consoles, disable Quick Resume for Forza Horizon 6: To disable Forza Horizon 6 from using Quick Resume, highlight the game box art anywhere in the console experience (Home, My Games & Apps, Pins, etc) and then press the Menu button, then go to Manage game and add-ons > Quick Resume settings > Disable Quick Resume. Ensure you are online when ‘quitting’ the game. Give your saved time to sync to the cloud before powering off or switching devices. Do not force quit the game during save screens. Do not power off the device during gameplay. Always "Quit" (console) or "Exit to desktop" (PC) once you've finished your play session, ensuring the save icon is not visible when you’re closing the game. Before turning off your console, shutting down your PC, or force-closing the Steam app, give your devices or clients at least a few minutes to ensure your latest progress has been synchronized with the cloud. This will reduce the risk of progress reversions as you switch between different platforms. XBOX Series X|S consoles, Steam, and the XBOX app on PC all include game save indicators that confirm your progress has been synced. You can read more about the bug in the official support document here. Forza Horizon 6 is currently available on PC (Steam and the Microsoft Store), Xbox Series X|S, and Game Pass. The game is also coming to PlayStation 5 later this year.
  • Recent Achievements

    • One Year In
      slackerzz earned a badge
      One Year In
    • One Year In
      highriskpaym earned a badge
      One Year In
    • One Month Later
      highriskpaym earned a badge
      One Month Later
    • Week One Done
      highriskpaym earned a badge
      Week One Done
    • Week One Done
      FBSPL earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      519
    2. 2
      PsYcHoKiLLa
      198
    3. 3
      +Edouard
      158
    4. 4
      Steven P.
      84
    5. 5
      ATLien_0
      75
  • Tell a friend

    Love Neowin? Tell a friend!