Data in database is entered only for the first time - php

Iam trying to create a private messaging system in which user sends message to another user and that content is inserted into database..Iam using a random number called hash to identify a conversation between two people..table for that is "message_group" and table for saving messages is "messages"..here comes the problem..
When I type something in text area and click on sendmessage button it inserts the data into the messages database..But if type something again and try to send it , the data wont enter into database..coz of this the other person is getting only first message..Please help me solving this problem..here's the code
<html>
<head>
<title>new convo</title>
</head>
<body>
<?php include 'connect.php';?>
<?php include 'message_title_bar.php';?>
<?php include 'functions.php';?>
<div>
<?php
if(isset($_GET['user']) && !empty($_GET['user'])){
?>
<form method='post'>
<?php
if(isset($_POST['message']) && !empty($_POST['message'])){
$my_id=$_SESSION['user_id'];
$user=$_GET['user'];
$random_number=rand();
$message=$_POST['message'];
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_string = "SELECT `hash` FROM `message_group` WHERE (`user_one`='$my_id' AND `user_two`='$user') OR (`user_one`='$user' AND `user_two`='$my_id')";
$check_con=mysqli_query($connect,$query_string) or die(mysqli_error($connect));
if(mysqli_num_rows($check_con)==1){
echo "<p>Conversation already Started</p>";
}else{
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($connect,"INSERT INTO message_group VALUES('$my_id' , '$user' , '$random_number')");
mysqli_query($connect,"INSERT INTO messages VALUES ('','$random_number','$my_id','$message')");
echo "<p>Conversation started</p>";
}
}
?>
Enter message:<br />
<textarea name='message' rows='7' cols='60'></textarea>
<br />
<br />
<input type='submit' name="submit" value="sendmessage" />
</form>
<?php
}
else{
echo "<b>Select User</b>";
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
$user_list=mysqli_query($connect,"SELECT `id`,`username` FROM `users`");
while($run_user=mysqli_fetch_array($user_list)){
$user = $run_user['id'];
$username = $run_user['username'];
echo "<p><a href='send.php?user=$user'>$username</a></p>";
}
}
?>
</div>
</body>
</html>
Any help is appreciated.

<html><head><title>new convo</title></head><body>
<?php include 'connect.php'; ?>
<?php include 'message_title_bar.php'; ?>
<?php include 'functions.php'; ?>
<?php $connect = mysqli_connect('localhost', 'root', '', 'php_mysql_login_system'); if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error(); ?>
<div>
<?php
if (isset($_GET['user']) && !empty($_GET['user'])) {
?>
<form method='post'>
<?php
if (isset($_POST['message']) && !empty($_POST['message'])) {
$my_id = $_SESSION['user_id'];
$user = $_GET['user'];
$message = $_POST['message'];
$query_string = "SELECT `hash` FROM `message_group` WHERE (`user_one`='$my_id' AND `user_two`='$user') OR (`user_one`='$user' AND `user_two`='$my_id')";
$check_con = mysqli_query($connect, $query_string);
if (mysqli_num_rows($check_con)) {
$f_array = mysqli_fetch_array($check_con);
$hash = $f_array['hash'];
echo "<p>Conversation already Started</p>";
} else {
$hash = rand();
mysqli_query($connect, "INSERT INTO message_group VALUES('$my_id' , '$user' , '$hash')");
echo "<p>Conversation started</p>";
}
mysqli_query($connect, "INSERT INTO messages VALUES ('', '$hash', '$my_id', '$message')");
}
?>
<label for="message">Enter message:</label>
<textarea name='message' id="message" rows='7' cols='60'></textarea>
<br/>
<br/>
<input type='submit' name="submit" value="sendmessage"/>
</form>
<?php
} else {
echo "<b>Select User</b>";
$user_list = mysqli_query($connect, "SELECT `id`,`username` FROM `users`");
while ($run_user = mysqli_fetch_array($user_list)) {
$user = $run_user['id'];
$username = $run_user['username'];
echo "<p><a href='send.php?user=$user'>$username</a></p>";
}
}
?>
</div>
</body>
</html>

There are many mistakes in code brother read basic first... and you are not using echo function to print old chat.
Just echo old chat. before post function.
steps:
1. Check if users already chatting.
2. If they are chatting echo chat which they already chatted.
3. If not chatting then start new chat.
4. if they are not chatting you dont need to echo anything just echo new message.
Your present code will just show you last message i think. because your page getting reload. and after it loads its just printing your last message in my view.. you need to print old chat as well.

