Cannot connect to localhost error:500 - php

I am currently using mamp in my mac. I have created a file names un.php which has a simple form validation. I want to insert the login/ register information into my table in the local database.
I think there might be some error in the form action keyword. I tried un.php in the form action, I also tried adding the url of the localhost in it, but the same error 500 is showing up.
Thank You

You made many mistakes in your code.
the image describe where there were error.
this image show them off.
errors.
1. the firs if parentheses was not closed.
2. when using mysqli_select_db($a, $b), $a is the 'connection name' and $b is the 'database name'
3. on your $c, many errors were made. these remaks must correct them:
you should not use the minus (-) sign. this is about E-mail. the dash will be considered as a minus sign and will return error.
$_POST[name] is not correct. the correct way is $_POST["name"]. the problem with $_POST["name"] will also cause problem because there was many ("). the best way is to define it in a variable and using it. example: $name = $_POST["name"].
4. the mysqli_query($a, $b) is writen the same as mysqli_select_db($a, $b).
in mysqli_query($a, $b), $a is the connection name, and $b is the query.
5. if(isset($_POST["submit"])), for me it means nothing because 'submit' is a button but not a field. (i am not sure, but i tried and it does not work).
I written the important part of the code only.
I have rewritten the code for you. it works fine with me. it s
<html>
<head>
</head>
<body>
<h2> PHP Form validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >
Name: <input type="text" name="name" />
<br/>
E-mail: <input type="text" name="Email"/>
<br/>
Website: <input type="text" name="website" />
<br/>
Comment: <textarea name="comment" rows ="5" cols="40"></textarea>
<br/>
<input type="submit" value="submit"/>
</form>
<?php
if(isset($_POST["name"])){
$name = $_POST["name"]; $Email = $_POST["Email"]; $_POST["website"]; $_POST["comment"];
$servername = "localhost";
$username = "root"; $password = "password";
$dbase = "test";
$db = mysqli_connect($servername, $username, $password);
if(!$db) echo "Not connected";
else {
$p = mysqli_select_db($db,$dbase);
if(!$p) echo "Problem";
else {
$c = "INSERT INTO Users(name, Email, website, comment) VALUES ('$name', '$Email', '$website', '$comment')";
if(mysqli_query($db, $c));
}
}
mysqli_close($db);
}
?>
</body>
</html>

Related

Why is my website failing to upload to my database (using MySQLI) and then not redirecting me?

I've been racking my brains over this problem for a while now but as yet have not found the problem. I have a form (in index.php) that uploads the user input to a database after the submit button is pressed. As expected I'm redirected to add_records.php after pressing submit, but then I'm stuck on it, despite including the line
header("location: index.php")
The redirect works fine if I comment out all the mysqli code, therefore I've concluded the error is to do with mysqli and uploading to the database (perhaps I'm handling the geographical data incorrectly). I've done all the usual things - checked the error log, checked for any errors on PHPMyAdmin but all show no errors! I shown the code below to help troubleshoot, with all sensitive info replaced with '#' (note - I've checked the database password etc. several times and they're correct).
index.php:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: ##/records/login.php");
exit;
}
echo file_get_contents("##/code/header.php");
?>
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
</div>
<form action="##/records/add_records.php" method="POST">
<input type="text" name="species" placeholder="Species">
<br>
<input type="date" name="date" placeholder="Date">
<br>
<input type="time" name="time" placeholder="Time">
<br>
<input type="location" name="location" placeholder="Location Name">
<br>
<input type="text" name="lat/long" placeholder="Lat Long">
<br>
<input type="number" name="count" placeholder="Count">
<br>
<input type="text" name="county" placeholder="County (default Norfolk)">
<br>
<input type="text" name="country" placeholder="Country (default United Kingdom)">
<br>
<input type="text" name="notes" placeholder="Notes">
<br>
<button type="submit" name="submit">Submit</button>
</form>
<p>
Sign Out of Your Account
</p>
<?php echo file_get_contents("##/code/footer.php"); ?>
add_records.php:
<?php include_once '##/records/config_bird_records.php';
$species = mysqli_real_escape_string($conn, $_POST['species']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$time = mysqli_real_escape_string($conn, $_POST['time']);
$location = mysqli_real_escape_string($conn, $_POST['location']);
$latlong = mysqli_real_escape_string($conn, $_POST['latlong']);
$count = mysqli_real_escape_string($conn, $_POST['count']);
$county = mysqli_real_escape_string($conn, $_POST['county']);
$country = mysqli_real_escape_string($conn, $_POST['country']);
$notes = mysqli_real_escape_string($conn, $_POST['notes']);
$sql = "INSERT INTO bird_db (Species, Date, Time, Location, Lat/Long, Count, County, Country, Notes) VALUES ('$species', $date, $time, '$location', geography::STGeomFromText('POINT($latlong)', 4326), $count, '$county', '$country', '$notes')";
mysqli_query($conn, $sql);
mysqli_close($conn);
header("location: ##/records/index.php")
?>
config_bird_records.php:
<?php
/* Database credentials.*/
define('DB_SERVER', '##');
define('DB_USERNAME', '##');
define('DB_PASSWORD', '##');
define('DB_NAME', '##');
/* Attempt to connect to MySQL database */
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
Thanks for any help,
Louis
The header method needs to be called before you send any output to the browser.
Your code includes output in both success and error cases, which means the redirect will never work. If you remove echo "Records added successfully."; it should work.
you can use javascript for that instead of header() fro redirecting; function
try the following:
echo "<script type='text/javascript'>alert('Upload Successful');
window.location='redirected_page.php';
</script>";
As for the failing to upload, have you googled how mysqli_real_escape_string works, u need to because it will affect some special characters in you variables

How to update user input of a form when i am using header that links to other file?

I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)

