php update new SQL content [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm new to PHP so please have patience and explain it to me like I'm 5.
I have a page where it shows the content of a table from SQL, but whenever I update with php I have for force update my browser to make it display the new content of the table. I got the same problem as this guy but I didn't understand his solution:
Php won't update to show new sql content
This is my PHP code for updating the table:
<!-- html dok -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
</body>
</html>
<?php
$server = "localhost";
$brugernavn = "";
$kode = "";
$db = "";
mysql_connect($server , $brugernavn , $kode) or die(mysql_error());
echo "Forbundet til mysql server<br/>";
mysql_select_db($db)or die(mysql_error());
echo "Forbundet til databasen<br/><br/>";
$data = mysql_query("SELECT * FROM nyheder" ) or die(mysql_error());
while ($info = mysql_fetch_array($data))
{
echo "Nyhed: " . $info['nyhed']. "<br/><br/>";
}
// Update tabel
if (isset($_POST['update'])) {
$nyhed = $_POST['nyhed'];
$tabeldata = "UPDATE nyheder SET nyhed = '$nyhed' WHERE ID ='1'";
$resultat = mysql_query($tabeldata);
if($resultat) {
echo "Din nyhed blev opdateret" . "<a href=get.php>Videre</a>";
}
else {
echo "FEJL";
}
}
else {
echo "Ingen nyheder er blevet opdateret";
}
mysql_close();
?>
and this is my code for displaying the table content:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT nyhed FROM nyheder WHERE ID='1'";
$result = $conn->query($sql);
$link_address = 'form.php';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["nyhed"] . "<br><br>";
echo "<a href='$link_address'>Opdater</a>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
Thank you so much in advance! :)

If you want to use Php won't update to show new sql content's answer change below
if($resultat) {
echo "Din nyhed blev opdateret" . "<a href=get.php>Videre</a>";
}
to
if($resultat) {
echo "Din nyhed blev opdateret" . "Videre";
}
this will add current time to get.php as query string (will looks like get.php?time=1417626725) and every time you click the link browser sees get.php as new url and fetch the page again without load it from cache (if it's cached)

Related

how to redirect to another page in php an mySql Database?

how can I redirect the user to another php page based on the button he is pressing?
For example .. I want that once loaded the page, in it are generated buttons containing the "id" of the table taken from a database ... At the click of the button you are redirected to a page in which there are textbox with the fields belonging to the table id ..
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT idCantiere,nomeCantiere,codiceCommessa,indirizzoCantiere FROM Cantiere";
$result = $conn->query($sql);
echo'<h1> <font face="verdana" color="green">Quale Cantiere desideri Modificare?</font> </h1>';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo'<br><br><br>';
echo'' . $row["nomeCantiere"] . '';
// echo '';
//''<input type="button" value="' . $row["nomeCantiere"] . '" />'
}
echo'<br><br><br>';
echo 'Nuovo Cantiere +';
} else {
echo "0 results";
}
$idCantierePerSelect = $_POST["idCantiere"];
global = $idCantierePerSelect;
function navigaButton()
{
// FUNCTION That redirect to the page
};
$conn->close();
?>
So I have to pick up the "idCantiere" and I have to make sure that by clicking on the button on the page that opens me there are textBox with the data of the table of the "idCantiere"
I think you are confusing the static html between dynamic server page.
1.PHP is responsible for fecthing data from database or server file system ,and send html tags to front end
2.the browser receives strings from php , and parse the strings to html elements ,finally starts to run javascript
If you want to redirect page.
In php header('Location: /your/path')
In javascript , window.location.href='/your/path'
Very quickly written and not tested - you could perhaps do like this. The function has to be javascript to interact with the client's actions ( ie: button press ) but the processing of the task is done by php. So, in the loop pass the ID of the record to the function as an inline argument and reload the same page with a new querystring. PHP will process the querystring, find the ID and then do a different database lookup to find the page that you want to redirect to.
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) die("Connection failed");
/*
This section should be ignored when page loads normally
but will be processed when the `navigaButton` is called
and the url changes.
*/
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['action'],$_GET['id'] ) ){
$sql='select NEWLOCATION from TABLE where ID=?';
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bind_param('i',$id);
$id=filter_input( INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT );
$stmt->execute();
$stmt->store_result();
$stmt->bind_result( $url );
$stmt->close();
/* read the recordset and .... */
exit( header( 'Location: '.$url) );
}
}
?>
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>.... </title>
<script>
function navigaButton(id){
location.search='action=redirect&id='+id
};
</script>
</head>
<body>
<?php
$sql = "SELECT idCantiere,nomeCantiere,codiceCommessa,indirizzoCantiere FROM Cantiere";
$result = $conn->query($sql);
echo'<h1> <font face="verdana" color="green">Quale Cantiere desideri Modificare?</font> </h1>';
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo'
<br><br><br>
' . $row["nomeCantiere"] . '
';
}
echo'<br><br><br>
Nuovo Cantiere +';
} else {
echo "0 results";
}
$idCantierePerSelect = $_POST["idCantiere"];
/* below is incorrect */
/*global = $idCantierePerSelect;*/
$conn->close();
?>
</body>
</html>

