How to output data using php from mysql database - php

I am making a blog using mysql to input and output data(blog posts) using php. I have create a table, inserted rows for the data such as: id, title, content and date in "addentry.php".
I am having problems outputting the data using php on my "viewblog.php". Where it says "//output from table"(line 115), thats where i want to output the data. Ive tried my best to find a solution.
Thanks in advance.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- image.html
A trivial document
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head><title> My Blog </title></head>
<style type ="text/css">
body{
position: fixed;
overflow:overlay;
width: 100%;
top: -20px;
left: -20px;
right: -40px;
bottom: -40px;
height: auto;
background-image:url(image.jpg);
background-size: cover;
}
.container{
background-color: #ecdad6;
padding: 30px;
width:920px;
margin-left: 25%;
padding-bottom:1000px;
padding-left:0px;
border: 2px solid black;
}
.links{
position: absolute;
padding-right: 135px;
padding-bottom: 800px;
margin-left: 680px;
margin-right: 100px;
font-size: 20px;
word-wrap: break-word;
top:-3px;
}
.blog{
position: absolute;
width:678px;
padding-bottom: 920px;
margin-left: 10px;
font-size: 20px;
text-align: left;
word-wrap: break-word;
}
ul li { margin-top: -10px; }
}
iframe{
border:2px solid black;
width:4000px;
display:block;
*}
}
</style>
<body>
<!--Logo & hyperlinked -->
<p align = "center"><img src = "Logo.jpg" alt="My logo" width="10%" height="10%"/></p>
<br/>
<hr width="50%">
<div class="container">
<div class="blog">
<?php
$host = "dbprojects.eecs.qmul.ac.uk" ;
$user = "hm315" ;
$pass = "cXtXuyf2pnF4H" ;
$db = "hm315" ;
$link = mysql_connect ( $host , $user , $pass );
if (! $link ) {
die( 'Could not connect: ' . mysql_error ());
}
echo 'Connected successfully' ;
$db_selected = mysql_select_db ( $db , $link );
if (! $db_selected ) {
die ( 'Can\'t use $db : ' . mysql_error ());
}
echo 'Connected successfully' ;
//select from table
$sql = "SELECT * FROM post02";
$row=mysql_fetch_array($sql);
echo 'selecting table works';
//output from table
//connection + database, record created and close connection.
if ($link->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link->error;
}
mysql_close ( $link );
?>
<form action='index.php' method='get'></form>
<div class="links">
<ul><li>home</li></ul>
<ul><li>logIn</li></ul>
<ul><li>add_entry</li></ul>
</div>
</div>
</div>
</body>
</html>
<?php
$host = "xxx.ac.uk" ;
$user = "xxx" ;
$pass = "xxx" ;
$db = "xxx" ;
$link = mysql_connect ( $host , $user , $pass, $db );
if (! $link ) {
die( 'Could not connect: ' . mysql_error ());
}
echo 'Connected successfully' ;
$db_selected = mysql_select_db ( $db , $link );
if (! $db_selected ) {
die ( 'Can\'t use $db : ' . mysql_error ());
}
/*
// create a table
$sql="create table post02(id INT(6) unsigned auto_increment primary key , title varchar(30) not null, content varchar(255) not null, date TIMESTAMP)";
$connection = mysql_query($sql);
if (! $connection ) {
die ( 'Cant create table : ' . mysql_error ());
}
echo 'Created a table successfuly' ;
*/
//insert to table
echo'insert table - initializing';
if($_POST['submit']){
$title = $_POST['title'];
$content = $_POST['content'];
$date = date('l jS \of F Y h:i:s A');
}
$sql = "INSERT INTO post2('title', 'content', 'date') VALUES ($title, $content,$date))";
if($title =="" || $content=="" ){
echo "please compelete your post!";
return;
}
echo'insert table completed';
mysql_query($db ,$sql);
header("location: viewblog.php");
//record created is successful
if ($link->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link->error;
}
mysql_close ( $link );
?>