PHP error whilst confirming successful row insertion

people
Overview i am crating a dummy website for learning purposes therefore its functionalists are basic and security in not on the agenda atm.
I am experiencing this minor problem that i cant resolve. So why i am trying to do is to add a new account and echo a message saying that the insertion was suspenseful, but i get an error message in a place where i want to add a new record saying that the variable which suppose to hold the message is undefined.
A lil more: So when i am in the Home page of the wbesite and click a register button that is when the error message pops up but when i actually submit a query to add a account that error message changes to the message i want to show.
<?php
if(isset($_POST['submited'])){
include('connect_mysql.php');
$username= $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$email = $_POST['email'];
$NewAccountQuery = "INSERT INTO users (username, password, first_name, last_name, email) VALUES ('$username','$password', '$firstname', '$lastname', '$email')";
if(!mysql_query($NewAccountQuery)){
die(mysql_error());
}//end of nested if statment
if($NewAccountQuery){
echo $confirm = "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 name="submited" 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="back" onclick="index.php" class="button">
</li>
</ul>
</div>
</form>
</article>
<aside>
<?php print $confirm; ?>
</aside>
<div id="footer">This is my site i Made coppyrights 2013 Tomazi</div>
</div>
</body>
</html>
ok here is the image before i submit the query:
Image after i submit the query:
echo $confirm = "1 record added to the database";
Should be:
$confirm = "1 record added to the database";
echo $confirm;
It looks like you don't need the echo there as you echo it else where. If all you want to do is assign $confirm to 1 record added to the database, then you just need to assign it, without the echo. Echo basically outputs it to the html in the same way print does.
I think that the error message is pretty clear. $confirm is not defined. You only define it in the "successful query" section. A simple solution is to define it before the entire if(isset($_POST['submited'])){ block. Just put $confirm = ''; and nothing will be printed out.
Some notes:
Since you are learning and this is all new, you should stop using ext/mysql now and use PDO or mysqli as your DB engine (I prefer the former).
Also, if($NewAccountQuery){ is not very meaningful. It will always be true since it's just a string you define earlier. If you switch to PDO you could check PDOStatement::rowCount.
Basically the problem is when you load the homepage for the first time - it won't go into the if(isset($_POST['submited'])) condition since $_POST['submitted'] is not set. And since you are setting the $confirm inside this loop, This statement <?php print $confirm; ?> won't find $confirm variable set. Hence it will give out PHP NOTICE.. So like someone said here either set $confirm = ''; before if condition or you can do something like this while printing
<?php
if(isset($confirm))
print $confirm;
?>
If you are just echoing or printing the string you don't need to assign it to a variable first. Either of these would work:
echo '1 record added to the database';
OR
$confirm = '1 record added to the database';
echo $confirm;
<?php
if(isset($_POST['submited'])){
include('connect_mysql.php');
$username= $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$email = $_POST['email'];
$NewAccountQuery = "INSERT INTO users VALUES ('$username','$password', '$firstname', '$lastname', '$email')"; // simplified query if those are only 5 cols in order
$result = mysql_query($NewAccountQuery);
if($result){
$confirm = "1 record added to the database";
} else {
exit('error inserting row');
}
}
?>

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);
}
}
?>

my php script enters blank info into mysql db!

When I try to enter data from a form I have made it adds a new entry as i can see from phpmyadmin but does not transfer other details across
I am using a simple form that collects 9 fileds post is to update.php. Here is what I have in update.php
<?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];
mysql_connect ("localhost", "mydb_userid", "MYPASSWORD") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");
$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";
mysql_query($query) or die ('Error updating DB');
echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";
?>
Hope someone can help, searching the net seems to sugest something about global variables - but i dont know if i have control of that as its an hosted site.
this is the signup form:
<!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>Candidate Registration</title>
</head>
<body>
<form medthod="post" action="update.php">
Real Name:<br />
<input type="text" name="realname" size="50" /><br />
Age:<br />
<input type="text" name="age" size="10" /><br />
Country:<br />
<input type="text" name="country" size="20" /><br />
In Game Name:<br />
<input type="text" name="gamename" size="30" /><br />
In Game Level:<br />
<input type="text" name="gamelevel" size="10" /><br />
In Game Item Level:<br />
<input type="text" name="itemlevel" size="10" /><br />
Class Played:<br />
<input type="text" name="class" size="30" /><br />
How long have you played wow?:<br />
<input type="text" name="played" size="10" /><br />
Please enter a brief statement of why you want to join:<br />
<input type="text" name="support" size="5000" /><br />
<br />
<input type="submit" value="Update DB" />
</form>
</body>
</html>
this is the update.php form
<?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];
mysql_connect ("localhost", "mydb_daniel", "mypwd") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");
$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";
mysql_query($query) or die ('Error updating DB');
echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";
?>
I understand peoples concerns about sercurity, but please understand this only for me to mess around with and produce a basic signup form for my guild, i wont be requesting credit card details :)
Is your form method set to POST? - unless you have explicitly added this the variables will be within the $_GET superglobal so your variables would be like this:
$realname = $_GET['realname'];
If it is set to POST - please do a var_dump($_POST) at the top of your script and see if any variables are making it to your script.
Something else that i've seen before is caused when people are redirecting in a .htaccess from domain.com to www.domain.com and they post a script explicity to domain.com/script.php and the script then redirects to www.domain.com/script.php and this empties the POST.
EDIT
You have spelt method wrong in your form tag - if you update this then it should work as your misspelling will be causing the variables to be sent as GET vars.
You can fix your security issues in a basic way like this:
$realname = mysql_real_escape_string($_POST['realname']);
$age = mysql_real_escape_string($_POST['age']);
$country = mysql_real_escape_string($_POST['country']);
$gamename = mysql_real_escape_string($_POST['gamename']);
$gamelevel = mysql_real_escape_string($_POST['gamelevel']);
$itemlevel = mysql_real_escape_string($_POST['itemlevel']);
$class = mysql_real_escape_string($_POST['class']);
$played = mysql_real_escape_string($_POST['played']);
$support = mysql_real_escape_string($_POST['support']);
Whoa, slow down. You've not even escaped this data!
$realname = mysql_real_escape_string($_POST['realname']);
Or to escape it all:
$_POST = array_map('mysql_real_escape_string', $_POST);
Note the second solution isn't entirely reliable. Can produce some strange results. It is generally better to run these inputs through a function/class for validation and cleansing.
On your ghost issue, try this and note response after form submit (put right at top):
var_dump($_POST);
exit;
You spelled method attribute wrong in your query, that is why it isn't working.

Categories