Create a Clickable Link from a Table made from Database Results

I'm making a class web-page that allow you to view class details by clicking a link associated with the class. I have a database loaded with classes,enrolled students as well as the assigned professor. Below I have the query in a for each loop creating a table from the results however I want to make the entries urls that direct to that class page. For example: "localhost/class?class_id=cs120". I can't just add a link below and have it parameterized to cs120 as all links would just go there. My understanding of SQLITE3, PHP and HTML is limited, Below is my code for this page.
<!DOCTYPE html>
<?php include("secure.php") ?>
<html lang= "en">
<head>
<title> Class Index </title>
<meta charset= "utf-8" />
<link rel="stylesheet" href="class_coverpage.css" />
</head>
<?php
//echo("Hello Retrieving Table");
$username = $_SESSION['user'];
//echo 'Hello: ' . $username;
$classquery = "SELECT DISTINCT Classes.Class_id, Classes.Section_id ,Classes.className, Classes.Subject, Classes.Location FROM Classes,StudentClasses,Students WHERE StudentClasses.Class_id = Classes.Class_id AND StudentClasses.Student_id = Students.Student_id AND StudentClasses.Section_id = Classes.Section_id AND Students.Username = '$username'; ";
//$teacherquery = "SELECT TeacherClasses.Teacher_id, TeacherClasses.Class_id FROM TeacherClasses";
//echo("Trimming Query");
trim($classquery);
//echo("Stripping Slashes");
$classquery = stripslashes($classquery);
//echo("Setting up Query");
$results = $db->query($classquery);
if (!$results){
echo("<h2>Error: The query could not be executed.</h2>");
$error = $db->lastErrorMsg();
echo("<p>$error<p>");
exit;
}
echo "<table><tr>";
echo "<td>Course ID:</td>";
echo "<td>Section ID:</td>";
echo "<td>Subject:</td>";
echo "<td>Location:</td></tr>";
echo("<tr>");
for($i=0;$i<$num_cols;$i++){
$head = $results->columnName($i);
echo("<th>$head</th>");
}
echo ("</tr>");
// Write rows into table
$ct = 0;
while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
echo ("<tr>");
foreach($row as $v){
// I want to Make this section down here create a link hopefully.
//echo ("<td><a href='class_detail.php?Class_id=$row['id']'> $v </a></td>");
}
$ct = $ct + 1;
echo ("</tr>");
}
echo
("</table>");
?>

Simple PHP script connected to MYSQL Database