The question was not that clear, I wrote a sample code according to the question's title. Oh, and don't forget to change your creds.
<table>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<?php
$r = $link->query("SELECT * FROM table");
while($rf = $r->fetch_assoc())
{
echo "<tr>
<td>{$rf['column_1']}</td>
<td>{$rf['column_2']}</td>
<td>{$rf['column_2']}</td>
</tr>";
}
?>
</table>

Related

How to add the id of the first table to the id_position field of the second table when I click submit?

I have two tables. How to add the id of the first table to the position_id field of the second table when I click submit? My request is sent using ajax. Fields for the second table are dynamic; you can add them as many as you like. For example, if I had 5 records that were added to the database, then position_id, the id of the first table should be added, for all records.
//My Code
//data base
CREATE TABLE IF NOT EXISTS `article` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`description` text NOT NULL,
`text` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;
CREATE TABLE IF NOT EXISTS `data` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`position_id` int(10) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;
//index.php
<html>
<head>
<title>Dynamically add input field using jquery</title>
<style>
.container1 input[type=text] {
padding:5px 0px;
margin:5px 5px 5px 0px;
}
.add_form_field
{
background-color: #1c97f3;
border: none;
color: white;
padding: 8px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border:1px solid #186dad;
}
input{
border: 1px solid #1c97f3;
width: 260px;
height: 40px;
margin-bottom:14px;
}
.delete{
background-color: #fd1200;
border: none;
color: white;
padding: 5px 15px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 14px;
margin: 4px 2px;
cursor: pointer;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
$('#mess').html(data);
$("#content").hide();
}
});
});
});
</script>
</head>
<body>
<span id="mess"></span>
<div id="content">
<form name="add_name" id="add_name">
Title:<br>
<input type="text" name="title">
<div class="container1">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div><input type="text" name="mytext[]"></div>
</div>
Description:<br>
<textarea cols="50px" rows="15px" name="description"></textarea><br>
Text:<br>
<textarea cols="50px" rows="15px" name="text"></textarea><br>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
</div>
</body>
</html>
//name.php
<?php
$number = count($_POST["mytext"]);
if($number > 0)
{
$title = $_POST["title"];
$desc = $_POST["description"];
$text = $_POST["text"];
$connect = new PDO('mysql:dbname=test_db;host=localhost','root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
if(trim($title)!='' || trim($desc)!='' || trim($text)!='')
{
try{
$query = "INSERT INTO article
(title, description, text)
VALUES (:title, :description, :text)";
$statement = $connect->prepare($query);
$statement->execute(
array(
':title' => $title,
':description' => $desc,
':text' => $text
)
);
}
catch(PDOException $e){
throw new Exception($e -> getMessage() . " " . get_class($this).' -> '.__METHOD__);
$file = "exceptionlog.txt";
file_put_contents($file, $e -> getMessage(), FILE_APPEND);
}
echo "Added!";
}
for($i=0; $i<$number; $i++)
{
if(trim($_POST["mytext"][$i] != ''))
{
try{
$query = "INSERT INTO data
(name)
VALUES (:name)";
$data = array(':name' => $_POST["mytext"][$i]);
$statement = $connect->prepare($query);
$statement->execute($data);
}
catch(PDOException $e){
throw new Exception($e -> getMessage() . " " . get_class($this).' -> '.__METHOD__);
$file = "exceptionlog.txt";
file_put_contents($file, $e -> getMessage(), FILE_APPEND);
}
}
}
}
?>
If I've understood your question correctly, LastInsertId() is your tool here.
https://www.w3schools.com/php/php_mysql_insert_lastid.asp
//name.php
<?php
$number = count($_POST["mytext"]);
if($number > 0)
{
$title = $_POST["title"];
$desc = $_POST["description"];
$text = $_POST["text"];
$connect = new PDO('mysql:dbname=test_db;host=localhost','root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
if(trim($title)!='' || trim($desc)!='' || trim($text)!='')
{
try{
$query = "INSERT INTO article
(title, description, text)
VALUES (:title, :description, :text)";
$statement = $connect->prepare($query);
$statement->execute(
array(
':title' => $title,
':description' => $desc,
':text' => $text
)
);
$position_id = $statement->LastInsertId();
}
catch(PDOException $e){
throw new Exception($e -> getMessage() . " " . get_class($this).' -> '.__METHOD__);
$file = "exceptionlog.txt";
file_put_contents($file, $e -> getMessage(), FILE_APPEND);
}
echo "Added!";
}
for($i=0; $i<$number; $i++)
{
if(trim($_POST["mytext"][$i] != ''))
{
try{
$query = "INSERT INTO data
(name, position_id)
VALUES (:name, '".$position_id."')";
$data = array(':name' => $_POST["mytext"][$i]);
$statement = $connect->prepare($query);
$statement->execute($data);
}
catch(PDOException $e){
throw new Exception($e -> getMessage() . " " . get_class($this).' -> '.__METHOD__);
$file = "exceptionlog.txt";
file_put_contents($file, $e -> getMessage(), FILE_APPEND);
}
}
}
}

How To Retrieve Column's Data of a Table, Store It Into An Array, and Finally Echo The Array

Here's what I'm basically trying to do:
Retrieve the values of a column
Store those values into an array in PHP
Echo each value with a line break in between each value
Here's my attempted code:
<?php
$connection = mysqli_connect("localhost", "root", "bruhfrogzombie098", "growtapi_social");
if (!$connection) {
die("Failed to connect to MYSQL: " . mysqli_connect_errno());
};
$members = mysqli_query($connection, "SELECT Username FROM s_users");
$members_status = mysqli_query($connection, "SELECT Status_Content FROM s_users");
$members_array = array();
while ($member = mysqli_fetch_assoc($members)) {
$members_array[] = $member;
};
$members_status_array = array();
while ($status = mysqli_fetch_assoc($members_status)) {
$members_status_array[] = $status;
};
?>
And this is where I want to echo out the values:
<center>
<h1>Members Directory</h1>
<div style="width: 20%; height; 75%; border: 3px solid black; margin: auto; overflow: hidden; overflow-y: scroll;">
<?php echo $members_array['$member'];
echo "<br />";
?>
</div>
</center>
I don't receive any errors, but the problem is that nothing shows up in the div, meaning that I either didn't retrieve the data properly or didn't use it right.
Note: I've finally moved on to writing up-to-date code, so I hope no one here comments that somewhere in this code I have outdated code ( ͡° ͜ʖ ͡°)
$members_array = array();
while ($member = mysqli_fetch_assoc($members)) {
$members_array[] = $member;
//$members_array is array and $member is array so $members_array like $members_array[][];
};
<center>
<h1>Members Directory</h1>
<div style="width: 20%; height; 75%; border: 3px solid black; margin: auto; overflow: hidden; overflow-y: scroll;">
<?
$member_count = count($members_array);
for( $i = 0 ; $i < $member_count ; $i++ ){
echo $member_array[$i]['Username'];
echo "<br />";
}
?>
</div>
</center>

PHP MySQL Result displays twice why?

I have this simple PHP Script to fetch results from the localhost WAMP server, and when I echo the query it displays one record twice for every record I have!
Result displayed as shown in picture:
Here is the PHP MySQL script
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$movie_lists = "";
$no_result = "";
$servername = "localhost";
$username = "root";
$password = "localpass";
$dbname = "movieadventuredb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$sql = "SELECT id, movie_quality, movie_release_date FROM movielisting";
$sql = "SELECT * FROM movielisting ORDER BY ID DESC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "id: " . $row["id"]. " - Name: " . $row["movie_name"]. " " . $row["movie_quality"]. "<br>";
$id = $row["id"];
$movie_quality = $row["movie_quality"];
$release_date = strftime("%Y", strtotime($row["movie_release_date"]));
$movie_lists .= "<div class='item item-1'><a href='#'><img src='inventory_images/$id.jpg'/></a>
<a href='#'><div class='overlay'>
<p class='movie_quality $movie_quality'>$movie_quality</p>
<p class='movie_year year'>$release_date</p>
</div></a>
</div>";
}
} else {
$movie_lists = "";
}
$conn->close();
?>
Below is the code for CSS for the listing.
.recent_movies_slider .recent_movie_lists {float:left; width:97%;}
.slider-horizontal {width:90%; margin:25px auto; *background:#eee; height:240px; z-index:1;}
.slider-horizontal .item {height:200px; width:150px; margin:20px 10px 0;}
.slider-horizontal .item img {height:200px; width:150px;}
.slider-vertical {width:364px; margin:25px 0; float:left; background:#eee; height:300px;}
.slider-vertical .item {height:80px; width:324px; margin:10px 0 10px 20px;}
.overlay { position: relative; top:-204px; left:0; *right:0; *bottom:0; width:150px; height:200px; z-index:2; display:block; *background:red; *background-color: rgba(0,0,0,0.5); color:#fff;}
.overlay:hover {background:rgba(48, 160, 186, 0.43) url("../default_images/play-button.png") no-repeat; background-position:50% 50%;}
.movie_quality {
position: absolute;
bottom: 5px;
left: 5px;
text-transform:uppercase;
}
.hd {background:#B43104; padding:2px; border-radius:2px;}
.cam {background:#DBA901; padding:2px; border-radius:2px;}
.year {background:#086A87; padding:2px; border-radius:2px;}
.movie_year {
position: absolute;
bottom: 5px;
right: 5px;
}
and below is the HTML to echo out the result
<div class="recent_movie_lists">
<div id="slider" class="slider-horizontal">
<?php echo $movie_lists; ?>
</div>
</div>
Try setting this: $movie_lists = (all your code); instead of $movie_lists .= (all your code).
Sorry for all the stuff above, as allready answered in the comments. Why don't you just echo out the while loop in your div?
<div class="recent_movie_lists">
<div id="slider" class="slider-horizontal">
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "id: " . $row["id"]. " - Name: " . $row["movie_name"]. " " . $row["movie_quality"]. "<br>";
$id = $row["id"];
$movie_quality = $row["movie_quality"];
$release_date = strftime("%Y", strtotime($row["movie_release_date"]));
echo "<div class='item item-1'><a href='#'><img src='inventory_images/$id.jpg'/></a>
<a href='#'><div class='overlay'>
<p class='movie_quality $movie_quality'>$movie_quality</p>
<p class='movie_year year'>$release_date</p>
</div></a>
</div>";
}
} else {
echo "";
}
?>
</div>
</div>
As I'm assuming your keeping the HTML and PHP in the same file.

PHP: global variable not being stored?

It turns out this has nothing to do with global variables (sorry discussed in another post).
I was trying to keep all the code on one page (self-processing), but I'm pretty sure it's not possible. Arranging the following code outlined in the answer below, on the same page, does not work. Figures.
*edited to add the whole script minus the CSS (unnecessary).
<!DOCTYPE html>
<head>
<title>Inventory Tables</title>
</head>
<style></style>
<body>
<?php //IRCinventoryhome.php
require("IRCpage.inc");
require_once 'IRCinventoryconfig.php';
$homepage = new IRCtemplate();
$homepage->Display();
session_start();
?>
<!-- Dropdown Menu for Table Selection -->
<div id="contentHeader">
<?php //Menu for table selection
ini_set('display_errors',1); error_reporting(E_ALL);
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$result = $connection->query("SHOW TABLES");
$table = array();
while ($row = $result->fetch_row()){
$table[] = $row[0];
}
$count = count($table);
?>
<div id="select">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<select name="value">
<?php for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo <<<_END
<pre>
<option value="$table[$pointer]">$table[$pointer]</option>
</pre>
_END;
}
?>
</select>
<input type="submit" value="go">
</form>
</div> <!-- End .select -->
</div> <!-- End #contentHeader -->
<div id="content">
<!-- Code for Database Tables and Actions -->
<?php //inventory mysql tables
if (($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['value'])) {
$thisTable = $_POST['value'];
global $thisTable;
ini_set('display_errors',1); error_reporting(E_ALL);
$queryColumns = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
if (!$resultColumns) die ("Database access failed: " . $connection->error);
$columns = array();
while ($column = $resultColumns->fetch_row()){
$columns[] = $column[0];
}
echo "<div id=\"table\"><table class=\"CSSTableGenerator\" >\n";
$count = count($columns);
$insertColumns = array();
for ($pointer = 1 ; $pointer < $count ; ++$pointer) {
$insertColumns[] = $columns[$pointer];
}
for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo "<th scope=\"col\" bgcolor=\"#efefef\">";
echo $columns[$pointer];
echo "</th>";
}
echo "<th>ACTIONS</td>";
$queryRows = "SELECT * FROM $thisTable";
$resultRows = $connection->query($queryRows);
if (!$resultRows) die ("Database access failed: " . $connection->error);
$rows = $resultRows->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$resultRows->data_seek($j);
$row = $resultRows->fetch_array(MYSQLI_NUM);
$count = count($row);
echo "<tr>";
for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo "<td>";
echo $row[$pointer];
echo "</td>";
}
?>
<td>
<input action="<?php echo $_SERVER['PHP_SELF']?>" type="submit" value="edit" name="edit">
<input action="<?php echo $_SERVER['PHP_SELF']?>" type="submit" value="delete" name="delete">
</td>
</tr>
<?php
}
echo "</table></div>"; //end table, end content
$connection->close();
}
?>
<!-- FORM FOR ADDING ROWS TO CURRENT TABLE -->
<div id="table">
<table id="formTable">
<form name="addRow" action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type="hidden" name="control">
<td>
Add row?
</td>
<?php for ($pointer = 1 ; $pointer < $count ; ++$pointer) { ?>
<td>
<input type="text" name="<?php echo $columns[$pointer];?>">
</td>
<?php } ?>
<td>
<input type="submit" value="go">
</td>
</form>
</table>
</div> <!-- end form, end table, end content -->
<?php
global $thisTable;
echo $thisTable;
if (isset($_POST['control'])) {
global $thisTable;
echo $thisTable;
$valuesArray = array();
if (isset($_POST)) {
$valuesArray = $_POST;
}
$columnsArray = array_keys($valuesArray);
//array_splice($columnsArray, 0, 1);
$columnsString = implode(", ", $columnsArray);
print_r($columnsString);
$insertValues = array();
foreach($valuesArray as $values) {
$insertValues[] = $values;
}
$valuesString = implode(" ", $insertValues);
$valuesString = "'".$valuesString."'";
$valuesString = str_replace(" ", "', '", $valuesString);
$valuesString = substr($valuesString, 3);
print_r($valuesString);
/*
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$queryInsert = "INSERT INTO $thisTable ($columnsString) VALUES ($valuesString)";
$result = $connection->query($queryInsert);
if (!$result) echo "INSERT failed: $query<br>" .
$connection->error . "<br><br>";
$connection->close();
*/
}
?>
</div> <!-- End #content -->
</body>
</html>
After 20 hours or so I'm still not sure if this possible to do all on the same page. But this solution works...
Page one:
<!DOCTYPE html>
<head>
<title>Interactive Resource Center Inventory</title>
<meta charset="UTF-8">
</head>
<script src="../_js/jquery.min.js"></script>
<script src="../_js/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$('form').submit(function() {
$('input[type=submit]')
prop('disabled',true);
});//end submit
var max_fields = 4; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div>Column: <input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});//end ready
</script>
<style>
#table {
margin-top:2px;
}
#formTable {
width:100%;
margin:0px;padding:0px;
border:1px solid #000000;
border-bottom:none;
border-left:none;
border-right:none;
}
#formTable td{
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
width:100px;
font-size:14px;
font-family:arial;
font-weight:normal;
color:#000000;
}
#formTable input[type="text"]{
width:95%;
}
.CSSTableGenerator {
margin:0px;padding:0px;
width:100%;
border:1px solid #000000;
border-top:none;
border-right:none;
border-left:none;
}
.CSSTableGenerator table{
width:100%;
height:100%;
margin:0px;padding:0px;
}
.CSSTableGenerator tr:nth-child(odd){ background-color:#e5e5e5; }
.CSSTableGenerator tr:nth-child(even) { background-color:#ffffff; }
.CSSTableGenerator th{
border:1px solid #000000;
border-width:0px 1px 1px 0px;
width:100px;
}
.CSSTableGenerator td{
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
width:100px;
font-size:14px;
font-family:arial;
font-weight:normal;
color:#000000;
}
.CSSTableGenerator tr:last-child td{
border-width:0px 1px 0px 0px;
}
.CSSTableGenerator tr td:last-child{
border-width:0px 0px 1px 0px;
}
.CSSTableGenerator tr:last-child td:last-child{
border-width:0px 0px 0px 0px;
}
.CSSTableGenerator tr:first-child td{
background:-o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) ); background:-moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#b2b2b2"); background: -o-linear-gradient(top,#cccccc,b2b2b2);
background-color:#cccccc;
border:0px solid #000000;
text-align:center;
border-width:0px 0px 1px 1px;
font-size:14px;
font-family:arial;
font-weight:bold;
color:#000000;
margin-top:-2px;
</style>
<body>
<?php //IRCinventoryhome.php
require("IRCpage.inc");
require("IRCinventoryfunctions.php");
require_once 'IRCinventoryconfig.php';
$homepage = new IRCtemplate();
$homepage->Display();
session_start();
$_SESSION['value'] = $_POST['value'];
$thisTable = $_SESSION['value'];
var_dump($_SESSION);
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
if ($connection->connect_error) die($connection->connect_error);
global $connection;
$result = $connection->query("SHOW TABLES");
$table = array();
while ($row = $result->fetch_row()){
$table[] = $row[0];
}
$count = count($table);
?>
<!-- Dropdown Menu for Table Selection -->
<div id="contentHeader">
<div id="select">
<form action="http://localhost:8888/IRC/IRCinventoryhometest.php" method="POST">
<select name="value">
<?php for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo <<<_END
<pre>
<option value="$table[$pointer]">$table[$pointer]</option>
</pre>
_END;
}
?>
</select>
<input type="submit" name="go">
</form>
</div> <!-- End .select -->
</div> <!-- End #contentHeader -->
<div id="content">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$thisTable = "OUTGOING";
$queryColumns = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
if (!$resultColumns) die ("Database access failed: " . $connection->error);
global $resultColumns;
$queryRows = "SELECT * FROM $thisTable";
$resultRows = $connection->query($queryRows);
if (!$resultRows) die ("Database access failed: " . $connection->error);
global $resultRows;
$rows = $resultRows->num_rows;
global $rows;
global $connection;
drawTable();
$connection->close();
} else {
if(isset($_POST['value'])) {
$thisTable = $_POST['value'];
}
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
if ($connection->connect_error) die($connection->connect_error);
global $connection;
$queryColumns = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
if (!$resultColumns) die ("Database access failed: " . $connection->error);
global $resultColumns;
$queryRows = "SELECT * FROM $thisTable";
$resultRows = $connection->query($queryRows);
if (!$resultRows) die ("Database access failed: " . $connection->error);
global $resultRows;
$rows = $resultRows->num_rows;
global $rows;
global $connection;
drawTable();
?>
<!-- FORM FOR ADDING ROWS TO CURRENT TABLE -->
<div id="table">
<table id="formTable">
<form name="addRow" action="http://localhost:8888/IRC/IRCprocessinventory.php" method="POST">
<input type="hidden" name="control">
<td>
Add row?
</td>
<td></td>
<?php for ($pointer = 2 ; $pointer < $countColumnsGlobal ; ++$pointer) { ?>
<td>
<input type="text" name="<?php echo $columns[$pointer];?>">
</td>
<?php } ?>
<td>
<input type="submit" value="submit">
</td>
</form>
</table>
</div> <!-- end table -->
<?php
}
?>
</div> <!-- End #content -->
</body>
</html>
Page 2:
<?php
require_once 'IRCinventoryconfig.php';
ini_set('display_errors',1); error_reporting(E_ALL);
session_start();
if(isset($_SESSION['value'])) {
$thisTable = $_SESSION['value'];
$valuesArray = array();
if (isset($_POST)) {
$valuesArray = $_POST;
}
$columnsArray = array_keys($valuesArray);
array_splice($columnsArray, 0, 1);
$columnsString = implode(", ", $columnsArray);
$insertValues = array();
foreach($valuesArray as $values) {
$insertValues[] = $values;
}
$valuesString = implode("','", $insertValues);
$valuesString = "'".$valuesString."'";
$valuesString = substr($valuesString, 3);
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
if ($connection->connect_error) die($connection->connect_error);
$queryInsert = "INSERT INTO $thisTable ($columnsString) VALUES ($valuesString)";
$result = $connection->query($queryInsert);
if (!$result) echo "INSERT failed: $query<br>" .
$connection->error . "<br><br>";
else echo "Successful entry";
$connection->close();
}
?>

