I have a very simple chat system I've built using PHP and MySQL (this is my second day ever using these languages) and I am wondering if there is any way to auto refresh the table data I'm pulling from my database and loading into an html table via PHP without having something like Javascript go and reload the whole web page... just reloading the html table with the data in it that PHP filled it up with.... Does that make sense?
Here is my code if it helps (for /chat.php)
<html><head></head><body><center>
<form action="chat.php" method="post">
Message: <br><textarea type="text" name="message" style="width:80%; height:300px;"></textarea><br>
<input type="submit" name="submitButton"/> <button name="Refresh Chat">Refresh Chat</button>
</form>
<div style="width:100%;">
<?php
$host="****";
$user="****";
$password="****";
$cxn = mysql_pconnect ($host, $user, $password);
mysql_select_db("defaultdb", $cxn);
if (getenv(HTTP_X_FORWARDED_FOR)) {
$ipaddress = getenv(HTTP_X_FORWARDED_FOR);
} else {
$ipaddress = getenv(REMOTE_ADDR);
}
$message = nl2br(strip_tags(nl2br($_POST["message"])));
if (isset($_POST['submitButton'])) {
if ($message != "") {
mysql_query("INSERT INTO ChatTest (ID, TimeStamp, Message) VALUES ('$ipaddress', NOW(), '$message')");
}
header('Location: chat.php');
}
$message = "";
$data = mysql_query("SELECT * FROM ChatTest ORDER BY TimeStamp DESC") or die(mysql_error());
Print "<table border cellpadding=3 width='100%' style='table-layout:fixed'>
";
Print "<tr>";
Print "<th style='width:10%;'>ID:</th><th style='width:10%;'>TimeStamp:</th><th style='width:70%;'>Message:</th>";
while($info = mysql_fetch_array( $data )) {
Print "
<tr>";
Print " <td>".$info['ID'] . "</td> ";
Print " <td>".$info['TimeStamp'] . " </td>";
Print " <td style='white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word'>".$info['Message'] . "</td></tr>
";
}
Print "</table>";
mysql_close($cxn);
?>
</div></center></body></html>
The technique is called AJAX and one of the easiest libraries to add to the project would be jQuery. I assume your issue isn't with JavaScript, but with the idea of reloading the entire page.
UPDATE
Because I'm such a nice guy ;) This should work, more or less, I haven't tried it out, so there might be a typo or two:
<?php
$host="****";
$user="****";
$password="****";
$cxn = mysql_pconnect ($host, $user, $password);
mysql_select_db("defaultdb", $cxn);
if (getenv(HTTP_X_FORWARDED_FOR)) {
$ipaddress = getenv(HTTP_X_FORWARDED_FOR);
} else {
$ipaddress = getenv(REMOTE_ADDR);
}
$message = nl2br(strip_tags(nl2br($_POST["message"])));
if (isset($_POST['submitButton'])) {
if ($message != "") {
mysql_query("INSERT INTO ChatTest (ID, TimeStamp, Message) VALUES ('$ipaddress', NOW(), '$message')");
}
header('Location: chat.php');
}
$message = "";
$data = mysql_query("SELECT * FROM ChatTest ORDER BY TimeStamp DESC") or die(mysql_error());
$tbl = '';
$tbl .= "<table border cellpadding=3 width='100%' style='table-layout:fixed'>
";
$tbl .= "<tr>";
$tbl .= "<th style='width:10%;'>ID:</th><th style='width:10%;'>TimeStamp:</th><th style='width:70%;'>Message:</th>";
while($info = mysql_fetch_array( $data )) {
$tbl .= "
<tr>";
$tbl .= " <td>".$info['ID'] . "</td> ";
$tbl .= " <td>".$info['TimeStamp'] . " </td>";
$tbl .= " <td style='white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word'>".$info['Message'] . "</td></tr>
";
}
$tbl .= "</table>";
mysql_close($cxn);
if (isset ($_GET['update']))
{
echo $tbl;
die ();
}
?>
<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
</head><body><center>
<form action="chat.php" method="post">
Message: <br><textarea type="text" name="message" style="width:80%; height:300px;"></textarea><br>
<input type="submit" name="submitButton"/> <button name="Refresh Chat">Refresh Chat</button>
</form>
<div id="messages" style="width:100%;">
<?php echo $tbl; ?>
</div></center>
<script type="text/javascript">
$(document).ready (function () {
var updater = setTimeout (function () {
$('div#messages').load ('chat.php', 'update=true');
}, 1000);
});
</script>
</body></html>
As for coding techniques, you might want to look into SQL-injections and maybe writing cleaner HTML, but I'm sure you'll get there :)
the only way you would do it without javascript is to use an iframe for the chat interface, and a meta refresh.
but why not use javascript?
Related
I got another problem with my Code.
I generate a dynamic table from SQL-content and use textfields in the table to, maybe someday, change the content.
The problems is, I cann't access the textfields from outside the whileloop to save the content, all I get is Undefined index error for every field.
<form method="POST" enctype="text/html">
<?php
require_once ('config.php');
$sql = " SELECT * FROM kassen ORDER BY name ASC ";
$db_erg = mysql_query( $sql );
echo "<tr>";
echo "<td>";
echo '<table border="1" width="80%" align="center">';
echo "<tr> <th>Name</th><th>Stand</th><th>Verbrauch</th><th>Einzahlungen</th></tr>";
while ($zeile = mysql_fetch_assoc($db_erg))
{
echo '<tr>';
echo '<td>'. $zeile['name'] . '</td>';
echo '<td><center>'. $zeile['bier_stand'] . '€</td>';
echo '<td>';
/* in the text below, i set the name to verbrauch"'.$zeile['id'] and
ergebnis"'.$zeile['id'] which should generate a new unique name for every
single text*/
echo '<center><input type="text" name="verbrauch"'.$zeile['id'].' value="0" size="10" />';
echo '</td>';
echo '<td>';
echo '<center><input type="text" name="einzahlung"'.$zeile['id'].' value="0" size="10" />';
echo '</td>';
echo '</tr>';
} echo '</table>';
?>
<center><input type="hidden" name="aktion" value="speichern" />
<center><input type="Submit" name="" value="speichern"/>
</form>
<?php
if (isset ($_POST['aktion']))
{
if ($_POST['aktion'] == "speichern" )
{
require_once ('config.php');
$sql = " SELECT * FROM kassen ORDER BY name ASC ";
$db_erg = mysql_query( $sql );
while ($zeile = mysql_fetch_assoc($db_erg))
{
$standalt = $zeile["bier_stand"];
/* now I try to put the value of the text to the DB, but all i get is
Undefined Index error */
$verbrauch = $_POST['verbrauch'.$zeile['id']];
$einzahlung = $_POST['einzahlung'.$zeile['id']];
$stand = $zeile["bier_stand"] - $verbrauch + $einzahlung;
$id = $zeile["id"];
$sql = "UPDATE kassen SET ";
$sql .= " bier_stand_alt = '$standalt', ";
$sql .= " bier_stand = '$stand', ";
$sql .= " bier_verbrauch = '$verbrauch', ";
$sql .= " bier_einzahlungen = '$einzahlung' ";
$sql .= " WHERE id='$id'";
}
echo '<h2>Änderungen übernommen</h2>';
echo 'zurück zur Bierkasse';
exit;
}
}
?>
Any idea what I'm messing up?
Sorry for questioning,
realy stupid mistake
echo '<center><input type="text" name="einzahlung"'.$zeile['id'].' value="0" size="10" />';
should have been
echo '<center><input type="text" name="einzahlung'.$zeile['id'].'" value="0" size="10" />';
so actually just the " was in wrong place ... stupid stuff that happens at 3am
I`m trying to parse date in PHP. I copy part of several examples but it is not working.
What I am trying to do is :
I have a PHP file that receives a variable 'parttype' and runs a query.
<?php
$parttype = $_POST['parttype'];
echo "$parttype";
$conn = mysqli_connect("127.0.0.1", "root", "") or die ("No connection");
mysqli_select_db($conn , "shop") or die ("db will not open");
$query = "SELECT * from parts where parttype='$parttype'";
$result = mysqli_query($conn, $query) or die("Invalid query");
echo '<table border="1" align ="center"><tr><th>Id</th><th>Name</th><th>Price</th><th>InStock</th><th>Description</th><th>SUpplier</th><th>Quantity</th><th>Remove</th></tr>';
while($row = mysqli_fetch_array($result))
{
echo "<tr><form action='ppcomppartout.php' method='post'><td><input type='hidden' name='partid' value='$row[0]'>" . $row[0] . "</td><td>" . $row[1] . "</td><td>" . $row[2] . "</td><td>" . $row[3] . "</td><td>" . $row[5] . "</td><td>" . $row[6] . "</td>
<td><input type='text' name='qtty' placeholder='0'></td><td>Buy <input type='submit'></td>
</form></tr>";
}
echo "</table>";
mysqli_close($conn);
?>
Then in the index.php I have a function get() that posts the variable to data.php
and another function that is not working - function parse(data). I eventually insert a button to get some results, but I wanted the results to come up as soon as I change the values on the select box.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
function get() {
$.post("data.php", {parttype: form.parttype.value },
function(output) {
$("#output").html(output).show();
});
}
function parse(data){
$('#output').append('<select>');
$("select").on("change", function(evt)
{
line_record( $("select option:selected").index(),data)
});
}
</script>
</head>
<body>
<form name="form">
<select name="parttype" style="width: 117px">
<?php
$con = mysqli_connect("127.0.0.1", "root", "") or die ("No connection");
mysqli_select_db($con , "shop") or die ("db will not open");
$query = "SELECT distinct parttype from parts";
$result = mysqli_query($con, $query) or die("Invalid query");
while($rows = mysqli_fetch_array($result)) {
echo "<option value=\"" . $rows[0] . "\">" . $rows[0] . " </option>";
}
echo "</select>";
mysqli_close($con);
?>
</select>
<!--<input type="submit" value="OK!!"/>-->
</form>
<!--<input type="text" name="parttype">-->
<!--<input type="button" value="Get" onClick="get();" >-->
<input type="submit" value="Get" onClick="get();" >
</form>
<div id="output"></div>
</body>
</html>
Can some one help with this?? What I am doing wrong ??
You don't specify what the problem is exactly, but you should take it step by step.
The first problem you will encounter is probably when you call your get() function on page load. The data you are sending to your php script is:
{parttype: form.parttype.value }
where form.parttype.value seems to be undefined. If you want to send the values of your form, you can change that to:
$("form").serialize()
You should also check your html source as there seem to be multiple closing form tags.
Note: You are dumping your $_POST variable in your sql query without any validation or escaping. You should really switch to prepared statements as your code is vulnerable to sql injection.
This has been bugging me for 3 days now.. I'm new to this and trying to get my head round something. I have a form which involves 3 fields. Firstname, Surname, Marks. I have used a while loop to generate the table from a mysql table. I have used a text box and used the loop to call the text box after the 'ID' so each text box is named uniquely. I am then using a post method to send values to a second page which will update the 'marks' column with the value the user has just put in.. this is where I am finding my problem!
This is the initial page.
<html>
<head><title>Please Enter Your Surname</title></head>
<body>
<center>
<h2><font color=blue>Please Enter Your Surname</font></h2><p>
<form action="insert.php" method="POST">
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("session6",$db)or do_error("Could not connect to the database");
$result = mysql_query("SELECT * FROM members ORDER BY id",$db);
$rows=mysql_num_rows($result);
if(!$rows)
{
do_error("No results found");
}
else
{
echo "<table border=3 cellspacing=1 cellpadding=1
align=center bgcolor=lightblue>\n";
echo "<caption><h2><font color=blue> Members Details
</font></h2></caption>\n";
echo "<tr><th>Member Id</th><th>Firstname</th><th>Mark</th></tr>\n";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td strong>" . $row['Id'] . "</td>";
echo "<td strong>" . $row['Firstname'] . "</td>";?>
<td strong><input type="text" name="<?php echo $row['Id']; ?>" size="20"></td>
<tr>
<?php
}
?><input type="hidden" name="no_of_rows" value="<?php echo $rows; ?>">
<?php
echo "</table>\n";
}
mysql_close($db) or do_error("Could not close connection");
function do_error($error)
{
echo $error;
die();
}
?>
<input type="submit" value="Search">
<input type="reset" value="Reset">
</form>
</body></html>
`
Then the update is done here which is where I seem to be having a problem:
<html>
<body>
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("marks",$db)or do_error("Could not connect to the database");
$i=1;
while ($i <= $_POST["no_of_rows"])// or $_POST["No_of_Rows"] from form
{
$insertsql = "UPDATE members SET mark = " . $_POST[$i] . " WHERE Id = " . $row['Id'] . ";";
echo $_POST['$i'];
$i++;
}
?>
</body></html>
When I echo $_POST[$i'] it shows the correct values but does not update the DB, and I'm not about ready to throw my laptop in the bin! ha! I know it is prob going to be something stupid I just can't see what, so any help would be appreciated.
You're missing the single quotes in your update query. This would help:
$insertsql = "UPDATE `members` SET `mark` = '" . $_POST[$i] . "' WHERE `Id` = '" . $row['Id'] . "' ;";
you are also not running the mysql_query query command for the update
lastly you are using the mysql php commands which are deprecated. Use mysqli or pdo instead. and don't forget to escape data in your queries to prevent sql injections
Problem is the single quotes here, forcing to literal '$i' which probably isnt a key in $_POST
echo $_POST["$i"];
No need to use quotes when variable is used:
$_POST[$id];
Im a newbie in PHP and I want to create a simple webpage app for my website, I was able to produce this page base on a tutorial here.
<?php
$con = mysql_connect("localhost","*****","*****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*****", $con);
$result = mysql_query("SELECT * FROM products");
echo "<table border='1'>
<tr>
<th>Name</th>
<th>classification</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['classification'] . "</td>";
echo "<td><input type='checkbox' name='{number[]}' value='{$row['prodID']}' /></td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
<?php
?>
<html>
<head>
</head>
<form name="form1" method="post" action="result_page.php">
<input type="submit" name="Submit" value="Submit">
</p>
</form>
<body>
</body>
</html>
but my problem is how to create a result_page.php to show the selected entries or data base on the selected checkbox so i can create a comparison page. I have this as being my result_page.php but nothing is showing up. I know Im doing something wrong but I cant find out.
<?php
error_reporting(E_ALL);
$host = 'localhost';
$user = '******';
$pass = '******';
$dbname = '******';
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
mysql_select_db($dbname);
$sql = "SELECT * FROM products WHERE prodID IN (";
foreach ($_POST['number'] as $product) $sql .= "'" . $product . "',";
$sql = substr($sql,0,-1) . ")";
$result = mysql_query($sql);
while ($myrow = mysql_fetch_array($result))
{
echo "<table border=1>\n";
echo "<tr><td>Name</td><td>Position</td></tr>\n";
do {
printf("<tr><td>%s %s</td><td>%s</tr>\n", $myrow["1"], $myrow["2"], $myrow["3"]);
} while ($myrow = mysql_fetch_array($result));
echo "</table>\n";
}
?>
A quick glance, the section that generates the output is not correct. You have looped two times for no apperant reason.
while ($myrow = mysql_fetch_array($result)) //<========remove this line
{ //<========remove this line
echo "<table border=1>\n";
echo "<tr><td>Name</td><td>Position</td></tr>\n";
do {
printf("<tr><td>%s %s</td><td>%s</tr>\n", $myrow["1"], $myrow["2"], $myrow["3"]);
} while ($myrow = mysql_fetch_array($result));
echo "</table>\n";
} //<========remove this line
This is done by human parse, but should serves as a starting point.
And to recap tadman, no this is not a good tutorial. And normally you won't need to do printf for the output.
I am creating an insert process in php but I have a problem in my code. when I refresh my page, it will also submit and insert the data.
here is my code :
<form action="/drupal/node/1" method="post">
Name: <input type="text" name="name" />
Price: <input type="text" name="price" />
Minutes: <input type="text" name="minutes" />
<input type="submit" />
</form>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_select_db("zain", $con);
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['minutes']))
{
$val_name = $_POST['name'];
$val_price = $_POST['price'];
$val_min = $_POST['minutes'];
$max_id_sql = mysql_query("SELECT MAX(id) FROM card_category");
$data = mysql_fetch_array($max_id_sql);
if ($data[0]==0)
{
$val_id = 1;
}
else
{
$val_id = $data[0] + 1;
}
mysql_query("INSERT INTO card_category (id, name, price, minutes) VALUES ($val_id,'$val_name',$val_price,$val_min )");
$_POST['name'] == NULL;
$_POST['price'] == NULL;
$_POST['minutes'] == NULL;
}
$result = mysql_query("SELECT * FROM card_category");
echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
<th>mins</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['minutes'] . "</td>";
echo "</tr>";
}
echo "</table>";
if (isset($_POST['lastname']))
{
print $_POST['lastname'];
}
mysql_close($con);
?>
my question is, how can I handle when I refresh the page and it will not submit the data?
thanks in advance
When you get the POST submission:
Process the data
Return a Redirect response
Get a GET request from the browser on the URL you redirect to
Respond to that with the HTML
If the browser is refreshed, it will resubmit the GET request which your PHP won't use to modify the database.
This is the POST-REDIRECT-GET pattern. There are some more details in this blog entry (which also has example PHP code in the comments).
How to fix refresh the page do not post the value using php:
if ($_SERVER['HTTP_CACHE_CONTROL']=="")
{
// process the data
}
If you look at $_SERVER['REQUEST_METHOD'] variable, it will say 'POST' when the user submitted data and 'GET' when he did not. So:
if($_SERVER['REQUEST_METHOD']=='POST')
{
// process the data
}
By the way, your code is eminently vulnerable to SQLI attacks ...