I have the following code and need some customizations. I need a line break after each mysql record and the capability for the webpage to load at the very bottom. Can this be possible? Thanks in advance. CODE:
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title> Food Orders </title>
<link rel="stylesheet" type ="text/css" href="default.css">
</head>
<body>
<?php
$server_name = "localhost";
$user_name = "root";
$password = "mysqlpW";
$database_name = "menuDB12";
$connection = new mysqli($server_name, $user_name, $password, $database_name);
if ($connection->connect_error) {
die("Connection Error: " . $connection->connect_error);
}
$attributes "SELECT tablenumber, food FROM clients";
$results = $connection->query($attributes);
if ($results->num_rows > 0) {
while ($rows = $results->fetch_assoc()) {
echo "Table Number: " . $rows["tablenumber"]. " Food Item: " . $rows ["food"].
"<br>";
}
} else {
echo "No Results";
}
$connection->close();
?>
</body>
</html>
if i understood right, you want to display your database results at the end of the page, for that you can try this
$table = ''; if ($results->num_rows > 0) {
while ($rows = $results->fetch_assoc()) {
$table .= "Table Number: " . $rows["tablenumber"]. " Food Item: " . $rows ["food"].
"<br>";
}
} else {
$table = "No Results";
}
and at the end of your page or where you want it to be displayed simply add
<?php echo $table; ?>
You write about line breaks in the original question, but in the comments you specify page breaks (for printing).
Also, I understand you want the content to be displayed at the bottom of the printed page.
If my understanding is correct (and it would help if you edited the question to be more precise), I'd suggest consulting the following:
Page breaks for printing on php page
It helped me some time ago when I was creating a web-based document for printing.
Just use echo "<br>"; for a new line.
And i would recommend ajax for refreshing
https://www.w3schools.com/xml/ajax_intro.asp

