Extract PHP codes into Separate file - php

Can anyone help me to extract the following php codes into a separate file? Below is the code:
<?php
//ini_set('display_errors', true);//Set this display to display all erros while testing and developing the script
//////////////////////////////
require "config.php"; // Database Connection
echo "<!doctype html public \"-//w3c//dtd html 3.2//en\">
<html>
<head>
<title>Demo script from example.com</title>
</head>
<body>
";
echo "<input id=\"city\" list=\"city1\" >
<datalist id=\"city1\" >";
//// Collect options from table ///
$sql="select city from city "; // Query to collect records
foreach ($dbo->query($sql) as $row) {
echo "<option value=\"$row[city]\"/>"; // Format for adding options
}
//// End of data collection from table ///
echo "</datalist>";
?>
<center>
<br><br>a href='http://www.example.com' rel='nofollow'>example.com : Footer text.</a></center>
</body>
</html>
Below is the database connection file, just for reference:
<?php
///////// Database Details , add here ////
$dbhost_name = "localhost";
$database = "test"; // Your database name
$username = "root"; // Login user id
$password = "test"; // Login password
/////////// End of Database Details //////
//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
I just want to extract the PHP code in the main display page for a cleaner code structure.

Usually, the way to do this is to put your HTML in a "template" and your PHP code in another file. You can use a full-featured template engine like Smarty or Plates, or you can just place your HTML in a separate PHP file. Let's say your main file is called myfile.php. Make a new file called myfile.template.php.
In myfile.php:
<?php
require "config.php";
$cities = array();
$sql = "SELECT city FROM city";
foreach ($dbo->query($sql) as $row)
{
$cities[] = $row['city'];
}
include('myfile.template.php');
In myfile.template.php:
<!DOCTYPE html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Demo script from example.com</title>
</head>
<body>
<input id="city" list="city1" />
<datalist id="city1" >
<?php foreach ($cities as $city): ?>
<option value="<?php echo $city; ?>" />
<?php endforeach; ?>
</datalist>
<div align="center">
<br><br>
<a href='http://www.example.com' rel='nofollow'>example.com : Footer text.</a>
</div>
</body>
</html>

Related

MySQL PHP - Fetch data and present in HTML

I'm just learning PHP and I'd like to do a basic login. Once logged in, I'd like to show basic information from the user (in this example, just the name), but for some reason I'm not getting the name printed. Could you help me please?
<?php
include "config.php";
// Session
if(!isset($_SESSION['uname'])){
header('Location: login.php');
}
// Logout
if(isset($_POST['but_logout'])){
session_destroy();
header('Location: login.php');
}
// CHECK THIS
$sql_query = "select * from users where username='".$uname."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
?>
<!doctype html>
<html>
<head></head>
<body>
<form method='post' action="">
<h1>Dashboard</h1>
<div>
<!-- CHECK THIS -->
<h2>Hello <?php echo $row['name']; ?></h2>
</div>
<div>
<input type="submit" value="Logout" name="but_logout">
</div>
</form>
</body>
</html>
The login, logout and session are already working.
The table structure contains a table named users with the columns: id, username, password, name, email.
Thanks
$uname is undefinded
Try: $_SESSION['uname'] on line 14;
Alway u can debug this e.g. var_dump($sql_query) and execute it in phpmyadmin
And if you want use $row['name'], you must have assoc array: $row = mysqli_fetch_assoc($result);
this is a very basic example:
first of all you must to open a conection to your server and database, create a php file, lets call "CONEXION_DB.php" and add the next code:
<?php
function ConexionDBServer($DB_Con)
{
$servername = "your_server";
$username = "your_user";
$password = "your_password";
$conDB = mysqli_connect($servername, $username, $password);
if (!$conDB)
{
die('Could not connect: ' . mysqli_error());
return -1;
}
$DB = mysqli_select_db($conDB, $DB_Con);
if (!$DB)
{
echo "<SCRIPT LANGUAGE='javascript'>
alert('CONEXION WITH DB FAIL');
</SCRIPT>";
return -1;
}
return $conDB;
}
?>
now create your "main" page, lets call "main_page.php", and add:
<?php
echo "example mysql </br>";
?>
<!doctype html>
<html>
<head></head>
<body>
<form action="<?php echo $PHP_SELF?>" method="POST">
<input size=10 maxlength="150" type="text" name="txtUsuario">
<input type="submit" value="Login" name="cmdLogin">
</form>
<?php
if($_POST[txtUsuario])
{
$sql_query = "select * from users where username='" . $_POST[txtUsuario] . "'";
require_once('CONEXION_DB.php');
$con=ConexionDBServer("name_of_your_db");
$result = mysqli_query($con,$sql_query);
while($row = mysqli_fetch_array($result))
{
echo $row['username'] . "</br>";
}
mysqli_close($con);
}
?>
</body>
</html>
as you can see, in order to capture the input entry from your form, you must to use the $_POST method.