Related

How to reset every variable in PHP?

I am currently creating a quiz using PHP, HTML and mySQL for simply practice. However, I keep running into a problem where, the question displayed is different to the actual question linked to the answer. So where the user is correct, the answer is wrong.
Here is what I have for the question page:
<?php
session_start();
session_unset();
$link = mysqli_connect("xxxx","xxxx","xxxx", "xxxx");
if(mysqli_connect_error()) {
echo "There was an error connecting to the database!";
}else{
$qNo = rand(1,2);
$query = "SELECT * FROM questions WHERE questionID = '".$qNo."'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$answer = $row[2];
$question = $row[1];
if(isset($_POST['submit'])){
$_SESSION['question'] = $row[1];
$_SESSION['answer'] = $answer;
$_SESSION['userAnswer'] = $_POST['userAnswer'];
header("Location: process.php");
}
}
?>
<html>
<head>
<title>Quiz v2</title>
</head>
<body>
<h1>Welcome to Quiz!</h1>
<div>
<p><a><?php print_r($question);?></a></p>
<form method="post">
<label for="answer">Answer: </label><input name="userAnswer">
<button name="submit">Answer</button>
</form>
</div>
</body>
</html>
This is what I have for the process page:
<?php
session_start();
$link = mysqli_connect("xxx","xxxx","xxxx", "xxxx");
if(mysqli_connect_error()) {
echo "There was an error connecting to the database!";
}else{
echo $_SESSION['userAnswer'];
echo $_SESSION['answer'];
echo $_SESSION['question'];
if($_SESSION['userAnswer']==$_SESSION['answer']){
}
}
?>
Over here you can see the question displayed is:
enter image description here
But this is what is actually being asked and compared:
enter image description here

log in with session does not work

I have this script sign in first with sql insert into query and redirected to login page. I checked all my queries on phpmyadmin. All queries are working. I do not have any error message in my query. Also it is suppose to show " password/username does not match" message if there is incorrect user/password. After i submit form, the page did not redirect to welcome page and form field clears.
this is my login page
<?php
require_once "./include/variables.inc.php";
$debug =0;
$error_text = "";
$uname = "";
$pwd = "";
session_start();
if (!isset($_SESSION['member_id'])){
if(isset($_POST["submit"])) {
if($debug) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
//die("temp stop point");
}//end ofdebug if
$uname = mysqli_real_escape_string($dbc,trim($_POST['uname']));
$pwd = mysqli_real_escape_string($dbc,trim($_POST['pwd']));
if (!empty($uname) && !empty($pwd)) {
$query = "SELECT * FROM employees WHERE username = '".$uname."'
AND password = '".MD5($pwd)."'";
echo $query;
$result = mysqli_query($dbc,$query) or die ("Error in query". mysql_error());
if(mysqli_num_rows($result)) {
$row = mysqli_fetch_assoc($result);
$_SESSION['member_id'] = $row['member_id'];
$_SESSION['member_name'] = $row['member_name'];
header('Location:index.php');
}
else {
$error_text .= "The username/password are incorrect. Please enter correct username and password.";
}
}
}//end of if(isset($_POST["submit"])
}
require_once('./include/html.head.php');
?>
<body>
<div id="wrapper">
<?php require_once('./include/header.php'); ?>
<div id="side">
<?php require_once('./include/pb.side.php'); ?>
</div>
<div id="content">
<div class="form">
<p class="strong">All Santa helpers log-in here.</p>
<?= $error_text ?>
<form method="post" action="<?= $_SERVER['PHP_SELF'] ?>" enctype="multipart/form-data">
<p>User Name: <input name="uname" type="text" value="<?= $uname ?>"></p>
<p>Password: <input name="pwd" type="password"></p>
<input name="submit" type="submit" value="Login">
</form>
</div>
<div class="rdeer">
<img src="images/login_img.png" alt="Rain Deer">
</div>
</div>
<?php require_once('./include/footer.php'); ?>
</div>
</body>
</html>
and function php is
<?php
function user_authenticated($username, $password) {
if(!empty($username) && !empty($password)) {
$query = "SELECT userName, password FROM employees WHERE userName = '".$username."' and password = '".$password."'";
$result= mysqli_query($dbc, $query)
or die ("Query does not work." . mysql_error());
// If result matched $username and $password, table row must be 1 row
} else {
echo "Query error. ";
}
}
Notice the line mysqli_num_rows($result). Replace it with mysqli_num_rows($result)>0 since that function returns an int.

html text form with php isn't inserting into MySQL server