AJAX loading whole page instead of part of the page to load data from database

I want to show image in iframe using AJAX but my full page is loading in every 5 seconds where I want only a content will load if there is any change in the status table.
I think I have do something with the section. May be I need to transfer the PHP code some where or I need to do some change on DIV. if someone please help me ?
main.php
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(function(){
function status(){
$.ajax({
type: "GET",
url: "main.php",
success: function(data){
$('div.divGranite').html(data);
}
});
};
setTimeout(status, 5000);
});
</script>
</head>
<body>
<div id="divGranite">
<?php
//Connect to Database
$connection = mysqli_connect("localhost", "root", "pass");
if (!$connection) {
die("Error: " . mysqli_error());
}
$db_select = mysqli_select_db($connection, "database");
if (!$db_select) {
die("Error: " . mysqli_error());
}
$appID = "select * from table where state= '1' ";
$result = mysqli_query($connection,$appID);
while ($row = $result->fetch_assoc()) {
$currentID = $row['id']."<br>";
}
?>
</div>
<div id="display1">
</div>
</body>
<?php
if($currentID != $displayID){
function loadUnload($ID) {
$connection = mysqli_connect("localhost", "root", "pass");
if (!$connection) {
die("Error: " . mysqli_error());
}
$db_select = mysqli_select_db($connection, "usr_web26_1");
if (!$db_select) {
die("Error: " . mysqli_error());
}
switch ($ID) {
case $ID == 1:
echo '<div>';
echo '<iframe src="../imageview/index.php" id="imgiframe" style="position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe>';
echo '</div>';
break;
case $ID == 2:
echo '<div>';
echo '<iframe src="../videoview/index.php" id="imgiframe" style="position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe>';
echo '</div>';
break;
default:
echo "Wrong ID";
break;
}
}
?>
</html>
For the ajax code write this
$(function(){
var lastData = '';
function status(){
$.ajax({
type: "GET",
url: "main.php",
success: function(data){
if (data != prevData) {
$('div.divGranite').html(data);
prevData = data;
}
}
});
};
setTimeout(status, 5000);
});
rest of them is fine !
This main.php is returning the hole main.php including head-tag and putting it into the divGranite, if you want an ajax request to just return a part of the what main.php produces you need make two files:
main.php - rendering the default page
ajax.php - rendering the
iframe only
This would open you up to call ajax.php instead and give you the wanted result
Your ajax.php would look something like this,
<?php
//Connect to Database
$connection = mysqli_connect("localhost", "root", "pass");
if (!$connection) {
die("Error: " . mysqli_error());
}
$db_select = mysqli_select_db($connection, "database");
if (!$db_select) {
die("Error: " . mysqli_error());
}
$appID = "select * from table where state= '1' ";
$result = mysqli_query($connection,$appID);
while ($row = $result->fetch_assoc()) {
$currentID = $row['id']."<br>";
}
if($currentID != $displayID) {
function loadUnload($ID) {
$connection = mysqli_connect("localhost", "root", "pass");
if (!$connection) {
die("Error: " . mysqli_error());
}
$db_select = mysqli_select_db($connection, "usr_web26_1");
if (!$db_select) {
die("Error: " . mysqli_error());
}
switch ($ID) {
case $ID == 1:
echo '<div>';
echo '<iframe src="../imageview/index.php" id="imgiframe" style="position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe>';
echo '</div>';
break;
case $ID == 2:
echo '<div>';
echo '<iframe src="../videoview/index.php" id="imgiframe" style="position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe>';
echo '</div>';
break;
default:
echo "Wrong ID";
break;
}
}

Categories