How can I return the control to the web page from which another php webpage was called

Please see my code below.
How can I return the control to the index.php to an executable statement after the closing form tag to display query results on index.php page rather than code shown toward the end of processData.php?
I have searched through Google, this forum and have not seen a solution? Those familiar with Fortran, Visual Basic would appreciate the return statement that can be used to go back to the calling routine. Is there a statement similar to return to hand over the control to the calling web page in PHP?
Code for index.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Report Summary</title>
</head>
<body>
<h1>Online Sales Report Demo
<br>
<br>
<form method="post" action="processData.php">
Enter Your Full Name:<input type="text" name= "author_name" />
<br>
Enter Your eMail Address:<input type="text" name= "author_email" />
<br>
<input type="submit" value="Submit">
</form>
**//Question - How to return the control to a statement after </form> tag to print values instead of processData.php**
</body>
</html>
Code for processData.php:
<?php
// define variables and set to empty values
$author = $email = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//Next extract the data for further processing
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$author = test_input($_POST['author_name']);
$email = test_input($_POST['author_email']);
//Next echo the Values Stored
echo "<br>";
echo "<br>Your Name:".$author;
echo "<br>Your Email Address:".$email;
}
?>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydatabase');
$sql = "SELECT Sales_Author, Sales_Date, Sales_Channel, Sales_Title, Sales_Unit, Sales_Royalty, Sales_Currency
FROM Sales_tbl
WHERE Sales_Email= '" . $email . "' ORDER BY Sales_Date ASC";
$result = mysql_query( $sql, $conn );
if(!$result )
{
die('Could not fetch: ' . mysql_error());
}
?>
<table border="2" style="background-color: #84ed86; color: #761a9b; margin: 0 auto;">
<thead> <tr> <th>Date</th><th>Channel</th><th>Title</th><th>Units</th><th>Royalty</th><th>Currency</th></tr></thead><tbody>
<?php
while($row = mysql_fetch_assoc($result)){
echo "<tr>
<td>{$row['Sales_Date']}</td>
<td>{$row['Sales_Channel']}</td>
<td>{$row['Sales_Title']}</td>
<td>{$row['Sales_Unit']}</td>
<td>{$row['Sales_Royalty']}</td>
<td>{$row['Sales_Currency']}</td>
</tr>\n"; }
?>
</tbody></table>
<?php
mysql_close($conn);
echo "Fetched data successfully\n";
?>
</body>
</html>
If I take your question literaly this is one possibility:
In processData.php put that link where ever you want it to be:
back to index.php
then you can react on that parameter in index.php:
....
<input type="submit" value="Submit">
</form>
//Question - How to return the control to a statement after </form> tag to print values instead of processData.php**
<?php
if(isset($_GET['state'])) {
switch($_GET['state']) {
case "fromProcess":
echo "I come from process!";
// do whatever you want to do
break;
default:
echo "ERROR: undefined state submitted";
}
}
?>
</body>
</html>
There's of course also the possibility to redirect without clicking a link via
header("location: index.php?state=fromProcess");
// NOTE: This has to be before ANY output, and no output after that will be seen.
But I have the feeling, that you actually want to display data generated from processData in index.html.
Then you got at least two possibilities:
Include processData.php in index.php and wrap it in a
<?php
if(isset($_POST['author_name'])) {
include('processData.php');
// process the data and make output
}
?>
Same is possible the other way round (but that's kinda tricky for what you want to do).
One general thing you have to keep in mind:
php scripts are scripts, basicly all on their own.
They are out of memory once they finished executing, so you cannot call a function of another script unless you include it into the current script (without autoload - but that not what you want).

calling a html file from another html file which contains a post method

how to call a html file 2 (which shows me a picture I need) in a html file 1 which includes two text fields and a list of which the user will fill and I will recover after the in a .php file.
My problem is when I click the display button, I find myself in the .php page thanks to method = "post" action = "transfert.php found in the html file 1
I need these values to be transferred to the .php file but I do not want to head it, for cons I want to show the image I need.
Here my html file 1 :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Interface</title>
</head>
<body>
<form name="form1" method="post" action="transfert.php">
<p>Date de Debut :
<input type="text" name="date1" id="champ_date1" size="12" maxlength="20" /></p>
<p>Date de Fin :
<input type="text" name="date2" id="champ_date1" size="12" maxlength="20" /> </p>
<p> choisir KPI
<select name="list" size="1" id="0">
<option value="TotalVoiceTrafficBH1" id="1">TotalVoiceTrafficBH1</option>
<option value="TotalVoiceTrafficBH2" id="2">TotalVoiceTrafficBH2</option>
<option value="CSSRBH1" id="3">CSSRBH1</option>
<option value="CSSRBH2" id="4">CSSRBH2</option>
<option value="TCHBlockingBH1" id="5">TCHBlockingBH1</option>
<option value="TCHBlockingBH2" id="6">TCHBlockingBH2</option>
<option value="SDCHHBlockingBH1" id="7">SDCHHBlockingBH1</option>
<option value="SDCCHBlockingBH2" id="8">SDCCHBlockingBH2</option>
<option value="SDCCHDropBH1" id="9">SDCCHDropBH1</option>
<option value="SDCCHDropBH2" id="10">SDCCHDropBH2</option>
<option value="TCHDropBH1" id="11">TCHDropBH1</option>
<option value="TCHDropBH2" id="12">TCHDropBH2</option>
<option value="HOSRBH1" id="13">HOSRBH1</option>
<option value="HOSRBH2" id="14">HOSRBH2</option>
</select>
</p>
<p><input type="submit" value="Afficher" size="15"/>
</p>
</form>
// here i wanna to insert my html file 2 so i can get my picture
</body>
</html>
It seems as though English is not your primary language so your question is not that clear.
I can't get what your problem is and what you intend to achieve, however two observations.
Why not post html2 file and transfert.php. it might give us clues on why you are having problems
Why are you mixing php and html file types in one application ? since your site is not going to be static, I suggest you stick with using php all through
so here is my php file and my html2 file, i need to get the chart generated by my html2 file from my html1 file. The problem is that i am automatically redirected to my transfert.php page whilst clicking on the display button, but i want to send my variables to transfert.php and get my chart from my html2 file.
//transfert.php
<?php
$var1=$_POST['date1'];
$var2=$_POST['date2'];
$var3=$_POST['list'];
if($var1 != NULL AND $var2 != NULL AND $var3 != NULL)
{
//address of the server where db is installed
$servername = "localhost";
//username to connect to the db
//the default value is root
$username = "root";
//password to connect to the db
//this is the value you would have specified during installation of WAMP stack
$password = "";
//name of the db under which the table is created
$dbName = "test";
//establishing the connection to the db.
$conn = new mysqli($servername, $username, $password, $dbName);
//checking if there were any error during the last connection attempt
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//the SQL query to be executed
$query = "SELECT A,$var3 FROM `feuil1` WHERE A >= '$var1' AND A<= '$var2'";
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
//initialize the array to store the processed data
$jsonArray = array();
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc())
{
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['A'];
$jsonArrayItem['value'] = $row[$var3];
//append the above created object into the main array.
array_push($jsonArray, $jsonArrayItem);
}
//Closing the connection to DB
//$conn->close();
$con = new mysqli($servername, $username, $password, $dbName);
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
}
if (is_array($jsonArray)) {
$sql = "TRUNCATE TABLE `table_temporaire`";
$res = $con->query($sql);
foreach ($jsonArray as $row) {
$id = $row['label'];
$na = $row['value'];
$st = $con-> prepare("INSERT INTO `table_temporaire`(A, $var3) VALUES (?, ?)");
$st->bind_param('ss', $id, $na);
$st->execute();
}
}
}
$con->close();
}
if($var1 == NULL)
{
echo 'Vous devez entrer date de Debut';
}
if($var2 == NULL)
{
echo 'Vous devez entrer date de Fin';
}
?>
// file2.html
<!DOCTYPE html>
<html>
<head>
<title>Fusion Charts Column 2D Sample</title>
</head>
<body>
<div id="chart-container">FusionCharts will render here</div>
<script src="js/jquery-2.1.4.js" type="text/javascript"></script>
<script src="js/fusioncharts.js" type="text/javascript"></script>
<script src="js/fusioncharts.charts.js" type="text/javascript"></script>
<script src="js/themes/fusioncharts.theme.zune.js" type="text/javascript"></script>
<script src="js/atr1.js" type="text/javascript"></script>
</body>
</html>
Aha! I see!
I think it will make your life easier if you use the fusionchart.php wrapper.
This allows you to load your data from the database,
Encode in a jsonarray and then call it like below
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();

