How can I show some text from the database on my PHP or HTML pages. I have the database table called "pages" and inside there I have "homepage". I need to make it possible to get the text inside the database out at the page? Any commands for this I am using MySQL.
In a PHP file, use SQL to select the field(s) you want from the database. Use the echo command to send it to the user. (Yes, you have to write code.)
An example tweaked from the php.net site below. It should get you started... <?php mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error()); mysql_select_db("mydb"); $result = mysql_query("SELECT homepage FROM pages"); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo $row["homepage"]; } mysql_free_result($result); ?> PHP:
I know this is solved, but surely you want to encourage against mysql? Considering it's going to become deprecated because of it's vulnerabilities? I suggest PDO or MySQLi. <?php $Host = 'localhost'; $User = 'your username'; $Pass = 'Your pass'; try { $con = new PDO("mysql:host=$Host;dbname=mysql", $User, $Pass); echo 'Database connection made'; } catch(PDOException $e) { echo $e->getMessage(); } $Query = $con->prepare('SELECT row FROM table'); $Query->execute(); while($Row = $Query->fetch(PDO::FETCH_ASSOC)) { echo htmlentities($Row['row'], ENT_QUOTES, "UTF-8"); // htmlentities on output assuming it has not been cleaned } PHP:
mysql has a tendancy to be easily exploited. news.php.net/php.internals/53799 Obviously it's long term yet, but there's the news. It's advised that you moved over to MySQLi or PDO. PDO protects against SQL injections and is faster, not to mention it's use of database abstraction and it's a lot nicer to look at, IMO.
Thanks for the link, I had no idea. Agreed it's definately worth keeping in mind for development and probably better to look at other options such as PDO as you mentioned. It would help if php.net also placed this information on the mysql_* documentation page too!
Yes, I know. Regarding the SQL injections, I was simply answering why PDO is better, because of the way it seperates data/syntax and binding params. Obviously you can't rely solely on PDO as a "OMG my site is secure now" method, you still need to escape other data, XSS, CSRF and so on. And yes, it'd be much easier if PHP made it more clear of their plans