What is the best way to include php database data with HTML - php

I am currently working on a website, i am quite new to this. I have established connection to my database with the connection.php file, but it seems quite hard to style a PHP file.
So i want to know:
Is there a smarter way to make a dropdown with data from a database and how would i include and syle the website then if it is still a .php file?
My preference would be to create a good looking website with HTML & CSS. But i don't know how to include my dropdown with data from the database?
As it is right now all are in one file, so it looks like this
Thank you in advance
Index.php
<?php
ini_set("display_errors", "On");
error_reporting(E_ALL);
$host='database.****.us-east-1.rds.amazonaws.com';
$db = '****';
$port = 5432;
$username = 'postgres';
$password = '****';
try {
$conn = new PDO("pgsql:host=$host;port=$port;dbname=$db;user=$username;password=$password");
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html>
<body>
<h1>Choose Category</h1>
<?php
$sql ="select * from products inner join category on category.category_id = products.category";
//Prepare the select statement.
$stmt = $conn->prepare($sql);
//Execute the statement.
$stmt->execute();
//Retrieve the rows using fetchAll.
$users = $stmt->fetchAll();
// show menu from dropdown
?>
<select>
<?php foreach($users as $user): ?>
<option value="<?= $user['id']; ?>"><?= $user['name']; ?></option>
<?php endforeach; ?>
</select>
</body>
</html>

There is a much simpler way but I am going to give an example:
Suppose you have a php file:
connection.php:
<?php
function connect(){
$con=mysqli_connect("localhost","root","","dbname");
if(!$con)
die("Could not connect");
}
return $con;
}
?>
Now another file called getAll.php
<?php
require("connection.php");
$con=connect();
$getAll="select * from employees";
$res=mysqli_query($con,$getAll);
while($row=mysqli_fetch_array($res)){
echo "<option value='$row[firstname]'>$row['firstname']</option>"
}
mysqli_close($con);
?>
Now where you want to display the dropdown list:
Suppose a file called display.php
<html>
<body>
<select name="employee">
<?php
require("getAll.php");
?>
</select>
</body>
</html>
This is a simple way to get data from database and display them.

Related

Save text with Tinymce online editor in Mysql database and show the saved text on the website