display multiple results from a sql query

so I am trying to display multiple results from a database when a query is searched, the query is passed from a search box on another page.
I have it displaying one result, but that is all it will display.
I need it to display all the results that are relevant to the search query.
the php code is below
<meta charset="UTF-8">
<?php
$mysqli = new mysqli('localhost', 'scott', 'tiger','courses');
if ($mysqli->connect_errno)
{
die('Database connection failed');
}
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
$search_result = $result->fetch_assoc();
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<h3><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
</body>
and the code for the search bar
<!doctype html>
<html>
<Head>
<meta charset = "utf-8">
<title>Search</title>
</head>
<body>
<h2>Search</h2>
<form name="search" method="post" action="SearchResultsPage.php">
<input name="searchBar" type="text" size="40" maxlength="60" />
<input type="submit" name="Submitsearch" value="Search" />
</form>
</body>
Does anyone have any suggestions?
Thanks in advance;
You will need to place it in a while loop to show multiple results, the fetch function you're using will only retrieve one row, if you place it in a loop you can keep fetching until there is nothing to fetch:
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<?PHP while($search_result = $result->fetch_assoc()) { ?>
<h1><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
<?PHP } ?>
</body>
P.S. your code is vulnerable to SQL injection, you should read about prepared statements. More Info on that
You can iterate over your query results with a while loop. To complete the example I added the necessary data cleaning.
<?php
// function to clean post data
function cleanPost(&$value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = cleanPost($v);
}
return $value;
}
else {
$value = mysql_real_escape_string($value);
return trim(htmlentities(strip_tags($value)));
}
}
// search function
function search() {
// check if post data is set
if (isset($_POST['searchBar'])) {
// make link with db
$link = mysqli_connect('localhost', 'scott', 'tiger','courses');
if (!$link)
return false;
}
// clean your post data
$cleanPostData = cleanPost($_POST);
// query
$sql = "SELECT title, summary, id FROM course WHERE title LIKE '%".$cleanPostData['searchBar']."%'";
$result = mysqli_query($link, $sql);
// iterate over results
if (isset($result) && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
// here is your data
echo $row['title'] . "< br/>";
echo $row['summary'] . "< br/>";
echo $row['id'] . "< br/>";
}
}
}
}
// call search function
search();
?>

