Display user name in a page - php

I have an input text area where the user enter his name and i want his name to be shown in another page.
This is what i've tried so far:
HTML of the form:
<html>
<form method="post" name="input" action="name.php" >
Name:<br/>
<input name="user" type="text"/><br/>
<input type="submit" name="Submit" value="insert" />
</form>
name.php
<?php
mysql_connect("localhost", "root", "root") or die("Connection Failed");
mysql_select_db("user")or die("Connection Failed");
session_start();
$_SESSION['user'] = $_POST['user'];
$user = $_POST['user'];
$query = "INSERT INTO test(user)VALUES('$user')";
if(mysql_query($query)){
echo "inserted";}
else{
echo "fail";}
?>
and the page where i want the name to be shown:
<?php
$connection = mysql_connect('localhost', 'root', 'root');
mysql_select_db('user');
echo $user;
mysql_close();
?>
Thanks in advance

Before printing the value for $user with echo $user;, you've to fetch its value either from database with a SELECT query or from the SESSION Right now you're opening a connection to the database on the page where you want to print $user but are not fetching data from the table. $user has no value assigned here.

You haven't done anything to populate the $user variable in the final page.
You need to make an SQL query or read some form data.
(You also need to defend against XSS attacks)

Related

Checking if textbox is empty returns empty even to I have entered and input on my PHP/HTML

This is my form from my html
<form action="Belo_Connect2.php" method="POST">
<center>
Name:<input type="text" name="namefordelete">
<p> //button that submits to php file
<button>DELETE</button>
</p>
</center>
Now below is my php file that returns Name is empty but I definitely input text when running it on my localhost. Can you guys help me to pinpoint my error here? Thank you so much. And please note if im deleting things right way here. Thank you again
$name = filter_input(INPUT_POST,'namefordelete');
if(!empty($name)){
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "studentInfoDB";
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
if(mysqli_connect_error()){
die('Connect Error('.mysqli_connect_errno().')'.mysqli_connect_error());
}
//my delete query
else{
$sql = "DELETE FROM studentTbl WHERE Name = '$name'";
if($conn->query($sql)){
echo "One record Deleted!";
}
else{
echo "Error:".$sql."<br>".$conn->error;
}
$conn -> close();
}
}
//this always return even I have an input on my input box from html file name=namefordelete
else{
echo "Name should not be Empty";
die();
}
?>
If you are having a link directly to the php screen by [A hyperlink], it will not submit the data in the namefordelete inputbox.
Hence please try to amend as follows:
<form action="Belo_Connect2.php" method="POST">
<center>
Name:<input type="text" name="namefordelete">
<input type="submit" value="delete">
</form>
</center>

Unable to update database row in PHP with $_POST variable

I want it so that when the user types into the textarea/input and clicks save changes, the information they input has been added and saved into the database. Below is my code:
$name = $_SESSION['u_name'];
$uid = $_SESSION['u_uid'];
$id = $_SESSION['u_id'];
$con = mysqli_connect("localhost", "root", "pass123", "db_name");
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "<script type='text/javascript'>alert('connection failed. try again');</script>";
}
$remind1 = $_POST['remind1'];
$remind2 = $_POST['remind2'];
$remind3 = $_POST['remind3'];
$remind4 = $_POST['remind4'];
$remind5 = $_POST['remind5'];
if (isset($_POST['updBtn'])){
$sql = "UPDATE reminders SET remindone='$remind1' WHERE username='$uid'";
if ($con->query($sql) === TRUE) {
echo "<script type='text/javascript'>alert('Updated successfully');</script>";
}else{
echo "<script type='text/javascript'>alert('error while updating. try again');</script>";
}
}
Below is the corresponding HTML:
<form action="body.php" method="post">
<input type="submit" class="sideBtn" value="Save Changes" name="updBtn"><br>
<input type="text" class="event" name="remind1"><br>
<input type="text" class="event" name="remind2"><br>
<input type="text" class="event" name="remind3"><br>
<textarea class="event" name="remind4"></textarea><br>
<textarea class="event" name="remind5"></textarea><br>
</form>
Ideally what would happen, is that whatever the user types into the textarea/input is updated in the database, then they can access and later tweak the text if they need to.
I have been able to pinpoint that my problem is somewhere along the $_POST variables in my PHP as, if I were to substitute the aforementioned variable with a string as such:
$sql = "UPDATE reminders SET remindone='hello' WHERE username='$uid'";
...it works perfectly. But with when using the POST variable, it does not work.
How can I fix this mistake of mine and make it so that the user is able to post text into the database? Is the $_POST variable required here or is there another method to achieve this?