Publishing MySQL data into PHP Columns [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
im working on a project for basically my friends and i to use. Maybe to use it for other games as well. SpeedRunning! i have made and was able to POST the Data into MySQL with THIS information
<?php include_once('include/action_page.php');?>
<!DOCTYPE HTML>
<meta charset="UTF-8">
<html>
<head>
<title>Roleplayer's Tavern Home</title>
<link href="/style/style.css" rel="stylesheet" type="text/css">
<script src="/include/jquery-1.11.2.min.js"></script>
<?php include_once('/include/rpt_site_no_script.php');?>
</head>
<body onload="">
<div class="page_container" name="page_container">
<div id="page_header">
<!-- The title of the webpage -->
<div style="max-width:250px; overflow:hidden">
<span id="header_title"><img src="style/logo.png" style="width:225px; height:67px;"/></span>
</div>
</div>
<!-- Left side bar -->
<div id="page_container_left">
<h3 id="page_content_header">Submit your data!</h3>
<?php include('include/submit_data.php');?>
</div>
<div id="page_container_right"
style="overflow-y: auto; max-height: 100%">
<h3 id="page_content_header">Donations for website?</h3>
<?php
?>
</div>
<!-- Main Content -->
<div id="page_content_container_main_page">
<div class="page_content_container">
<h2 id="page_content_container_header">Leaderboard WOO WOO</h2>
<hr>
<p id="page_content_container_content">
<h2>Players That Have Beaten Mad Pack 2</h2>
<?php include('include/leaderboard.php');?>
</div>
</div>
<br>
<!-- Footer -->
<div id="page_footer">
<ol id="footer_list">
<li>Copyright © Roleplayer's Tavern 2015-2016 - All Rights Reserved</li>
<li style="font-size:12px">Your IP address <?php echo $_SERVER['REMOTE_ADDR']; ?> will be logged for security reasons.</li>
</ol>
</div>
</div>
<script type="text/javascript">
var element=document.getElementsByName('page_container')[0];
var applyTo=document.getElementById('page_container_left');
var applyTo2=document.getElementById('page_container_right');
applyTo.style.height = (element.offsetHeight - 2) + "px";
applyTo2.style.height = (element.offsetHeight - 2) + "px";
window.onresize = function(event) {
var element=document.getElementsByName('page_container')[0];
var applyTo=document.getElementById('page_container_left');
var applyTo2=document.getElementById('page_container_right');
applyTo.style.height = (element.offsetHeight - 2) + "px";
applyTo2.style.height = (element.offsetHeight - 2) + "px";
}
</script>
</body>
</html>
as this is the HTML format.
Action_page.php is the page for submitting the information
<?php
$servername = "localhost";
$username = "USERNAME";
$password = "PASSWORD";
$mysqlDatabaseName = "SpeedRun";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $mysqlDatabaseName);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$sql = "INSERT INTO MineCraftRecords (MineCraftName, LevelSeed, Day, Time)
VALUES ('$_POST[MinecraftName]', '$_POST[LevelSeed]', '$_POST[Day]', '$_POST[Time]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Turtle Mode Activated";
$conn->close();
?>
<meta http-equiv="Location" content="https://rptavern.org/SpeedRun/">
and im having trouble on getting the page to LOAD the information provided into the leaderboard.php as this is what i have so far.
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$servername = "localhost";
$username = "USERNAME";
$password = "PASSWORD";
$mysqlDatabaseName = "SpeedRun";
$query="SELECT * FROM MineCraftRecords";$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;while ($i < $num) {CODE$i++;}
$variable=mysql_result($result,$i,"fieldname");
$field1-name=mysql_result($result,$i,"MineCraftName");
$field2-name=mysql_result($result,$i,"LevelSeed");
$field3-name=mysql_result($result,$i,"Day");
$field4-name=mysql_result($result,$i,"Time");
$field5-name=mysql_result($result,$i,"id");
// Create connection
$conn = mysqli_connect($servername, $username, $password, $mysqlDatabaseName);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Turtle Mode Activated";
?>
Im basically trying to base it off this website http://www.speedrun.com/mc but not as technical. Just to show the SpeedRunning time and have the TIME the top of the list.
Any help is awesome, as im very new to creating stuff like this. i will take the time to read everyone's comments and suggestions that you all can provide :D
I suggest cleaning up your code. Some thing that can be done is that you can separate the dB connect details into a separate file. This will optimize your code and will it make sure to change the details later on as your project grows.
If you would ever consider using PDO here is a code example that will help you out. I'm not sure if mySQLi is similar to PDO but have a look anyway. It's super easy to use and implement in as many pages as possible!
HTML/PHP (displaying data in table):
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
</head>
<body>
<?php
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(-1);
require_once("../DAL/db_functions.php");
//Run query on branch table
readQuery("M_Branch");
//If there are any details in branch table continue
if($numRecords === 0){
echo "<p>No Branches Found!</p>";
}
else{
$arrRows = NULL;
//Create table and headings
echo "<table id='mavis' border='1' width='100%'>";
echo "<tr>";
echo "<th>Branch Code</th>";
echo "<th>Branch Name</th>";
echo "<th>Manager</th>";
echo "<th>Branch Address</th>";
echo "<th>Suburb</th>";
echo "<th>State</th>";
echo "<th>Post Code</th>";
echo "<th>Phone Number</th>";
echo "<th>Fax Number</th>";
echo "<th></th>";
echo "</tr>";
while($arrRows = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>";
echo "<td>".$arrRows['Branch_Code']."</td>";
echo "<td>".$arrRows['Branch_name']."</td>";
echo "<td>".$arrRows['Manager']."</td>";
echo "<td>".$arrRows['Branch_Address']."</td>";
echo "<td>".$arrRows['Suburb']."</td>";
echo "<td>".$arrRows['State']."</td>";
echo "<td>".$arrRows['Post_code']."</td>";
echo "<td>".$arrRows['Phone']."</td>";
echo "<td>".$arrRows['Fax']."</td>";
//Cannot delete already created records - Foreign key constraint fails
//If phpMyadmin were to delete one then other tables will incur problems
echo "<td><a href='edit_branch.php?ID=$arrRows[Branch_Code]'>Edit</a>";
echo "<br /><a href='../BLL/delete_confirm.php?TYPE=Branch&ID=$arrRows[Branch_Code]' onClick='return checkDelete()'>Delete</a></td></tr>";
}
echo "</table>";
echo "<form action='../DAL/add_branch.php' method='post'>";
echo "<input type='submit' value='Add a New Branch' />";
echo "</form>";
echo "<p></P><P>$numRecords Records Returned</P>";
}
?>
</body>
Here is my connect and readQuery function located in ../Db_functions.php
I have created functions that are reusable and can be used with multiple DB tables.
//Database connection Variables
$localhost = "localhost";
$user = "root";
$password = "root";
$db = "Mavis";
$dsn = "mysql:host=$localhost;dbname=$db";
//Declare Global Variables
$dbConnection = NULL;
$stmt = NULL;
$numRecords = NULL;
//This connect database function can be used to connect anywhere
function connect(){
//These are variables from the other file (dblibary) - global allows access to these variables
global $user, $password, $dsn, $dbConnection; //Required to access the global variables.
try{
$dbConnection = new PDO($dsn, $user, $password);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $error){
//display error message if connection doesnt work
echo "The following error occured: " . $error->getMessage();
}
}
Read Query:
function readQuery($table){
global $numRecords, $dbConnection, $stmt;
connect();
$sqlStr = "SELECT * FROM " . $table.";";
try{
$stmt = $dbConnection->query($sqlStr);
if($stmt === false){
die("Error executing the qquery: $sqlStr");
}
}
catch(PDOException $error){
echo "An Error occured: " . $error->getMessage();
}
$numRecords = $stmt->rowCount();
//Close the DB connection
$dbConnection = NULL;
}

How to connect a MySQL db to an html page using php on XAMPP server?

Hi i was trying to connect MySQL database to a simple html code given below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org
/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="result.php" method="POST">
S.No :
<input type="text" name="key">
<input type="submit" value="Search">
</form>
</body>
</html>
This html code passes the form input "key" to another php file whose code is given below.
<?php
$serial=$POST['key'];
if(!$serial){
echo 'Please go back and enter the correct value';
exit;
}
$db = new mysqli('localhost', 'root', '', 'demo_db', 'tbldem');
if(mysqli_connect_errno()) {
echo 'Connection lost.. please try again later !!';
exit;
}
$query = "select * from tbldem where".$serial."like'%".$serial."%'" ;
$result = $db->query($query);
$num = $result->num_rows;
for($i = 0; $i < $num; $i++) {
$row = $result->fetch_assoc();
echo"<p>Serial : </p>";
echo $row['Index'];
echo"<p>Name : </p>";
echo $row['Name'];
echo "<p>Course : </p>";
echo $row['Course'];
}
$result->free();
$db->close();
?>
Now when I try to pass a value in the form input in the my browser I get a php code as a result instead of the information in the database which was supposed to to be returned while passing the value in form input, which is also given below(the problem). I am trying to make a project which use this feature as a primary tool so please help as soon as possible.
query($query); $num = $result->num_rows;
for($i = 0; $i < $num; $i++) {
$row = result->fetch_assoc(); echo"
Serial :
"; echo $row['Index']; echo"
Name :
"; echo $row['Name']; echo "
Course :
"; echo $row['Course']; } $result->free(); $db->close(); ?>
I commented some wrong line in the code and i changed them, just follow it.
<?php
$serial=$_POST['key']; // change to $_POST['key'];
if(!$serial){
echo 'Please go back and enter the correct value';
exit;
}
$db = mysqli_connect('localhost','user_name','pass','demo_db'); // dont select your table in this line
mysqli_select_db($con,"tbldem"); // select your table here
if(mysqli_connect_errno()){
echo 'Connection lost.. please try again later !!';
exit;
}
$query = "select * from tbldem where serial LIKE '%$serial%';" ; // change $serial to serial like this line
$result = $db->query($query);
$num = $result->num_rows;
for($i=0;$i<$num;$i++){
$row = $result->fetch_assoc();
echo"<p>Serial : </p>";
echo $row['Index'];
echo"<p>Name : </p>";
echo $row['Name'];
echo "<p>Course : </p>";
echo $row['Course'];
}
$result->free();
$db->close();
?>
The only issue I see right off the top of my head is you wrote $POST['key']; when it should be $_POST['key']; don't forget the underscore. Visit the PHP manual to learn more, it also helps with debugging code.
On another note, for those hopefully learning from this question, it is good to point out that the code you are using to connect to the database is taking advantage of a work around that doesn't technically use the official Object Oriented method. This allows your PHP code to work in PHP versions prior to 5.2.9/5.3.0 when it was fixed. See the PHP manual for some great explanations on that.
Hope this helps.

Categories