session variable keeps disappearing following selection

I have a value that I receive from another url from $_SESSION. It arrives glued together with a second value I needs as {$is:$user} or {2:bob}. I split them with they with explode and 'attempt' to assign them as $_SESSION['id'] = $pieces[0]; and $_SESSION['cust_name'] = $pieces[1];
The first time the process works prefect. the values are segmented and they go to the proper place.
But following my selected submit, I lose the value of $_SESSION['cust_name']
How can I retain the value of $_SESSION['cust_name'] following my selection?
<?php
session_start();
if(isset($_POST['SubmitForRedirect'])){
//store as session variable
$_SESSION['printdata'] = $_POST['bolredir'];
//forward browser
die(header("Location: add-job.php"));
}
require_once("header2.php");
//var_dump($_SESSION['id']);
//var_dump($_SESSION['cust_name']);
$cust_info = $_SESSION['id'];
$pieces = explode(":", $cust_info);
//if(isset($_SESSION['cust_name']))
$_SESSION['id'] = $pieces[0];
$_SESSION['cust_name'] = $pieces[1];
//else
//echo "Something died";
echo $pieces[0];
?><br /><?php
echo $pieces[1];
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- <link href="style.css" rel="stylesheet" type="text/css" /> -->
<title> Contacts Database </title>
</head>
<body>
<h2> Select and existing job for: <?php echo $_SESSION['cust_name']; ?> with the ID of: <?php echo $_SESSION['id']; ?> and select print options</h2>
<?php
// selection box submit
try{
$conn = new PDO("mysql:host=localhost;dbname=$db", $user, $pass);
$stmt = $conn->prepare("SELECT * FROM customer INNER JOIN orders ON orders.cust_id = customer.id WHERE id =".$_SESSION['id']);
$stmt->execute();
$result = $stmt->fetchAll();
?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST">
<select name="bolredir">
<option></option>
<?php
foreach ($result as $item){
echo '<option value='.$item['cust_id'].'>';
echo ($item['ship_name'] .",". $item['ship_addr'] .",". $item['total_price'].",". $item['cust_id']."<br />\n");
echo '</option>';
}
}
catch (PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
?>
</select>
<input type="submit" name="SubmitForRedirect" value="Submit" />
</form>
</body>
You must put session_start() at the top of every page before any output if you wish to use sessions:
<?php
session_start();
require_once("header2.php");
It looks like you are overwriting $_SESSION['id'] on every request.
You would normally set this only once, upon signon.

Categories