how to return values from mysql table with ajax and php

I am new to programing. I have one form to create Groups. It has two text fields Code Id and Code description. After submitting it showed me that the Code Id which i entered is already exist and if not it add one record in MySQL table. What I want that when I leave the Id text field at the same time with onchange event and Ajax to search table and alert if the Id already exit and at the same time fill name text box with description of that Code Id. How to do that? My code is
HTML file
...
</style>
<body>
<H1>Create Grup</h1>
<br>
<form action="creategrup.php" method="post">
<p>
<label for="codigo">Grup Id:</label>
<input type="text" required="required" autofocus="autofocus"
maxlength="4" name="codigo" id="codigo">
</p>
<p>
<label for="nombre">Grupo description:</label>
<input type="text" required="required" name="nombre" id="nombre"">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
And PHP is
<?php
include 'connectdb.php';
$nombre=$_POST['nombre'];
$codigo=$_POST['codigo'];
$sql = "select codigogrupo,nombregrupo from grupo where
codigogrupo='$codigo'";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) >0) {
echo "<p><h1><b>Grup Id $codigo allready exist....</h1></b></p><br>";
echo "<a href='creategrup.html'>Go Back</a>";
}
else {
mysqli_query($conn, "insert into grupo(codigogrupo,nombregrupo)
values('$codigo','$nombre')");
if(mysqli_affected_rows($conn)>0){
echo "<p><h1><b>Grup $nombre added</h1></b></p>";
echo "<a href='creategrup.html'>Go Back</a>";
} else {
echo "Grup not added<br>";
echo mysqli_error ($conn);
}
}
?>
Connectdb.php
<?php
$servername = "server name";
$username = "user name";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
?>
Please help me.
You are getting already exist message so that may be confirm that there is another data with same id. For further assistance please knock me

Save input into database

Hello guys i need some help.I connected to database from server and can insert some info like $sql = "INSERT INTO Posts (Text_Post) VALUES ('Sample Text')";. Now I want to save on click text from <input type="text" /> to database. Can you tell me what i am doing wrong.
<?php
$servername = "google.com";
$username = "google";
$password = "google";
$dbname = "google";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['Submit'])) {
$sql = "INSERT INTO Posts (Text_Post) VALUES ('".$_POST['text']."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>anonim</title>
</head>
<body>
<form name="form" action="" method="post">
<input type="text" name="text" id="text" value="Salut" /=>
<input type="submit" id="Submit" />
</form>
</body>
</html>
You're missing the name tag on your submit. When data is POST'ed to the server, it uses the name tag.
<input type="submit" id="submit" name="Submit">
Remember to watch your Capitals also - (since you're checking if Submit is SET then you need to POST the submit).
You could just do:
if(isset($_POST['text'])) {
Also, going off the comments: I'd suggest taking a look at this link because you're prone to SQL Injections.
when we are going to post a form using POST or GET. we should always give name to all our fieds so we get get them just using $_POST['name'] or $_GET['name']. In Your case just give a name to your submit tag and check whether data is submitted or not.
replace
<input type="submit" id="Submit" />
with
<input type="submit" id="submit" name="submit">
and check it like
if(isset($_POST['submit'])) {// it will only check where form is posted or not
// your code...
}

PHP insert data to Mysql

I am experimenting with PHP and Mysql. I have created a database and table at mu localhost using xampp. I have also created a file that suppose to populate my table by executing a query, but the strange thing is that i get no errors but at the same time no DATA has been inserted into my DataBase:
CODE:
register.php:
<?php
session_start();
if(isset($_POST['submitted'])){
include('connectDB.php');
$UserN = $_POST['username'];
$Upass = $_POST['password'];
$Ufn = $_POST['first_name'];
$Uln = $_POST['last_name'];
$Uemail = $_POST['email'];
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, emial) VALUES ('$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
if(!mysql_query($NewAccountQuery)){
die(mysql_error());
}//end of nested if statment
$newrecord = "1 record added to the database";
}//end of if statment
?>
<html>
<head>
<title>Home Page</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<header><h1>E-Shop</h1></header>
<article>
<h1>Welcome</h1>
<h1>Create Account</h1>
<div id="login">
<ul id="login">
<form method="post" action="register.php" >
<fieldset>
<legend>Fill in the form</legend>
<label>Select Username : <input type="text" name="username" /></label>
<label>Password : <input type="password" name="password" /></label>
<label>Enter First Name : <input type="text" name="first_name" /></label>
<label>Enter Last Name : <input type="text" name="last_name" /></label>
<label>Enter E-mail Address: <input type="text" name="email" /></label>
</fieldset>
<br />
<input type="submit" submit="submit" value="Create Account" class="button">
</form>
</div>
<form action="index.php" method="post">
<div id="login">
<ul id="login">
<li>
<input type="submit" value="Cancel" onclick="index.php" class="button">
</li>
</ul>
</div>
</article>
<aside>
</aside>
<div id="footer">This is my site i Made coppyrights 2013 Tomazi</div>
</div>
</body>
</html>
I have also one include file which is connectDB:
<?php
session_start();
$con = mysql_connect("127.0.0.1", "root", "");
if(!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("eshop", $con) or die("Cannot select DB");
?>
Database structure:
database Name: eshop;
only one table in DB : users;
users table consists of:
user_id: A_I , PK
username
password
first_name
last_name
email
I spend a substantial amount of time to work this out did research and looked at some tutorials but with no luck
Can anyone spot what is the root of my problem...?
It is because if(isset($_POST['submitted'])){
you dont have input field with name submitted give the submit button name to submitted
<input name="submitted" type="submit" submit="submit" value="Create Account" class="button">
Check your insert query you have more fields than your values
Change :
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, email) VALUES ('$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
to :
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, email) VALUES ('','$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
Considering user_id is auto increment field.
Your email in query is written wrongly as emial.
Is error reporting turned on?
Put this on the top of your screen:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Some good answers above, but I would also suggest you make use of newer MySQLi / PDO instead of outdated 2002 MySQL API.
Some examples: (i will use mysqli since you wrote your original example in procedural code)
connectDB.php
<?php
$db = mysqli_connect('host', 'user', 'password', 'database');
if (mysqli_connect_errno())
die(mysqli_connect_error());
?>
register.php -- i'll just write out an example php part and let you do the rest
<?php
//i'll always check if session was already started, if it was then
//there is no need to start it again
if (!isset($_SESSION)) {
session_start();
}
//no need to include again if it was already included before
include_once('connectDB.php');
//get all posted values
$username = $_POST['username'];
$userpass = $_POST['password'];
$usermail = $_POST['usermail'];
//and some more
//run checks here for if fields are empty etc?
//example check if username was empty
if($username == NULL) {
echo 'No username entered, try again';
mysqli_close($db);
exit();
} else {
//if username field is filled we will insert values into $db
//build query
$sql_query_string = "INSERT INTO _tablename_(username,userpassword,useremail) VALUES('$username','$userpass','$usermail')";
if(mysqli_query($db,$sql_query_string)) {
echo 'Record was entered into DB successfully';
mysqli_close($db);
} else {
echo 'Ooops - something went wrong.';
mysqli_close($db);
}
}
?>
this should work quite nicely and all you need to add is your proper posted values and build the form to post it, that's all.
<?php
$db = mysqli_connect('host', 'user', 'password', 'database');
if (mysqli_connect_errno())
die(mysqli_connect_error());
?>
register.php -- i'll just write out an example php part and let you do the rest
<?php
//i'll always check if session was already started, if it was then
//there is no need to start it again
if (!isset($_SESSION)) {
session_start();
}
//no need to include again if it was already included before
include_once('connectDB.php');
//get all posted values
$username = $_POST['username'];
$userpass = $_POST['password'];
$usermail = $_POST['usermail'];
//and some more
//run checks here for if fields are empty etc?
//example check if username was empty
if($username == NULL) {
echo 'No username entered, try again';
mysqli_close($db);
exit();
} else {
//if username field is filled we will insert values into $db
//build query
$sql_query_string = "INSERT INTO _tablename_(username,userpassword,useremail) VALUES('$username','$userpass','$usermail')";
if(mysqli_query($db,$sql_query_string)) {
echo 'Record was entered into DB successfully';
mysqli_close($db);`enter code here`
} else {
echo 'Ooops - something went wrong.';
mysqli_close($db);
}
}
?>

Categories