Running php functions on the same screen - php

Hi I'm very very new to php and playing with codes to learn. I have a very basic login form that has username and password input and two input buttons
one to create entries in the database and other to read from database.
JsFiddle: https://jsfiddle.net/e93kcpto/
My sign up and read functions are located in functions.php file
function signUpFunct(){
if(isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$connection = mysqli_connect('localhost','root','','loginPage');
if($connection){
$query = "INSERT INTO users(username,password) VALUES ('$username','$password')";
if($query){
mysqli_query($connection,$query);
}
else{
die("Sign Up Failed");
}
}
else{
die("Failed to Connect Database");
}
}
}
function readAll(){
$connection = mysqli_connect('localhost','root','','loginPage');
if($connection){
$query = "SELECT * FROM users";
if($query){
$result = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($result)){
?>
<pre>
<?php print_r($row);?>
</pre>
<?php
}
}
else{
die("Sign Up Failed");
}
}
else{
die("Failed to Connect Database");
}
}
and this is how I call these two functions in the functions.php file(I'm not sure if this is a good approach so if there is a better way please let me know)
if(isset($_POST['signUp'])){
signUpFunct();
}
else if(isset($_POST['display'])){
readAll();
}
both functions work fine but the problem is when I click on the display button in the browser I am at http://localhost.../functions.php
what I would like to do is to display the data on the form page when I click on the Display button. How can I do this?

Related

display user input as comment on same page

I'm trying to create a comment system on my webpage. I want the user to be able in input a comment and have it automatically display on the same page, and reload so that if another user wants to comment the previous comment will also be there. So far, I have created a database that takes in the comments. I have tried to display the comments by querying through my database and printing it out, but it just seems to crash my site.
This is the code I have so far
index.php:
<form action="insert.php" method="GET">
Comments:
<input type="text" name="field1_name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<?php
$query="SELECT COMMENTS FROM parentComment";
$results = mysqli_query($query);
while ($row = mysqli_fetch_assoc($results)) {
echo $row['COMMENTS'];
}
?>
insert.php:
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'x'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_GET["field1_name"])) {
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
// Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$field1_name')";
$result = mysqli_query($link, $sql);
// attempt insert query execution
if ($result) {
//echo $_GET["field1_name"];
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
So far everything works as in the comments are being inserted into the database. My problem is with retrieving the comments and displaying it to the user on the same page. I've tried to do so, but it seems to be not working. Not sure where I'm going wrong in my implementation (I've implemented it in the index.php file)
You didn't connect to your db for the query:
$results = mysqli_query($query);
Pass the connection to the query:
$results = mysqli_query($link, $query);
It's required.
http://php.net/manual/en/mysqli.query.php
You also need to make sure that you did establish a connection in that file, otherwise it won't work.

MAMP can't establish database connection

I'm trying to save data from a multi-page form into a database. I followed this tutorial but the connection always fails. I had to change to function from mysql_connect to mysqli_connect as I am running PHP7, so this could be part of the issue. Here is the code:
<?php
session_start();
if (isset($_POST['state'])) {
if (!empty($_SESSION['post'])){
if (empty($_POST['address1'])
|| empty($_POST['city'])
|| empty($_POST['pin'])
|| empty($_POST['state'])){
// Setting error for page 3.
$_SESSION['error_page3'] = "Mandatory field(s) are missing, Please fill it again";
header("location: finder-step-3.php"); // Redirecting to third page.
} else {
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
extract($_SESSION['post']); // Function to extract array.
$connection = mysqli_connect("localhost", "root", "root");
$db = mysqli_select_db($connection, "finder_form"); // Storing values in database.
$query = mysqli_query($db, "insert into detail (name,email,contact,password,religion,nationality,gender,qualification,experience,address1,address2,city,pin,state) values('$name','$email','$contact','$password','$religion','$nationality','$gender','$qualification','$experience','$address1','$address2','$city','$pin','$state')", $connection);
if ($query) {
echo '<p><span id="success">Form Submitted successfully..!!</span></p>';
} else {
echo '<p><span>Form Submission Failed..!!</span></p>';
}
unset($_SESSION['post']); // Destroying session.
}
} else {
header("location: finder-step-1.php"); // Redirecting to first page.
}
} else {
header("location: finder-step-1.php"); // Redirecting to first page.
}
?>
Can anyone spot where I am going wrong? Thanks in advance!
Update 1:
#Damon Swayn, I have changed it to the below but still receive the form submission failed message:
$connection = mysqli_connect("localhost", "root", "root", "finder_form");
$query = mysqli_query($connection, "insert into detail (name,email,contact,password,religion,nationality,gender,qualification,experience,address1,address2,city,pin,state) values('$name','$email','$contact','$password','$religion','$nationality','$gender','$qualification','$experience','$address1','$address2','$city','$pin','$state')", $connection);
if ($query) {
echo '<p><span id="success">Form Submitted successfully..!!</span></p>';
} else {
echo '<p><span>Form Submission Failed..!!</span></p>';
}
#lps, I setup the following on a test.php page in the same directory and it connected successfully:
<?php
$con = mysqli_connect('localhost', 'root', 'root') or die('Could not connect the database : Username or password incorrect');
mysqli_select_db($con, 'finder_form') or die ('No database found');
echo 'Database Connected successfully';
?>
Update 2: Solved
The changes suggested by Damon Swayn worked, I just had to remove the $connection at the end of the query. Here is the working code:
$connection = mysqli_connect("localhost", "root", "root", "finder_form");
$query = mysqli_query($connection, "insert into detail (name,email,contact,password,religion,nationality,gender,qualification,experience,address1,address2,city,pin,state) values('$name','$email','$contact','$password','$religion','$nationality','$gender','$qualification','$experience','$address1','$address2','$city','$pin','$state')");
if ($query) {
echo '<p><span id="success">Form Submitted successfully..!!</span></p>';
} else {
echo '<p><span>Form Submission Failed..!!</span></p>';
}
mysqli_connect() can take 4 parameters, the fourth being the database name.
you are using the return value of mysqli_select_db() as the connection param for every following call, mysqli_select_db() returns a boolean true/false value, try replacing the $db param in the following calls after mysqli_select_db() with the $connection variable.

PHP MySQL login setup error

This is all really new to me and I only know the very basics. I'm creating a frontend login for a webpage (obviously security isn't a huge deal or I wouldn't be doing it). I keep getting in issue with my "where" clause, stating that the "user" does not exist. Database is setup like this:
dbname=connectivity
table=users
users has id, user, and pass.
Anyone want to give me some pointers? Thanks in advance.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Ya done goofed: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Ya done goofed: " . mysql_error());
function SignIn()
{
session_start();
if(!empty($_POST['user']))
{
$query = mysql_query("SELECT * FROM users where user = `$_POST[user]` AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['user']) AND !empty($row['pass']))
{
$_SESSION['user'] = $row['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
Please stop using mysql_*. use mysqli_* or PDO. Have a look to the code:-
<?php
// Force PHP to show errors
error_reporting(E_ALL); // Get all type of errors if any occur in code
ini_set('display_errors',1); // Display those errors
session_start(); // start session
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("connection not established"); Or use $con = mysqli_connect('localhost','root','','connectivity') or die("connection not established");
if(isset($_POST['submit'])){
SignIn();
}
function SignIn(){
if(!empty($_POST['user'])) {
$username = mysqli_real_escape_string($con , $_POST['user']); // prevent form SQL injection
$password = mysqli_real_escape_string($con , $_POST['pass']); // prevent form SQL injection
$query = mysqli_query($con,"SELECT * FROM users where user = '".$username."' AND pass = '".$password."'") or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0){ // check count of resultset
$_SESSION['user'] = $_POST['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}else{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
?>
There are some issues here:
SELECT * FROM users where user = `$_POST[user]` AND pass = '$_POST[pass]'
The quote styles are all over the place. Try this:
SELECT * FROM `users` WHERE `user` = '$_POST[user]' AND `pass` = '$_POST[pass]'
Also, you should pre-process for SQL injection if you're not already.
This is the correct formatted SQL.
$query = mysql_query("SELECT * FROM `users` WHERE `user` = `'".$_POST["user"]."'` AND pass = '".$_POST["pass"]."'") or die(mysql_error());
One thing to note is that you MUST escape and validate all global variables. For more information I strongly recommend you to read this SO post: How can I prevent SQL injection in PHP?
There are multiple things wrong with your code check it down below:
<?php
session_start(); // This needs to be on top of every page
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
// Use mysqli_* as mysql_* is depracted and will be removed
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die("connection not established");
// Add a bit of security
$user = mysqli_real_escape_string($con, $_POST['user']);
$pass = mysqli_real_escape_string($con, $_POST['pass']);
function SignIn($user, $pass) {
// Add backticks ` around column and table names to prevent mysql reserved word error
$query = mysqli_query($con, "SELECT * FROM `users` WHERE `user` = '$user' AND `pass` = '$pass'");
// No need to fetch the data you already have
// Check if the query returns atleast 1 row (result)
if( mysqli_num_rows($query) >= 1 ) {
$_SESSION['user'] = $pass;
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
} else {
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
if(isset($_POST['submit']) && !empty($user) && !empty($pass) ) {
SignIn($user, $pass);
} else {
echo "SORRY... THERE ARE EMPTY FIELDS... PLEASE RETRY...";
}
?>
Just changed your code like follows:
SELECT * FROM users where user ='$_POST[user]'AND pass = '$_POST[pass]'
That line need to rewrite like follows:
SELECT * FROM users WHERE user = '".$_POST[user]."' AND pass = '".$_POST[pass]."'
I believe that should work in every server without any kind of trouble.
You are missing quotations
Corrected code:
$query = mysql_query("SELECT * FROM `users` WHERE `user` = `'".$_POST["user"]."'` AND pass = '".$_POST["pass"]."'") or die(mysql_error())

php outputting code rather than executing

I am pretty new to php, but have to link a database to html through php as part of uni coursework, so I attempted to implement a register and log in feature to the site we created. As far as I am aware this code should work however whenever I try to run it through the html page it posts the code itself rather than running. This is the case for both the login and registration. What am I doing wrong?
//registration
<?php
define('DB_HOST', 'xxx');
define('DB_NAME', 'xxx');
define('DB_USER','xxx');
define('DB_PASSWORD','xxx');
$con = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL Database: " . mysql_error());
function NewUser() {
$Name = $_POST['Name'];
$Username = $_POST['Username'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$query = "INSERT INTO userDetails (Username,Email,Name,Password) VALUES ('$Username','$Email','$Name','$Password')";
$data = mysql_query($query) or die(mysql_error());
if($data) {
echo "YOUR REGISTRATION IS COMPLETED...";
}
}
function SignUp() {
if(!empty($_POST['Username'])) {
$query = mysql_query("SELECT * FROM userDetails WHERE Username = '$_POST[Username]' AND Password = '$_POST[Password]'") or die(mysql_error());
if(!$row = mysql_fetch_array($query) or die(mysql_error())) {
newuser();
} else {
echo "YOU ARE ALREADY A REGISTERED USER...";
}
}
}
if(isset($_POST['submit'])) {
SignUp();
}

Inserting user updates into SQL with PHP

I think I am really close now - there are no more nasty Orange boxes with errors in - the only problem I can see at the moment is that once I update the table (after the
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')";
) I get the message "No rows updated" echo to the screen!
Any ideas what the problem is?
Thanks.
<?php
//Start session
session_start();
$_SESSION['SESS_LOGIN'];
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$employ = clean($_POST['employer']);
$address = clean($_POST['flat']);
?>
<?Php
//Insert employer and address into database row for logged in user.
$login_name = $_POST['login_name'] ;
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')" ;
$result = #mysql_query($link, $qry);
//Check whether the query was successful or not
if(!$result) {
echo "No rows updated";
exit();
}else {
echo "Success";
}
?>
Don't use VALUES, use SET:
"UPDATE `members` SET `employer` = '".$employ."', `flat` = '".$address."' WHERE `login`='".$login_name."'"
First of all you should not suppress error messages by using the # opperator if you are looking for issues in your code. Also you are using the wrong parentheses (' instead of `). The rest of your code looks fine. maybe you need to give us some info about the database structure otherwise

Categories