I have another question about connecting to Mysql database.
I have a simple text document with Tinymce online text editor. Online I want to change the text with the editor, save it to Mysql database and then show the new text online. I have the following scripts and I get this error from the file doAddContents.php:
Warning: mysql_real_escape_string(): Access denied for user ''#'localhost' (using password: NO) in /../doAddContents.php on line 8
Warning: mysql_real_escape_string(): A link to the server could not be established in /../doAddContents.php on line 8
I have no idea what I'm doing wrong. Here are the scripts:
first the script to connect to the database:
db.php:
<?php
function doDB() {
global $mysqli;
//connect to server and select database
$mysqli = mysqli_connect("localhost", "name", "pass", "db-name");
//if the connection fails, stop script execution
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
?>
doAddContents.php file:
<?php
include("db.php");
doDB();
$h4_block = "Contents Saved!";
$elm1 = $_POST['elm1'];
$entity_elm1 = htmlentities($elm1);
$entity_elm1 = mysql_real_escape_string($entity_elm1);
$add_contents_sql = "UPDATE tinymce_contents SET `contents`=
'$entity_elm1', `modified`=now()";
$add_contents_res = mysqli_query($mysqli, $add_contents_sql)
or die(mysqli_error($mysqli));
//close connection to MySQL
mysqli_close($mysqli);
//create nice message for user
$display_block = "<p>The page has been successfully updated.</p>";
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<div>
<h4><?php echo $h4_block; ?></h4>
<?php echo $display_block; ?>
View Page!
</div>
</body>
</html>
View.php file:
<?php
include("db.php");
doDB();
$h4_block = "View Page!";
$get_contents_sql = "SELECT * FROM tinymce_contents";
$get_contents_res = mysqli_query($mysqli, $get_contents_sql)
or die(mysqli_error($mysqli));
if ($get_contents_res = mysqli_query($mysqli, $get_contents_sql)) {
//fetch associative array
while ($row = mysqli_fetch_assoc($get_contents_res)) {
$id = $row['id'];
$contents = $row['contents'];
$modified = $row['modified'];
//Draw the results
$view_block ="<p>ID: ".$id."</p>";
$view_block .="<b>Contents</b>:".html_entity_decode($contents);
$view_block .="<b>Modified</b>:".$modified."<br/>";
}
}
//close connection to MySQL
mysqli_close($mysqli);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<div>
<h4><?php echo $h4_block; ?></h4>
<?php echo $view_block; ?>
Back to Page Edit!
</div>
</body>
</html>
According to the documentation of mysql_real_escape_string. The function will try to create a mysql connection if there is no connection opened with mysql_connect().
http://php.net/manual/en/function.mysql-real-escape-string.php
You should not be using mysql_real_escape_string() but mysqli_real_escape_string()
http://php.net/manual/en/mysqli.real-escape-string.php

PHP MSQL server syntax error

I get this error when trying to get this details page for a project to work. Its for school and I dont really understand PHP that well yet.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"
Here is the code for that page.
<?php
require_once('connection.php');
mysqli_select_db($conn, $dbname);
$recordID = $_GET['recordID'];
$query_Shoe_Details = "SELECT * FROM Products WHERE Shoe_Brand = $recordID";
$Shoe_Details = mysqli_query($conn, $query_Shoe_Details) or die(mysqli_error(($conn)));
$row_Shoe_Details= mysqli_fetch_assoc($Shoe_Details);
$totalRows_Shoe_Details = mysqli_num_rows($Shoe_Details);
?>
<!DOCTYPE html>
<html>
<head>
<title>details</title><?php include 'connection.php';?>
</head>
<body>
<p>Product Name: <?php echo $row_Shoe_Details['Product_Name']; ?></p>
<p><img src=
"images/%3C?php%20echo%20$row_Shoe_Details['Image_Name'];%20?%3E"></p>
<p>Description: <?php echo $row_Shoe_Details['Product_Description']; ?></p>
<p>Price: $<?php echo $row_Shoe_Details['Product_Price']; ?></p><?php
mysqli_free_result($Shoe_Details);
?>
</body>
</html>
change your query as, use single quotes
$query_Shoe_Details = "SELECT * FROM Products WHERE Shoe_Brand = '$recordID'";
Also remove this <?php include 'connection.php';?>, No need to include again
Pl. prepare connection.php file in followng way like
$dbHost = '';
$dbUser = '';
$dbPass = '';
$dbName = '';
// setting up the web root and server root for
// this shopping cart application
$con=mysql_connect('','','');
if(!$con)
{
die('connection failed');
}
$db=mysql_select_db('',$con);
if(!$db)
{
die('db is not selected');
}
pass proper value in this syntax save it and in your code remove second line and test then and give feedback

Displaying blank page when including php-mysql connection file

I am using Ubuntu 14.04 and I am using lamp. I had a more complex issue but I figured out what is causing the error and made a small php-mysql connection snippet. When the connection file is included into the php/html file the whole thing displays a blank page.
My connect.php code:
<?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "ecalendar";
$conn = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if(mysqli_connect_errno(){
echo "Error".mysqli_connect_errno();
}
?>
and my web page with connection file included:
<?php
include "connect.php";
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Testing</p>
<?php
$sql="SELECT * FROM events WHERE eventid=1";
$result = mysqli_query($sql);
?>
<ul>
<li><?php $row = mysqli_fetch_array($result);
echo $result;
?>
</li>
</body>
</html>
<?php
mysqli_close($conn);
?>
The following line in connect.php:
if(mysqli_connect_errno(){
Should be:
if(mysqli_connect_errno()){ // note the extra ')'
You were not properly enclosing your condition with ().

Broken PHP web app (w/ Bluemix) - MySQLi stops script

I'm building a simple PHP webservice/webapp that when queried from an external application will return JSON formatted/encoded data from a MySQL database.
The PHP webapp and MySQL database are on Bluemix (and MUST to stay there).
Here is my current code for a typical PHP page:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Before Outside of php</p>
<?php
/*
* Following code will list all the customers
*/
echo "<p>Before Inside of php</p>";
$server = "Server";
$username = "username";
$password = "password";
$database = "database";
echo "<p>1 Inside of php</p>";
// Connecting to mysql database
$mysqli = new mysqli_connect($server, $username, $password, $database);
echo "<p>2 Inside of php</p>";
$response = array();
echo "<p>3 Inside of php</p>";
if ($result = $mysqli->query("SELECT firstName, lastName FROM customer")) {
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
$response[] = $row;
}
echo json_encode($response);
}
echo "<p>4 Inside of php</p>";
$result->close();
$mysqli->close();
echo "<p>After Inside of php</p>";
?>
<p>Before Outside of php</p>
</body>
</html>
I have put in the <p>1 Inside of PHP<p> stuff in there so I could see where the script stopped and therefore figure out why.
The last thing that gets echo'd to the screen is <p>1 Inside of php</p> so therefore we can assume it's the MySQLi functions not working.
After some googling, I found that the main reason for this was that the MySQLi extension hasn't been included in the installation/build of the PHP webapp.
I am using this buildpack:
https://github.com/cloudfoundry/php-buildpack.git
which allows for use of a .bp-config/options.json file to include any extensions not included in the build pack.
As MySQLi is not included in the buildpack. My .bp-config/options.json file shows as follows:
{
"PHP_EXTENSIONS": ["mysqli"]
}
Now that MySQLi is included, I threw a phpinfo(); in my PHP before the MySQLi function, just to double check, and it displayed all the PHP information WITH a section titled: MySQLi.
Just to point out, the MySQLi section wasn't there before I wrote the .bp-config/options.json file.
However, the script STILL stops at the first MySQLi function and won't display anything after that. I'm stumped. Is it Bluemix's fault? Is it my PHP? Do I need to do something else before MySQLi is properly installed? I don't know, Help?
Your PHP is a little wrong on the line with mysqli_connect.
It should be $mysqli = mysqli_connect($server, $username, $password, $database);. Notice the reference to new is not used.
mysqli_connect is a function, not a class. What you want is either:
$mysqli = mysqli_connect(...);
or
$mysqli = new mysqli(...);
Both are equivalent.
Additionally the use of MYSQL_ASSOC should be MYSQLI_ASSOC.
Here is a full replacement of your code below.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Before Outside of php</p>
<?php
/*
* Following code will list all the customers
*/
echo "<p>Before Inside of php</p>";
$server = "Server";
$username = "username";
$password = "password";
$database = "database";
echo "<p>1 Inside of php</p>";
// Connecting to mysql database
$mysqli = mysqli_connect($server, $username, $password, $database);
echo "<p>2 Inside of php</p>";
$response = array();
echo "<p>3 Inside of php</p>";
if ($result = $mysqli->query("SELECT firstName, lastName FROM customer")) {
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$response[] = $row;
}
echo json_encode($response);
}
echo "<p>4 Inside of php</p>";
$result->close();
$mysqli->close();
echo "<p>After Inside of php</p>";
?>
<p>Before Outside of php</p>
</body>
</html>

Using Template on PHP

i create a template file for my site... it's like:
<!-- template.php -->
<?php function showheader() { ?>
<head><body>
<!-- some of style files and menus -->
<div class="content">
<?php } ?>
<?php function showfooter() { ?>
</div></body></html>
<?php } ?>
i use this file as a template like this:
<?php include_once("template.php"); showheader(); ?>
content text or photo or ... etc.
<?php showfooter(); ?>
that's all... but if i try to use a connection on template file, it screw up!
i used an external file like:
<?php
//
// include_once connection file
// query strings goes here
//
do {
echo $row_table['id']; //example
} while ($row_table = mysql_fetch_assoc($table));
?>
and i use this file as include_once("filename.php"); on template file... at this point it gives errors... like what is this connection variable, what is this connection string... etc. it cannot reach connection strings...
by the way, i use another external connection like:
<?php
global $hostname_conn,$database_conn,$username_conn,$password_conn,$conn;
$hostname_conn = "localhost";
$database_conn = "test";
$username_conn = "****";
$password_conn = "****";
$conn = mysql_pconnect($hostname_conn, $username_conn, $password_conn) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_query("SET NAMES 'utf8'");
?>
i'm gonna cry! what's the problem... and do you know another way to use template...
thanks much...
PS: i change variables on conn.php as global (and it didnt work) and i change include, include_once, require, require_once where i include files but it didnt give anything.
This separates the page into two PHP files: (1) the first obtains the data, and (2) the second displays the data.
While getting data, not a single character should be printed out.
If some errors occurred, display an error page.
Once you get all your data with no errors - it's time to include a template. The template has two PHP files as well: the template for the page itself and the template that is shared in common by all the pages in the site.
By sorting things this way you'll solve all your present and future templating problems.
A typical script may look like
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.php";
include "template.php";
?>
where template.php is your main site template, including common parts, like header, footer, menu etc:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
and links.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
easy, clean and maintainable.
settings.php contains all common settings:
<?php
$hostname_conn,$database_conn,$username_conn,$password_conn,$conn;
$hostname_conn = "localhost";
$database_conn = "test";
$username_conn = "****";
$password_conn = "****";
$conn = mysql_connect($hostname_conn, $username_conn, $password_conn)
or trigger_error(mysql_error(),E_USER_ERROR);
mysql_query("SET NAMES 'utf8'") or trigger_error(mysql_error(),E_USER_ERROR);
$tpl = "default.php";
$pagetitle = "";
function dbgetarr(){
$a = array();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val) {
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
} else {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
?>

Categories