So, I have this system where you can make a post. So, how it works is, there is an input field, whatever you type in the input field, and click post, it will send to the database as en entry and get posted. The post will be displayed. However, with my current system, after entering something in the input field, and clicking post, the entry gets sent to the database, but the post doesn't actually display. For it to display, you need to refresh the page again, which it displays then, and two entries go to the database.
I don't want this to happen. Right when the user enters text into the input field and clicks post, the post should display on the go, you shouldn't have to refresh for the post to be displayed, and only one entry should be sent to the database, not two. Now, I won't include my database connection and my insert statements, but here is the code to display the post:
<div class="textPost">
<?php
$sql = "SELECT * FROM posts";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="textpostFormat">
// all the displayed post content
</div>
<?php
}
}
?>
</div>
Insert Statement (post.php):
<?php
session_start();
// Making Connection To The Database
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "root";
$database = "feed";
$connection = mysqli_connect($dbHost, $dbUser, $dbPass, $database) or die ("Sorry, we could not connect to the database");
// Posting System
if (!empty($_POST['postContent'])) {
$post = $_POST['postContent'];
$firstname = $_SESSION['firstname'];
$lastname = $_SESSION['lastname'];
$sql = "INSERT INTO posts (firstname, lastname, body, date_posted) VALUES (?, ?, ?, NOW())";
$stmt = mysqli_stmt_init($connection);
// nested if statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "";
} else {
mysqli_stmt_bind_param($stmt, "sss", $firstname, $lastname, $post);
mysqli_stmt_execute($stmt);
}
} else {
echo "";
}
?>
What should I do to resolve this issue? Please help.
table.php
queries the database and delivers a table - the "textPost" file
lets the user add another row and sends it to post.php
post.php
inserts the data into the database
uses require_once to include table.php which will display the updates. require_once 'table.php';
Related
I'm new to PHP and I'm going to try to explain it the way I could :D. I'm trying to accomplish when the user logged in (using username and password), it opens a new page with the users name, address etc.
In my database table, I have a username, password, name and address.
I was able to accomplish the login page using session but would like to how to get/fetch those information like name and address to the new page it opens.
Thank you,
MD :)
correct me if i'm wrong.
Here is how u fetch the information from a certain table by using PHP and MySQL(PhpMyAdmin) database.
$conn = mysqli_connect("localhost", "root", "", "hotel"); //Connecting to the database
if($conn){
$sql = "SELECT USER_NAME, USER_PASS FROM USER"; //SELECT statement
$result = $conn->query($sql); //Executing the statement
if(mysqli_query($conn, $sql)){ //If query success
while($row = $result->fetch_assoc()){ //While loop to retrieve all data
$user = $row["USER_NAME"]; //Assign Column USER_NAME in database to $user
$pass = $row["USER_PASS"]; //Assign Column USER_PASS in database to $pass
echo $user."</br>".$pass."</br>"; //Displaying the content
}
}else{
echo "Query failed";
}
}else{
die("Fatal Error");
}
$conn->close(); //Close the database connection
I'm creating a signup form and am onto the confirmation email part. I want to find all values associated with one other value in a database.
Ex. I get the "key" that is in the URL, then want to find all the values associated with it. In my database there are 4 columns: STR (the key), USERNAME, PASSWORD, and EMAIL. If I get STR I want to get the username, password, and email that are in the same row as the key and then insert it into another table in the same database.
verify.php:
<?php
$username = $_GET['username'];
$password = $_GET['password'];
$email = $_GET['email'];
$servername = "localhost";
$user = 'usernamelol';
$pass = 'passwordlol';
$dbname = 'vibemcform';
$str = $_GET['str'];
$conn = new mysqli($servername, $user, $pass, $dbname);
/* The variable query gets the "key" from the dont database. I want to compare that value with the other values associated with it. Ex. the variables in the same row as the key. */
$query = mysqli_query($conn, "SELECT * FROM `dont` WHERE STR='".$key."'");
/* Below is my attempt. Feel free to change whatever you want. */
$sql = "SELECT USERNAME, PASSWORD, EMAIL FROM dont";
$result = $conn->query($sql);
if (!$query) {
die('Error: ' . mysqli_error($con));
}
if (mysqli_num_rows($query) > 0) {
if ($result -> num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$sqltwo = "INSERT INTO data (USERNAME, PASSWORD, EMAIL) VALUES ($row["USERNAME"], $row["PASSWORD"], $row["EMAIL"])";
}
}
}
echo 'Successfully verified your email!'; exit;
?>
Why not simpy use the insert ... select syntax?
insert into data(username, password, email)
select username, password, email from dont where str = :key
You can run this query right ahead, and then check how many rows were affected:
If no row was affected, then it means that the select did not bring a row back: so the :key was not found in the database
If a row was affected, then the key was found and the executed row was inserted
Note that you should use parametrized queries so your code is safe from SQL injection (and more efficient as well); recommended reading How can I prevent SQL injection in PHP??
I want to select the password data of a user so they can log in on my website (for a member only website). I have a hash of the password and the username written to a table called "users" upon account creation. I do not know how to select a row on the table, so I get the error when the code looks for, something?
I found this on w3, but I don't understand what each part of the code means.
I tried to edit the code so it would match my user case, but I don't know how to.
$servername ="127.0.0.1";
$dbusername = "root";
$dbpassword = "";
$dbname = "users";
//create connection to db
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
$sql = "SELECT id, username, password FROM users";
$result == $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row == $result->fetch_assoc()) {
echo $userid = $row["id"] && $serverpassword = $row["password"] && $serverusername = $row["username"];
}
} else {
echo "User Lookup Failed";
}
$conn->close();
You don't need to select all records from database and then iterate all of them to check correct user. Besides, you should only select user by username and password as below:
$sql = "SELECT id, username, password FROM users WHERE username = '".$serverusername."' AND `password` = '".serverpassword."' ";
Apart, you should use data binding instead of variable to avoid SQL injection.
The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.
<!-- connect to database -->
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}
//<!-- post added information to database -->
if ($_POST['name']) {
if ($_POST['number']) {
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
} ?>
From looking at my code I believe the issue is with this line.
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";
There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";
These hard coded entries are put into the database but i can't get the user entered data to go in.
Create variables for the $_POST values and add the vars for ease of code understanding:
$name = $_POST['name'];
$number = $_POST['number'];
$sql = "INSERT INTO hello (id, name, number) VALUES ('', $name, $number)";
One reason your code may not be working because you have the single quotes around the $_POST values, then you can also do what Jasbeer Rawal recommended.
UPDATE
Based on the kind comments... I would personally take a different approach to adding the data to your database, instead use prepared statements. I use MySQLi, but you can also use PDO.
Start by creating your connection:
<?php
define("HOST", "localhost");
define("USER", "");
define("PASSWORD", "");
define("DATABASE", "");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
echo "There was a slight problem, please contact your webmaster before continuing.";
exit();
}
Then when the user submits the form handle it:
if(isset($_POST['submit']
{
$name = $_POST['name'];
$number = $_POST['number'];
if ($stmt = $mysqli->prepare("INSERT hello (name, number) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $name, $number);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: Could not prepare SQL statement.";
}
}
This will add $name and $number and your ID role has to be a primary role and set to auto_increment. IDs will be automatically generated.
You're about to go down a slippery slope using mysqli. I'd recommend trying to learn to use PDO for making queries. Right now, someone could easily put SQL into the name POST data and actually do damage to your database.
Anyways, your problem at hand, you have a missing bracket and one issue:
VALUES ('', '$_POST['name']', '$_POST['number'')";
It won't work as intended with nested single quotes.
VALUES ('', '$_POST[name]', '$_POST[number]')";
Remove single quotes from $_POST['name'] and $_POST['number'] as below
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', $_POST['name'], $_POST['number'])";
Your insert code be like this
$sql = "INSERT INTO hello (id, name, number)
VALUES ('','{$_POST['name']}', '{$_POST['number']}')";
Then your value will be in database
If field id is primary key and auto increment then your insert statement should be like
Try this:
$sql = "INSERT INTO hello ( name, number)
VALUES ('{$_POST['name']}', '{$_POST['number']}')";
I am creating a sign up form using HTML5/CSS3/PHP/MySql that will have following columns:
Firstname, Lastname, Email, Password ( to be filled on Web form-1)
Username, country, Age, SecurityQues, SecurityAns, Mobile (to be filled on web-form 2).
there is only one table named user_record for all the fields and it has a user_id that is auto generated and auto increment when the web form 1 is executed, and it is also the primary key for the table.
I am using insert query for web form 1 and update query for web form 2. but the second form's data cannot be submitted until it has UserId generated in the web form 1.
I tried to retrieve it using lastInsertId(); but it is not working as it returns the id only when the insertion is done on the same page so it works on form 1 but not on form 2.
there is only one table being used on two different web pages. on one insertion is being done and user_id is being generated.
On the another update query will be performed to update the remaining fields of the row created in the first form. for that form 2 needs primary key which is not available.
Can any one help me and tell me how to retrieve last UserId on the form 2 so that the data can be filled on the same row that user just created on form 1.
following is the code snippet for both form 1 and form 2.
Form 1 PHP Snippet:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "myDB";
$conn = new PDO("mysql:host=$servername;dbname=$db", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['sign_up-btn'])){
session_start();
$first_name = ($_POST['first_name']);
$last_name = ($_POST['last_name']);
$email_id = ($_POST['email_id']);
$password = ($_POST['password']);
$password2 = ($_POST['password2']);
if($password == $password2){
$password = md5($password);
$sql = "INSERT INTO user_record(first_name, last_name, email, password) VALUES('$first_name', '$last_name', '$email_id', '$password')";
$conn->exec($sql);
$_SESSION['message'] = "You are almost done";
$_SESSION['first_name'] = $first_name;
header("location: pro.php");
}else{
$_SESSION['message'] = "Password do not match";
}
}
$conn = null;
?>
PHP Script of form 2 is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "myDB";
$conn = new PDO("mysql:host=$servername;dbname=$db", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['sub_btn'])){
session_start();
$user_name = ($_POST['user_name']);
$sel_cont = ($_POST['sel_cont']);
$age = ($_POST['age']);
$sec_que = ($_POST['sec_que']);
$sec_ans = ($_POST['sec_ans']);
$mob_num = ($_POST['mob_num']);
$con_code = ($_POST['con_code']);
$id = $conn->lastInsertId();
$sql = "UPDATE user_record SET user_name = '$user_name', country = '$sel_cont',
age = '$age', security_ques = '$sec_que', security_ans = '$sec_ans',
mobile_num = '$mob_num', c_code = '$con_code' WHERE user_id = '$id' ";
$conn->exec($sql);
$_SESSION['message'] = "Welcome";
$_SESSION['user_name'] = $user_name;
header("location: home.php");
}
$conn = null;
?>
Plz tell me how to update the same row with the data of second form.
Obviously, the second form can't be submited if does not exists first record inserted.
I supose that second forms is already on the client browser.
You must to use session capabilities, on first form you must to set the lastInsertId() on a session variable.
Later, on form2 submit, the php can retrive the session variable before the UPDATE. If the session variable containing the lastInsertID is not set, means that the client has not submited first form.
As the #XPerez mentioned I needed to use session variables. so on the first web form I added following line before header statement:
$_SESSION['user_id'] = $conn->lastInsertId();
and on the second form I added following statement before Update statement
$id = $_SESSION['user_id'];
and it did the trick. Session variables can used on different web pages through out the single session. On the first page when session started I stored the id of the insertion statement into a session variable and then use it on the second page.