I am writing code that produces a <textarea> for a user to input something but it isn't giving me any output besides "please include some content" which is what it means to do if there is nothing in the box. This appears even if there is content in the <textarea> and won't even say "post fail" which is what it is meant to do if it can't insert into the database.
I am asking if anybody can see if there is something I have neglected to include, or if there is something that is wrong with my code.
<?php
session_start();
require('connect.php');
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
?>
<html>
<link rel="stylesheet" type="text/css" href="styles.css" />
<head>
<title> Welcome to faecesbook</title>
</head>
<?php include('header.php'); ?>
<form action="post.php" method="POST">
<br / >
<br / >
<br / >
<br / >
<center>
<br/>
<br/>
Type your post here:<br/>(160CharLimit)<br/>
<textarea style="resize: none; width: 800px; height: 100px;" name="con" maxlength="160">
</textarea>
<br />
<input type="submit" name="submit" value="Post" style="width: 800px;" >
</center>
</form>
<body>
</body>
</html>
<?php
$content = #$_POST['con'];
$post_date = date("d-m-y");
if(isset($_POST['submit'])){
if($content){
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
Try this code. It should work.
<?php
session_start();
require('connect.php');
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
?>
<html>
<link rel="stylesheet" type="text/css" href="styles.css" />
<head>
<title> Welcome to faecesbook</title>
</head>
<?php include('header.php'); ?>
<form action="post.php" method="POST">
<br / >
<br / >
<br / >
<br / >
<center>
<br/>
<br/>
Type your post here:<br/>(160CharLimit)<br/>
<textarea style="resize: none; width: 800px; height: 100px;" name="con" maxlength="160">
</textarea>
<br />
<input type="submit" name="submit" value="Post" style="width: 800px;" >
</center>
</form>
<body>
</body>
</html>
<?php
$post_date = date("d-m-y");
if(isset($_POST['submit'])){
if(isset($_POST['con']) && $_POST['con'] != ''){
$content = #$_POST['con'];
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
You have a missing braces in your code
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
Should read
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
}
And
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") ) // <--- here
echo "post successful";
}else{
echo "post fail";
}
Making it readable also helps reduce errors
$query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')");
if ($query){
echo "post successful";
}else{
echo "post fail";
}
I see your code sends submited data to another page, i checked it through print_r($_POST)
I changed <form action="post.php" method="POST"> to <form action="" method="POST"> and tried and it was working, in case if the code you submited here is not "post.php" do this.
So it means someting is wrong with your insert query. So try this PDO way of inserting data.I thought of suggesting you the following easy pdo insert
$dbhost = "localhost";
$dbname = "mydatabase";
$dbusername = "root";
$dbpassword = "mypppasss";
//connection string
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbusername,$dbpassword);
Inside the if($content) put the following code and try
$statement = $link->prepare("INSERT INTO post(userID,post_date,postContent)
VALUES(:inp1,:inp2,:inp3,:inp4)");
$statement->execute(array(
inp1=>$_SESSION["userID"],
inp2=>$post_date,
inp4=>$content
));
EDITED
Add this code to the form submitted page to see the posted data for debugging.
if($_POST){
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
EDITED
Note:# is used to hide errors, prevent it from displaying error
messages. that doesn't mean there is no error. Remove # for debugging
EDITED
Change your whole insert query part to this and try
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO post(userID,post_date,in_reply_to,postContent)
VALUES (".$_SESSION['userID'].",".$post_date.",'',".$content.")";
if (mysqli_query($conn, $sql)) {
echo "inserted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
This is what was wrong.
i had two set of <?php ?>, the first one in the code included require('connect.php'); within it, and the second one required it also.
<?php
require('connect.php'); <<<<<------ NEEDED TO ADD THIS
$content = #$_POST['con'];
$post_date = date("d-m-y");
$userID = mysqli_query($conn,"SELECT userID FROM users WHERE name = '".$_SESSION['name']."'");
if(isset($_POST['submit'])){
if($content){
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$userID."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
So thats what i think the offending piece of code was. And it now will give me error saying the SQLI query was unnsuccessful, which means it is at least attempting that part, whereas before it was not.

Trying to create login page using PHP and SQL

I've been working on a website login, and so far, I have the database and register page set up, but I'm trying to work on a Login page. I've been trying to retrieve data from the Database's Table. I was successfull at doing so on my register page to make sure there aren't multiple usernames of the same name, so I copied some of the code and pasted it onto this page. The problem: it returns blank. Please help... ._.
`
KHS SiteSpace
<div id="header">
<img src="./IMAGES/khslogo2.png" style="margin-left:4;float:left;" width="100" hieght="100">
<b>KHS<span id="name">SiteSpace</span></a>
<!--img src="./IMAGES/Menu.png" style="float:right;margin-right:6;" height="100" width="90"-->
</div>
<div id="content">
<p id="subTitle">Login</p>
<div style="float:left;height:30%;">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" id="register"><br>
Username:<br>
<input type="text" name="name"><br><br>
Password:<br>
<input type="password" name="pass">
<br><br>
<input type="submit" value="Confirm">
</form>
</div>
<div style="float:right;width:50%;border-style:none none none solid; border-color:222222;border-width:4;height:30%;">
<p style="margin-left:20;font-size:20;">Output:</p>
<p style="margin-left:20;padding-bottom:15;">
<?php
error_reporting(0);
#ini_set('display_errors', 0);
session_start();
$conn = new mysqli("localhost", "shanedrgn", "getting321", "Users");
if (!$conn) {die("Failure to connect");}
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
if (empty($name) or empty($pass)) {echo "Empty Fields";} else {
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
echo "Check: The fields arent empty...";#OUTPUT
echo "Testing Variables...";#OUTPUT
//Error Trapping
$sql = "SELECT Username FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$nameTrap = $record['Username'];
}
$sql = "SELECT Address FROM Users where Address = '$address'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$ipTrap = $record['Address'];
}
if ($nameTrap == $name) {
echo "Check: Username Exists...";
if ($passTrap == $pass) {
echo "Password is correct!";
$_SESSION['User'] = $name;
$sql = "SELECT * FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
$record=mysqli_fetch_array($Data);
session_start();
$_SESSION['id'] = $record['id'];
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
exit();
} else { echo "Password Invalid";}
} else {echo "That username doesn't exist!";echo $name.";;";echo $nameTrap;}
}
?>
</p></div>
</div>
</body>
</html>`
EDIT: Added missing code
You are doing this:
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
I understand, what you try, but it can't work. You can't set an Header after sending Body-Content - what you do using echo.
You should use JavaScript for your redirect, after the 4 second timeout. Use setTimeout and window.location.

Displaying html form inputs on browser permanently after fetched from MySQL database?

I have used an isset() function on 'submit' to store and retrieve my html form inputs. However all my SQL data in my table only gets displayed after I clicked the submit function on the browser as I programmed it that way.
I would like to make it now so that even when I refresh the browser the html form input remains permanently and I do not have to click submit to fetch the entire table and display (it rather displays itself straight away).
Please show me how I can go about this?
below is my code:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$question = $_POST['question'];
$description = $_POST['description'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
}
if(isset($_POST['question']) && $_POST['description']) {
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) {
echo "<p> {$row['question']}</p>";
echo "<p> {$row['description']}</p>";
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="submitQuestion">
<form action="" method="post">
<input type="text" name="question"/>
<textarea name="description" rows="10" cols="20"></textarea>
<input type="submit" name="submit" value="ASK"/>
</form>
</div>
</body>
</html>
If I've correctly understood the question, you would like to always display all entries and add new data only when it's required. For this goal, you can connect and retrieve data independently from form submission, and insert new data only when required.
<?php
require_once "connection.php";
// Connect to database
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
}
// Insert new data if required
if(isset($_POST['submit']) && isset($_POST['question']) && isset($_POST['description']))
{
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if(!$conn->query($sql)) {
echo "error during insert: " . $conn->error;
exit();
}
}
// Display data
$query = "SELECT * FROM `ask` ";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) {
echo "<p> {$row['question']}</p>";
echo "<p> {$row['description']}</p>";
}
// Close database connection
$conn->close();
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="submitQuestion">
<form action="" method="post">
<input type="text" name="question"/>
<textarea name="description" rows="10" cols="20"></textarea>
<input type="submit" name="submit" value="ASK"/>
</form>
</div>
</body>
</html>
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$question = $_POST['question'];
$description = $_POST['description'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
}
if(isset($_POST['question']) && $_POST['description']) {
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
}
$query = "SELECT * FROM `ask` ";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) {
echo "<p> {$row['question']}</p>";
echo "<p> {$row['description']}</p>";
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="submitQuestion">
<form action="" method="post">
<input type="text" name="question"/>
<textarea name="description" rows="10" cols="20"></textarea>
<input type="submit" name="submit" value="ASK"/>
</form>
</div>
As I told you in the other question..

Categories