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;
}
?>
Related
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.
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 ().
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>
In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>
#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);
First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.
I am using Jquery.load to load an external file with html/php content into one div. It loads the file, and displays what it's supposed to except it says access denied www-data#localhost password: no where it should be echoing some content.
I know that the main page, not the one being loaded, is connected to the db using require_once("assets/functions/config.php"); to call on my php file that contains the connection.
What am I doing wrong? It's probably simple, and I'm overlooking something.
EDIT: Okay on the index.php above <html> I have:
<?PHP
require_once("assets/functions/config.php");
//if ($notInstalled == 1) header("Location: install");
require_once("assets/functions/functions.php");
if ($users->checkAuth() == 0) {
header("Location: login.php");
exit;
}
$currentUser = $_COOKIE['vetelixir_username'];
?>
config.php is as follows:
<?
// MySQL Database
$db_host = "localhost";
$db_name = "dbname";
$db_username = "username";
$db_password = "password";
// Connect to the database
$connection = #mysql_connect($db_host,$db_username,$db_password) or die(mysql_error());
$db = #mysql_select_db($db_name,$connection)or die(mysql_error());
// end MySQL
?>
jQuery:
$("#button").click(function() {
$('#content').load('pages/external.php');
});
External File to Load:
<div id="div">
<?
$currentBlah = mysql_query("SELECT `firstname`,`lastname` FROM `blah` ORDER BY `lastname` ASC") or die(mysql_error());
while($u = mysql_fetch_array($currentBlah)) {
echo "<div class='clientRow'><span class='name'>".$u['firstname']." ".$u['lastname']."</span></div>";
}
?>
</div>
This looks like the php script that your jQuery function is calling is trying (and failing) to open an SSH session.