I have looked up tutorials multiple times and am having trouble figuring out where my code is wrong. I am able to run my php file and get my information sent into my database, so I know my connection isn't the issue, so I am thinking its my index.html file. It may have something to do with how i tried to implement jquery, but I don't know about that either
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="login.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#login').click(function(event){
event.preventDefault();
var username =$('#use').val();
var pass = $('#pass').val();
$.ajax({
url: 'login.php',
method:'POST',
data:
{
User: username,
Pass: pass
},
success:function(result){
alert(result);
}
});
});
});</script>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form">
<input type="text" placeholder="name"/>
<input type="password" placeholder="password"/>
<input type="text" placeholder="email address"/>
<button>create</button>
<p class="message">Already registered? Sign In</p>
</form>
<form class="login-form">
<input type="text" id="use" placeholder="username"/>
<input type="password" id="pass" placeholder="password"/>
<button type="submit" id="login">login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
</body>
</html>
PHP code connecting to my DB
<?php
$dbname = 'project test';
$dbuser = 'root';
$dbpass = '';
$dbhost = 'localhost';
$username=$_POST['use'];
$password=$_POST['pass'];
$conn= mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (User, Pass)
VALUES ('{$username}','{$password}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close(); ;
?>
In your index.html file, you are sending User and Password values However, when you are trying to get them in your php file, you are trying to get use and pass values. Their names don't match. The names need to match in order to get the values correctly.
Related
Trying to insert data into MySQL database with PHP. I don't want to refresh the page. The data isn't inserted when I press the Send Message button, but the data is displayed. Please help a noob out. Here's the HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Contact Form</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="form">
<form method="POST" action="form.php" id="foo" name="foo">
<h1>Contact Form</h1>
<table>
<tr>
<td>
<label for="fname">Full Name:</label><br>
<input type="text" name="fname" placeholder="John Doe" id="">
</td>
</tr>
<tr>
<td>
<label for="email">Your Email:</label><br>
<input type="email" name="email" placeholder="example#gmail.com" id="">
</td>
</tr>
<tr>
<td>
<label for="msg">Your Message:</label><br>
<textarea name="msg" placeholder="Type your message..." id="" cols="30" rows="10"></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Send Message">
</td>
</tr>
</table>
</form>
</div>
<p id="target">
</p>
<script>
$(function() {
$("#foo").submit(function(event){
// Stop form from submitting normally
event.preventDefault();
/* Serialize the submitted form control values to be sent to the web server with the request */
var formValues = $(this).serialize();
// Send the form data using post
$.post("form.php", formValues, function(response){
$('#target').load('show.php');
});
});
});
</script>
</body>
</html>
Here's form.php which is supposed to insert data into the database:
<?php
error_reporting(E_ALL);
log_errors(1);
display_errors(1);
if(isset($_POST['submit']))
{
$name = $_POST['fname'];
$email = $_POST['email'];
$message = $_POST['msg'];
//database details. You have created these details in the third step. Use your own.
$host = "localhost";
$username = "user";
$password = "GoTn_1290";
$dbname = "form_entriesdb";
//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect($host, $username, $password, $dbname);
//check connection if it is working or not
if (!$con)
{
die("Connection failed!" . mysqli_connect_error());
}
//This below line is a code to Send form entries to database
$sql = $con->prepare("INSERT INTO contactform_entries (name_fld, email_fld, msg_fld) VALUES (?, ?, ?)");
$sql->bind_param("sss", $name, $email, $message);
$sql->execute();
//connection closed.
$sql->close();
$con->close();
}
?>
And here's what displays my data, show.php:
<?php
$servername = "localhost";
$username = "user";
$password = "secret";
$dbname = "form_entriesdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT id, name_fld, email_fld, msg_fld FROM contactform_entries";
$result = $conn->query($sql2);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name_fld"]. " " . $row["email_fld"]. " " . $row["msg_fld"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I ended up using .ajax instead of .post. I also changed my filename to index.php. I can't find the website where I got my code from, but here it is:
<!DOCTYPE html>
<html>
<head>
<title>Insert data in MySQL database using Ajax</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div style="margin: auto;width: 60%;">
<div class="alert alert-success alert-dismissible" id="success" style="display:none;">
×
</div>
<form id="fupForm" name="form1" method="post">
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Name" name="name">
</div>
<div class="form-group">
<label for="pwd">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Email" name="email">
</div>
<div class="form-group">
<label for="pwd">Phone:</label>
<input type="text" class="form-control" id="phone" placeholder="Phone" name="phone">
</div>
<div class="form-group" >
<label for="pwd">City:</label>
<select name="city" id="city" class="form-control">
<option value="">Select</option>
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Pune">Pune</option>
</select>
</div>
<input type="button" name="save" class="btn btn-primary" value="Save to database" id="butsave">
</form>
</div>
<p id="target">
</p>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var city = $('#city').val();
if(name!="" && email!="" && phone!="" && city!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
name: name,
email: email,
phone: phone,
city: city
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
$('#target').load('show.php');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the fields !');
}
});
});
</script>
</body>
</html>
Here's save.php. It's the code that inserts data into the database:
<?php
include 'database.php';
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$city=$_POST['city'];
$sql = $con->prepare("INSERT INTO `crud`( `name`, `email`, `phone`, `city`) VALUES (?,?,?,?)");
$sql->bind_param("ssss", $name, $email, $phone, $city);
$rc = $sql->execute();
if (true===$rc) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
//connection closed.
$sql->close();
$con->close();
?>
Here is show.php:
<?php
include 'database.php';
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$query = "SELECT name, email, phone, city FROM crud";
$result = $con->query($query);
if ($result->num_rows > 0) {
// output data of each row
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["name"]. " " . $row["email"]. " " . $row["phone"]. " " . $row["city"]."<br>";
}
} else {
echo "0 results";
}
$result -> free_result();
$con->close();
?>
And here are the database connection details, database.php:
<?php
$servername = "localhost";
$username = "user";
$password = "secret";
$db="school";
$con = mysqli_connect($servername, $username, $password,$db);
?>
The code posted is entirely functional.
I have created a html register page which is really basic and requires the user to enter their First name, Last name, email, and password. However only the first and last names are being recorded in the database in phpmyadmin and the email and passwords are showing as blank cloumns. I have tried to drop and add the tables and columns again without any luck, i have changed variable names and no luck as well. Not too sure what to do.
Php code
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$password_ = $_POST['password_'];
if (isset($_POST['register'])) {
register($first_name,$last_name,$_email,$password,$conn);
}
$conn->close();
function register($first_name,$last_name,$email,$password,$conn) {
// echo $first_name . " " . $last_name . " " . $student_id . " " . $email;
$sql = "INSERT INTO `register` (`first_name`, `last_name`, `email`, `password_`) VALUES ('$first_name', '$last_name', '$email', '$password_')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
html code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Case</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<form role="form" action="register.php" method="POST">
<div class="form-group">
<label>First Name:</label>
<input type="text" class="form-control" id="first_name" name="first_name"required>
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" class="form-control" id="last_name" name="last_name"required>
</div>
<div class="form-group">
<label>Email address:</label>
<input type="varchar" class="form-control" name="e_mail" id="email"required>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control" id="password" name="password"required>
</div>
<div class="form-group">
<label>Confirm Password:</label>
<input type="password" class="form-control" id="confirm_password"required >
<script>
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>
</div>
<button type="submit" class="btn btn-default" name="register">Register</button>
</form>
</body>
</html>
In order to grab the _POST variables, your input forms must have a name attribute. For your Email form, you have only specified an ID and no name. Go back and add in the name='email' attribute and it should work. Same for password.
It looks like i was missing an underscore in the php register code where it states the function. i have added it and now my code seems to be working, thanks for all the feedback!
I want to create form in HTML files. let say it calls index.html ( client will see this page), and the HTML will be included some ajax codes where it links to php (server connect to Mysql)
So that client can do (insert delete edit) to database by inserting form in the index.html. How possibly to do that?. Please give me a simple code so that I can learn. Thank you so much. I found that PHP can link to others php to retrieve the data. But I would love to use HTML instead ,to link to php on the server.
Thank you so much.
edited code
enter code here (this is index.html)
<html>
<head>
<title>Submit Form Using AJAX PHP and javascript</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="css/style.css" />
<script>
function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var contact = document.getElementById("contact").value;
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if (name == '' || email == '' || password == '' || contact == '')
{
alert("Please Fill All Fields");
}
else
{
//AJAX code to submit form.
$.ajax({
type: "POST",
url: "https://../test2.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}</script>
</head>
<body>
<div id="mainform">
<div class="innerdiv">
<h2>Submit Form</h2>
//div starts here
<form id="form">
<h3>Fill Your Information!</h3>
<div>
<label>Name :</label>
<br/>
<input type="text" id="name" /><br/>
<br/>
<label>Email :</label>
<br/>
<input type="text" id="email"/><br/>
<br/>
<label>Password :</label>
<br/>
<input type="password" id="password" /><br/>
<br/>
<label>Contact No :</label>
<br/>
<input type="text" id="contact" /><br/>
<br/>
<input type="button" id="submit" onclick="myFunction()" value="Submit"/>
</div>
</form>
<div id="clear"></div>
</div>
</body>
</html>
and this is the php.
//Fetching Values from URL
$name2 = $_POST['name1'];
$email2 = $_POST['email1'];
$password2 = $_POST['password1'];
$contact2 = $_POST['contact1'];
$servername = "localhost";
$username = "user";
$password = "userpwd";
$dbname = "dbname";
// Establishing connection with server..
$dbc = mysqli_connect($servername, $username, $password , $dbname)
or die('Error connecting to MySQL server.');
// Selecting Database
if (isset($_POST['name1'])) {
//Insert query
$query = mysqli_query("insert into form_element(name, email, password, contact) values ('$name2', '$email2', '$password2','$contact2')");
echo "Form Submitted succesfully";
}
//connection closed
mysqli_close($dbc);
?>
I don't get it work.
I don't have all the div's you had in there before, but you should be able to add them!
This should work once you put in the right username, password and database name in connection.php
If this doesn't work or isn't what you wanted, please let me know!
This is also up and running at http://emmetstudios.com/form, if you want to see it in operation.
Here's the code, (put it all in the same folder, different files):
connection.php:
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "yourusername";
$dbpass = "yourpassword";
$dbname = "yourdatabasename";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
success.php:
<?php
require 'connection.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
$contact = $conn->real_escape_string($_POST['contact']);
$query = "INSERT into form_element (name,email,password,contact) VALUES('" . $name . "','" . $email . "','" . $password . "','" . $contact . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo "Successful!";
$conn->close();
?>
index.php:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="form" action="success" method="post" onsubmit="return validateForm()" name="upload">
Name:<br>
<input type="text" name="name"> <br><br>
Email:<br>
<input type="text" name="email"> <br><br>
Password:<br>
<input type="password" name="password"> <br><br>
Phone Number:<br>
<input type="text" name="contact"> <br><br>
<input id="submit" type="submit" value="Submit">
</form>
<script>
function validateForm() {
var name = document.forms["form"]["name"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["form"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
var password = document.forms["form"]["password"].value;
if (password == "") {
alert("Password must be filled out");
return false;
}
var contact = document.forms["form"]["contact"].value;
if (contact == "") {
alert("contact must be filled out");
return false;
}
}
</script>
</body>
</html>
This is my PHP code.
<html><head>
<title>login.php</title>
<link rel = "stylesheet" href="login-style.css">
</head>
<body>
<div class = "container">
<div class = "message">
<?php
define('DB_NAME','mydb');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_HOST','127.0.0.1');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if($link){
die('could not connect:'. mysql_error());
}
$db_selected = mysql_select_db(DB_NAME,$link);
if(!$db_selected){
die('can\'t use'.DB_NAME . ': ' . mysql_error());
}
$value1 = $_POST['name'];
$value2 = $_POST['password'];
$sql = "INSERT INTO Account (username,password) VALUES ('$value1','$value2')";
if(!mysql_query($sql))
{die('ERROR'.mysql_error());
}
mysql_close();
?>
<h1>Thank you for logging in </h1>
<form action = "form.html">
<p class ="submit">
<button type ="submit" >
GO TO FORM
</button>
</p>
</div>
</div>
</body>
</html>
I want to store the data in MySQL but when I run the html code (which i have connected to this php code using action =" name of this file"), no entry is done in database I created, can you tell me what is done wrong and help me to correct it?
<DOCTYPE! html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>Sign-In</title>
<link rel = "stylesheet" href ="style-sign.css">
<script type = "text/javascript">
function validateForm(){
var x = document.forms["forma"]["login"].value;
if(x == null || x == "")
{ alert("fill the field ");
return false;
}
var y = document.forms["forma"]["password"].value;
if( y == null || y == "")
{
alert("fill the field");
return false;
}
}
</script>
</head>
<body >
<div class="container">
<div class="login">
<h1>Login</h1>
<form name = "forma" method="post" onsubmit="return validateForm()" action = "login.php">
<p>
<input type="text" name="name" value="" placeholder="Username or Email">
</p>
<p>
<input type="password" name="password" value="" placeholder="Password">
</p>
<p class="submit">
<input type="submit" name="commit" value="Login" >
</p>
</form>
</div>
</div>
</body>
</html>
this is my html code which i have connected to this php file ,I am using xampp and using phpmyadmin , I am not getting any error and apache and mysql both are running
help me with this problem
Change the following:
$sql = "INSERT INTO Account (username,password) VALUES ('$value1','$value2')";
To:
$sql = "INSERT INTO Account (username,password) VALUES ($value1,$value2)";
EDIT:
You do not have input fields setup for the username and password. So POST will not work.
First you From needs an action and a method.
Best woould be to rename the file to form.php
<form action = "form.php" method="POST">
in the result file ...
Connect to the database
$mysqli= #new mysqli('localhost', 'fake_user', 'my_password', 'my_db');
if ($mysqli->connect_errno) {
die('Connect Error: ' . $mysqli->connect_errno);
}
escape your value strings
$query= "INSERT INTO Account (username,password) VALUES ('".$mysqli->real_escape_string($value1)."','".$mysqli->real_escape_string($value2)."')"
Execute query
$result=$mysqli->query($query);
Verify results if any or check if an Error occured
if(!$result) {
$ErrMessage = $mysqli->error . "\n";
$mysqli->close();
die( $ErrMessage) ;
}
Please help, this is driving me mad! I have, I thought, a simple registration form that I am trying to send data with PHP to MySQL in Webmatrix. (PHP 5.5 to add data to MySQL 5.7 in webmatrix 3) however, I get the following error in Chrome:
The localhost page isn’t working
localhost is currently unable to handle this request.
500
Here's the PHP:
<?php
$db_user = 'root';
$db_pass = '';
$db_name = 'MySQL10';
$db_host = 'localhost';
$fname = $_POST('fname')
$lname = $_POST('lname')
$email = $_POST('email')
//Create Connection
$conn = new mysqli ( $db_host, $db_user, $db_pass, $db_name);
//Check connection
if ($conn->connect_error) {
die("Connection failed:" . $conn->connect_error);
}
$sql = "INSERT INTO table_1 (fname_1, lname_1, email_1)
VALUES ('$fname', '$lname', '$email')";
$conn->close();
?>
Here's Mark up:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test Page</title>
</head>
<body>
<div class="registration">
<form name="test" method="post" action="demo.php" autocomplete="on">
<p>First name:<input type="text" name="fname" value=""></p>
<p>Last name:<input type="text" name="lname" value=""></p>
<p>Email Address:<input type="email" name="email" value=""></p>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
thank you all. I added the [] and the ; and having checked the input using: if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "" . $conn->error; } i was kindly reminded that I had not set a default value for the ID in the database!