This page shows the status of several chatrooms. A user can click a button to get them into the room of the person they choose. The nickname session of the person they select should be sent to the room through the form. The sessions are correct on this page, but when the values are submitted to the room, the nickname changes to the 1st nickname in the database, rather than the one I have passed to the page. How can I get the session to use the data it initially collected? (The page that receives the values only echos sessions, so I didn't post it)
<?php
session_start();
require_once('connect.php');
$con = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME) or die('Connection failed: ' . mysqli_connect_error());
$sql = mysqli_query($con, "SELECT UserType, NickName, Online, InChat FROM main_member WHERE UserType = 2 ORDER BY Online DESC");
while($row = mysqli_fetch_array($sql)){
$UserType = $row['UserType'];
$NickName = $row['NickName'];
$Online = $row['Online'];
$InChat = $row['InChat'];
$_SESSION['NickName_Session'] = $NickName;
echo '<table width="353" border="0">';
echo '<tbody>';
echo '<tr>';
echo '<td width="248" height="51">';
echo Status($Online,$InChat,$NickName);
echo '</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
}
function Status($Online,$InChat,$NickName){
if ($Online == 0) {
echo 'I am not online.';
}
elseif($Online == 1 && $InChat == 0){
echo 'I am online and I will be in my chatroom shortly.';
}
elseif($Online == 1 && $InChat == 1){
echo 'I am online.';
echo '<form name="get_nickname" id="get_nickname" action="script.php" method="POST">';
echo '<input type="hidden" name="nickname" id="nickname" value="' . $_SESSION['NickName_Session'] . '">';
echo '<input type="submit" name="submit" id="submit" value="Start Chat" />';
echo '</form>';
}
}
mysqli_close($con);
?>
this is the script page:
session_start();
if(!isset($_SESSION['file'])) {
$_SESSION['file'] = (rand(1000000, 9999999)) . round(10*microtime(TRUE));
}
if(isset($_POST['create'])) {
$_SESSION['file'] = (rand(1000000, 9999999)) . round(10*microtime(TRUE));
}
$url='chat_container.php';
Header("Location: $url");
exit();
and here is the chat container where I need the nickname:
session_start();
require_once('connect.php');
echo $_SESSION['NickName_Session'];
Related
i am dynamically adding the values in the dropdown . After selecting the value in the dropdown and entering text in the textbox, both textbox value and dropdown value has to be entered in the database on button click. But my code is not working properly ie only textbox value is inserted in the database but not dropdown selected vlaue. Please correct my code
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label style="margin-left:260px;width:170px"><h3 >Topic:</h3><br></label><br>
<select name="topic" style="margin-left: 282px;margin-top: -17px;">
<option value=""> -----Select----- </option>
<?php
$records = mysql_query("SELECT topic FROM topic ");
while ($row = mysql_fetch_array($records)){
echo "<option value=\"\">" . $row['topic'] . "</option>";
}
?>
</select>
<label style="margin-left:260px;width:170px"><h3 >Enter Crime Key Point:</h3><br></label><br>
<textarea name="details" id="details" rows="14" cols="60" style="margin-left:112px"><?php if(isset($_POST['details'])){echo htmlspecialchars($_POST['details']);}?>
</textarea><br><br>
<br><br><input type='submit' name='submit' value='Post' style='margin-left:305px;'>
</form>
if(isset($_POST["submit"]) ){
//if ( isset( $_POST['topic'] )){
//if(!empty($_POST['CarList'])){
$story = $_POST['details'];
$topic = $_POST['topic'];
echo $topic;
$sql = "SELECT `registered` FROM `user` WHERE `name`='{$_SESSION['name']}'";
$result = mysql_query($sql);
if (! $result)
{
throw new My_Db_Exception('Database error: ' . mysql_error());
}
else
{
$row = mysql_fetch_assoc($result);
$register=$row['registered'];
if ($register==1)
{
$sql = "INSERT INTO `stories`(`stories`,`name`,`topic`,`date/time`) VALUES ('$story','{$_SESSION['name']}','$topic',now())";
$result = mysql_query($sql);
echo $result;
if (! $result)
{
//echo "Story is not inserted. Please avoid special characters.";
echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error();
}
else
{
die("<script>location.href = 'usershome.php'</script>");
echo "Story inserted successfully";
}
}
else
{
$sql = "select count(*) from stories where `date/time`=DATE(NOW()) AND `name` = '{$_SESSION['name']}'";
$result = mysql_query($sql);
if (! $result)
{
throw new My_Db_Exception('Database error: ' . mysql_error());
}
else
{
$row = mysql_fetch_assoc($result);
$count=$row['count(*)'];
if ($count<3)
{
$sql = " INSERT INTO `stories`(`stories`,`name`,`date/time`) VALUES ('$story','{$_SESSION['name']}',now())";
$result = mysql_query($sql);
if (! $result)
{
echo "Story is not inserted";
}
else
{
die("<script>location.href = 'usershome.php'</script>");
echo "Story inserted successfully";
}
}
else
{
echo '<img src="images/animated-star-image-0009.gif" width="25px"/>Please Register to enter more than 3 stories per day';
}
}
}
}
}
?>
The line:
echo "<option value=\"\">" . $row['topic'] . "</option>";
change it to:
echo "<option value='".$row['topic']."'>" . $row['topic'] . "</option>";
You are passing empty values for the topic parameter. Setting up a correct value will ensure that you are inserting the correct user input in the database.
For future you can debug this easy by outputting your POST content before executing the SQLinsert.
That will fix your issue, but there are several other things you might consider changing, one of them is the deprecated mysql_ extension, switch to mysqli or PDO.
How do I refresh the table when I click EDIT NOW Button? or this is easier, how do I make refresh button to refresh the table? I have no knowledge on JSP to auto refresh. However, I manage to make an onchange event so when I choose menu, it will refresh upon changing. When I edit a data and submit, it does not refresh. How do I re-execute the echo of table? Thanks!
<?php
$selected='';
function get_options($select)
{
$conn = new mysqli('localhost', 'root', 'jared17', 'hbadb')
or die ('Cannot connect to db');
$result = $conn->query("select * from students");
$options='';
while ($row = $result->fetch_assoc())
{
$LRN = $row['LRN'];
$Last = $row['Last_Name'];
$First = $row['First_Name'];
if($LRN == $_GET['Students'])
{
$options.='<option value="'.$LRN.'" selected>'.$Last.', '.$First.'</option>';
}
else
{
$options.='<option value="'.$LRN.'">'.$Last.', '.$First.'</option>';
}
}
return $options;
}
if (isset($_GET['Students'])) {
$conn = new mysqli('localhost', 'root', 'jared17', 'hbadb')
or die ('Cannot connect to db');
$result = $conn->query("select * from students");
$lrn = $_GET['Students'];
$stmt = $conn->prepare("SELECT Last_Name, First_Name, Level, Q1, Q2, Q3, Q4, FINAL FROM english WHERE LRN = ?");
$stmt->bind_param('i', $lrn);
$stmt->execute();
$stmt->bind_result($last, $first, $level, $q1, $q2, $q3, $q4, $final);
$stmt->fetch();
echo "<table><tr><th>LRN</th><th>Name</th><th>Level</th><th>Q1</th><th>Q2</th><th>Q3</th><th>Q4</th><th>Final</th></tr>";
echo "<tr><td>$lrn</td><td>$last, $first</td><td>$level</td><td>$q1</td><td>$q2</td><td>$q3</td><td>$q4</td><td>$final</td></tr></table>";
}
echo "<html>";
echo "<body>";
echo "<form method=GET>";
echo "<select name=Students onchange=this.form.submit();>";
echo get_options();
echo "</select>";
echo "</form>";
echo "<form method=POST>";
///////////EDIT DATA
echo "Edit Data: ";
echo "<select name = 'Edit'>";
echo '<option value=Q1>Q1</option>';
echo '<option value=Q2>Q2</option>';
echo '<option value=Q3>Q3</option>';
echo '<option value=Q4>Q4</option>';
echo '<option value=FINAL>FINAL</option>';
echo '<input type="number" max="100" name="editdata" required>';
echo "</select>";
echo "<input type='submit' name='submit2' value='Edit Now'>";
if (isset($_POST['Edit'])) {
$conn2 = new mysqli('localhost', 'root', 'jared17', 'hbadb')
or die ('Cannot connect to db');
$upd = $_POST['Edit'];
$txt = $_POST['editdata'];
$now = "UPDATE english SET $upd='$txt' WHERE LRN='$lrn'";
$res = $conn2->query($now);
if (!$conn2->error) {
echo "Errormessage: $conn->error";
}
echo $now;
}
echo "</form>";
echo "</body>";
echo "</html>";
?>
I would use 2 pages view.php and edit.php. View would display the data with link to edit. When you click edit it would open edit.php to load the form to edit data and save it to db. Then issue the command
header("Location: view.php");
to reload the view.php and display the new data
I have uploaded the scripts I use as a basis for databases so you can see if this is what you want - feel free to amend any data it is just a test database. If you want more code just ask
www.cambodia.me.uk/php/view.php
Edited to include scripts as requested - sorry it is old code and mysql not mysqli
Connect script
<?php
/*
CONNECT-DB.PHP
Allows PHP to connect to your database
*/
// Database Variables (edit with your own server information)
$server = 'server';
$user = 'user';
$pass = 'pass';
$db = 'database';
// Connect to Database
$connection = mysql_connect($server, $user, $pass)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());
?>
View script
<?php
include('remote-connect.php');
$result = mysql_query("SELECT * FROM stats")
or die(mysql_error());
echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>date</th> <th>Home Team</th> <th></th><th></th><th>Away Team</th> <th></th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['date'] . '</td>';
echo '<td>' . $row['hometeam'] . '</td>';
echo '<td>' . $row['fthg'] . '</td>';
echo '<td>' . $row['ftag'] . '</td>';
echo '<td>' . $row['awayteam'] . '</td>';
echo '<td>Edit</td>';
//echo '<td>Delete</td>';
echo "</tr>";
}
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
Edit script
<!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>
<?php
function renderForm($id, $hometeam, $awayteam, $error)
{
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>First Name: *</strong> <input type="text" name="hometeam" value="<?php echo $hometeam; ?>"/><br/>
<strong>Last Name: *</strong> <input type="text" name="awayteam" value="<?php echo $awayteam; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
include('remote-connect.php');
if (isset($_POST['submit']))
{
if (is_numeric($_POST['id']))
{
$id = $_POST['id'];
$hometeam = mysql_real_escape_string(htmlspecialchars($_POST['hometeam']));
$awayteam = mysql_real_escape_string(htmlspecialchars($_POST['awayteam']));
if ($hometeam == '' || $awayteam == '')
{
$error = 'ERROR: Please complete all mandatory fields!';
renderForm($id, $hometeam, $awayteam, $error);
}
else
{
mysql_query("UPDATE stats SET hometeam='$hometeam', awayteam='$awayteam' WHERE id='$id'")
or die(mysql_error());
// Go back to view page and redisplay the edited data
header("Location: view.php");
}
}
else
{
echo 'Error!';
}
}
else
{
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM stats WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$hometeam = $row['hometeam'];
$awayteam = $row['awayteam'];
renderForm($id, $hometeam, $awayteam, '');
}
else
{
echo "No results!";
}
}
else
{
echo 'Error!';
}
}
?>
</body>
</html>
It's so easy. If you fetch your table's values after edit or delete operation, sql will bring fresh data.
I am trying to get the user to pick from the dropdown menu. When the user clicks on the selected item they will click a button and show the results.
I haven't been able to display the information onto the page.
$sql = "select * from Owner";
echo'<form action="index1.php" method="post">';
echo '<select name="bid" id="bid">';
foreach($conn->query($sql) as $row) {
echo '<option value=" ';
echo $row["id"];
echo ' ">';
echo $row['LastName'];
echo '</option>';
}
echo'</select>';
echo'<br><input type="submit" value="Show Info"><br>';
echo'</form>';
//check if submit button has been clicked
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['bid'];
try{
$sql = "select Owner.FirstName, Owner.LastName,MarinaSlip.BoatName from Owner, MarinaSlip where Owner.OwnerNum = MarinaSlip.OwnerNum
and Owner.FirstName = $id";
foreach($coon->query($sql) as $row){
echo$row['FirstName'].' '.$row['LastName'].' '.$row['BoatName'].'<br>';
}
}//end of try
catch(PDOExeption $e){
echo "Error: ".$e -> getMessage();
}
}
I'm trying to use HTML, PHP and MYSQL to pull data from a database and display it in a form (to later be edited). At this point I'm only trying to pull that data and display it in a form. (I'll worry about updating later). I pull the data but nothing displays in my textboxes:
<?php
$con = mysqli_connect("XXXXX"); //removed for privacy
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query="select * from VOLUNTEER";
echo '$query';
$result = mysqli_query($con, $query);
echo "<table>";
if ($result)
{
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo '<form method = "post" action="insertvolunteer.php">';
echo '<tr>';
echo '<td>First Name:</td>';
echo '<td>' . '<input type=text name=FirstName' . $row["FirstName"] . '</td>';
echo '<td>' . '<input type=hidden name=VolunteerId' . $row["VolunteerId"] . '</td>';
echo '</tr>';
}
}
echo "</form>";
echo "</table>";
mysqli_close($con);
?>
Text box data needs to be displayed on value as
echo '<td><input type="text" name="FirstName" value="'.$row["FirstName"].'"></td>';
connect.php
<?php
$server = "server";
$user = "user";
$password = "password";
$bd = "yourbd";
$connect = mysql_connect($server, $user, $password);
$connect = mysql_select_db("$bd", $connect);
if (!$connect){
echo mysql_error(); exit;
}
?>
namefile.php
<?php
include('connect.php');
$select = mysql_query("select * from VOLUNTEER");
while ($show = mysql_fetch_assoc($select)):
echo "<table>";
echo "<form method = 'post' action='insertvolunteer.php'>";
echo '<tr>';
echo '<td>First Name:</td>';
echo '<td><input type="text" name="FirstName" value="'.$show["FirstName"].'"></td>';
echo '<td><input type="text" name="FirstName" value="'.$show["VolunteerId"].'"></td>';
echo '</tr>';
echo "</form";
echo "</table>";
endwhile;
?>
When you create an MySQL query, you need to declare this. How?
$var = "SELECT * FROM SOMEWHERE"; wrong
$var = mysql_query("SELECT * FROM SOMEWHERE"); right
'n in echo '<td>' . '<input type=text name=FirstName' . $row["FirstName"] . '</td>';, you need to close the tag. And also have no need of separate <td> of <input>.
Try something like :)
#update I realized that you've got what was wished. Cheers.
I've created two php files with code for an order form for a cafeteria and the correspronding lines of code for inserting the posted values in my database. Here I present them.
CODE FOR addorder_form.php
**<?php
db_connect();
$cats=array("Kafedes", "Rofhmata", "Pota", "Snack/Glyka");
$arrlength=count($cats);
for($i=0;$i<$arrlength;$i++) {
$sql = mysql_query('SELECT title FROM products WHERE cname="'.$cats[$i].'"') or die(mysql_error());
echo '<div id="main_content">';
echo "<h4 style=color:#800000> ".$cats[$i]."</h4>";
echo "<br />";
while($row = mysql_fetch_array($sql, MYSQL_BOTH)){
echo "<div id='center' style='align:center'>";
echo "<input style='text-align:right;' type='checkbox' action='addorder.php' name='products[]' value='".$row["title"]."'>".$row["title"];
echo '</div>';
echo ' <div id="center_side" style="float:right"><form "method="post" action="addorder.php"><input type="text" size="4" padding-left="0.2em" name="quantity"/>';
echo '</div>';
echo '</div>';
echo '<br />';
}
}
echo '<form name="addorder" method="" action="addorder.php" onclick="addorder.php">';
echo '<input type="submit" value="Add order" style="float: right;"><br/>';
echo '</form>';
?>**
CODE FOR addorder.php
**<?php
include_once("buzzcafe_fns.php");
do_html_header("");
$quantity = '';
$title = '';
if (isset($_POST['quantity']) && isset($_POST['products'])) {
if(isset($_POST["Submit"])) {
$quantity = $_POST['quantity'];
$title = $_POST['products'];
if($_POST["Submit"] == "Submit")
{
for ($i=0; $i<sizeof($title); $i++) {
db_connect();
$insertOrder = mysql_query("INSERT INTO orders VALUES('".$title[i]."','".$quantity."')")or die(mysql_error());
}
echo "Record inserted";
}
}
}
?>**
When I run them I have non any syntax errors, though it does not work. As far as the db_connect() is set in the buzzcafe_fns.php file I've included and it is checked that works properly. How can I make my "INSERT INTO" work?
You can use another insert query
First You will check if $title variable array or not.
Next Using For loop
<?php
$con=mysql_connect("localhost","root","");
$db=mysql_select_db("yourdatabasename here" ,$con);
$count=count($title);
for($i=0;$i<$count;$i++){
mysql_query("INSERT INTO orders SET title='".$title[$i]."', quantity='".$quantity."'");
}
?>