if isset with multiple variables when submitting form - php

I made this typical form which shows a fade in message when submitting it! It works perfectly with up to 2 variables, but when i'm trying to change my code and insert a third variable or more a problem comes up when submitting.
The html code is:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Basic Form</title>
<meta name="description" content="A basic fade in form">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<title>Enable Disable Submit Button Based on Validation</title>
<style>
body{width:50%;min-width:200px;font-family:arial;}
#frmDemo {background: #98E6DB;padding: 40px;overflow:auto;}
#btn-submit{padding: 10px 20px;background: #555;border: 0;color: #FFF;display:inline-block;margin-top:20px;cursor: pointer;font-size: medium;}
#btn-submit:focus{outline:none;}
.input-control{padding:10px;width:100%;}
.input-group{margin-top:10px;}
#error_message{
background: #F3A6A6;
}
#success_message{
background: #CCF5CC;
}
.ajax_response {
padding: 10px 20px;
border: 0;
display: inline-block;
margin-top: 20px;
cursor: pointer;
display:none;
color:#555;
}
</style>
</head>
<body>
<h1>jQuery Fade Out Message after Form Submit</h1>
<form id="frmDemo" action="post-form.php" method="post">
<div class="input-group">Name </div>
<div>
<input type="text" name="name" id="name" class="input-control" />
</div>
<div class="input-group">Message </div>
<div>
<textarea name="comment" id="comment" class="input-control"></textarea>
</div>
<div class="input-group">Lastname </div>
<div>
<input type="text" name="lastname" id="lastname" class="input-control" />
</div>
<div style="float:left">
<button type="submit" name="btn-submit" id="btn-submit">Submit</button>
</div>
<div id="error_message" class="ajax_response" style="float:left"></div>
<div id="success_message" class="ajax_response" style="float:left"></div>
</form>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#frmDemo").submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var comment = $("#comment").val();
var lastname = $("#lastname").val();
if(name == "" || comment == "" || lastname == "" ) {
$("#error_message").show().html("All Fields are Required");
} else {
$("#error_message").html("").hide();
$.ajax({
type: "POST",
url: "form4.php",
data: { name:name, comment:comment, lastname:lastname }, // *** Modify this
success: function(data){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
}
})
</script>
</body>
</html>
and the php code is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['name']) && isset($_POST['comment']) && isset($_POST['lastname'])) { // **Change this
$name = $_POST['name'];
$comment = $_POST['comment'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO step4 (name, comment, lastname) VALUES ('{$name}', '{$comment}' '{$lastname}')";
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Either Name or Comment field not set"; // **Change this
}
$conn->close();
?>
I suppose that the problem has to do with some error in my php code in the if isset POST method, because it can handle 2 variables but no more...

You muss a comma in SQL query - but, if You setup default values in database, it will not throw an error.
I think, the problem is in JSON object in 'data' field in AJAX options.
Try to change syntax:
$.ajax({
type: "POST",
url: "form4.php",
data: "name="+name+"&comment="+comment+"&lastname="+lastname,
success: function(data){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});

You have syntax in your query, you forgot about comma:
$sql = "INSERT INTO step4 (name, comment, lastname) VALUES ('{$name}', '{$comment}' '{$lastname}')";
between '{$comment}' '{$lastname}'.
Put it there as follows:
{$comment}', '{$lastname}
so your code should look as follows:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['name']) && isset($_POST['comment']) && isset($_POST['lastname'])) { // **Change this
$name = $_POST['name'];
$comment = $_POST['comment'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO step4 (name, comment, lastname) VALUES ('{$name}', '{$comment}', '{$lastname}')"; // here the problem occurs
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Either Name or Comment field not set"; // **Change this
}
$conn->close();
?>
In error you can look inside your query:
Error: INSERT INTO step4 (name, comment, lastname) VALUES ('aths',
'as' 'asa') Column count doesn't match value count at row 1
which says your query doesn't have comma between values as and asa

Related

Insert And Retrieve Data in MySQL with $.post Noob Question

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.

Unable to send data from html form into mysql

I am unable to send the information from a from into mysql. I get the following error:
Fatal error: call to undefined function mysqli_connect()
I know the db connection is working because I am able to send other data into the database. I have added the connection information on the signupcontact.php but that did nothing.
I am not sure what the issue is since the database is connected.
Thanks for your help in advance.
form:
<?php
echo "<div class='wrapper'>";
require ('header.php');
include ('signupcontact.php');
include ('db_connect2.php');
?>
<head>
<title>Contac Information</title>
<meta charset="utf-8"/>
<link rel="stylesheet" href="style.css"/>
</style>
<script>
function validateForm() {
if (document.forms[0].userName.value == "") {
alert("Name field cannot be empty.");
return false;
} //end if
if (document.forms[0].userLastName.value == "") {
alert("Last Name field cannot be empty.");
return false;
} // end if
if (document.forms[0].userEmail.value == "") {
alert("Email field cannot be empty.");
return false;
} // end if
alert ("Successful!");
return true;
} //end function validateForm
</script>
</head>
<body>
<?php
echo '<form method="POST"
action="db_connect2.php"
onsubmit="return validateForm();">
<fieldset style="width:900px; margin:auto;">
<legend class="pcenter">Subscribe for updates</legend>
<label for="userName">Name: </label><br />
<input type="text" name="userName" id="userName"/><br /><br />
<label for="Last_Name">Last Name: </label><br />
<input type="text" name="userLastName" id="userLastName"/><br /><br />
<label for="userEmail">Email: </label><br />
<input type="text" name="userEmail" id="userEmail"/>
<br /><br />
<input type="submit" value="submit" id="submit"/><br />
</fieldset>
</form>
dbconnect:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'happy_blog');
if(!$conn) {
die("connection failed: ".mysqli_connect_error());
}
signupcontact (I added the connection here again to see if it helps, nothing)
<?php
$dBServername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "happy_blog";
// Create connection
$conn = mysqli_connect($dBServername, $dBUsername, $dBPassword, $dBName);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['submit'])){
$Name = $_POST['userName'];
$LName = $_POST['userLastName'];
$Email = $_POST['userEmail'];
$Name = mysqli_real_escape_string($conn,$_POST['userName']);
$LName = mysqli_real_escape_string($conn,$_POST['userLastName']);
$Email = mysqli_real_escape_string($conn,$_POST['userEmail']);
//$sql = "INSERT INTO contact (userName, userLastName, userEmail) VALUES ('".$_POST["userName"]."', '".$_POST["userLastName"]."', '".$_POST["userEmail"]."')";
$sql = "INSERT INTO contact (userName, userLastName, userEmail) VALUES ($Name, $LName, $Email)";
$result = mysqli_query($conn, $sql);
if ($conn->query($sql) === TRUE) {
echo "Form submitted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}

Send Form Data to mysqli dtbs using php fails (xampp environment)

Here is a my html form code: The problem is that i can't figure out how to succesfuly submit the form to mysql dtbs using xampp. (Data aren't sent to dtbs).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My Form</title>
<meta name="description" content="An interactive form">
</head>
<body>
<form action="test.php" method="post" id="Personalinfo">
<label for="fname">Όνομα:</label>
<input type="text" id="fname" name="firstname" placeholder="Όνομα
Πελάτη..">
<input type="submit" value="Submit">
</body>
</html>
and now my php code:
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Guests (firstname)
VALUES ('?')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Data is not sent in the mysql dtbs! i've been trying for 2 days solving this but nothing... please help!
Kind regards, Thanos
$sql = "INSERT INTO Guests (firstname) VALUES ('?')";
'?' is to substitute in an integer, string, double or blob value.
You placed the '?', but forgot to prepare it using bind_param. More importantly, you have to pass $firstname value into $stmt->bind_param("s", $firstname);
Updated Code
$firstname = $_POST['firstname'];
$sql = $conn->prepare("INSERT INTO Guests (firstname) VALUES (?)");
$sql->bind_param("s", $firstname);
if ($sql->execute() === TRUE) {
Read
Prepared Statements in MySQLi
how to insert into mysql using Prepared Statement with php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My Form</title>
<meta name="description" content="An interactive form">
</head>
<body>
<form action="test.php" method="post" id="Personalinfo">
<label for="fname">Όνομα:</label>
<input type="text" id="fname" name="firstname" placeholder="Όνομα
Πελάτη..">
<input type="submit" name="submitForm" value="Submit">
</body>
</html>
**test.php file**
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submitForm'])){
$firstname = $_POST['firstname'];
$sql = "INSERT INTO Guests (firstname)
VALUES ('{$firstname}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}else{
echo "Are you sure you enter a firstname and the name of your html submit is submitForm";
}
$conn->close();
?>

MySQL - PHP - Access denied for user ''#'localhost' to database 'myproject'

I'm very new to PHP so please bear with me. I have a registration form and I'm submitting the values entered on that form and having them inserted into a MySQL Database table, but I'm getting the following error:
ErrorAccess denied for user ''#'localhost' to database 'myproject'
I've granted all the access that is possible to the user that I'm using in my code, but I'm still having this error. Any help is appreciated and points will be awarded!
Here is my HTML Form:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Registration Page</title>
<script>
function validateForm() {
var x = document.forms["myForm"]["netID"].value;
if (x == null || x == "") {
alert("NetID must be filled out");
return false;
}
var y = document.forms["myForm"]["email"].value;
if (y == null || y == "") {
alert("Email must be filled out");
return false;
}
var n = document.forms["myForm"]["fname"].value;
if (n == null || n == "") {
alert("First Name cannot be blank");
return false;
} else if (n.length < 2) {
alert("First name cannot be less than 2 characters!");
return false;
}
var b = document.forms["myForm"]["lname"].value;
if (b == null || b == "") {
alert("Last Name cannot be blank");
return false;
} else if (b.length < 2) {
alert("Last Name cannot b less than 2 characters!");
return false;
}
}
</script>
</head>
<body>
<ul>
<br>
<br>
<br>
<br>
<center><img src="KSUlogo.PNG" alt="logo" style="width:100px;height:50px;"></center>
<br>
<br>
<br>
<br>
<br>
<li><a class="active" href="#home">Home</a></li>
<br>
<br>
<br>
<br>
<li>News</li>
<br>
<br>
<br>
<br>
<li>Contact</li>
<br>
<br>
<br>
<br>
<li>About</li>
<br>
<br>
<br>
<br>
</ul>
<h1 style="text-align:center;">CCSE Community Profile Page</h1>
<br>
<br>
<br>
<br>
<br>
<h2 style="text-align:center;">Enter your Registration Information</h2>
<div style="text-align:center">
<form name="myForm" action="RegistrationValues.php"
onsubmit="return validateForm()" method="post">
<center>NetID: <input type="text" name="netID"></center>
<br>
<center>Email: <input type="text" name="email"></center>
<br>
<center>First Name: <input type="text" name="fname"></center>
<br>
<center>Last Name: <input type="text" name="lname"></center>
<br>
<br>
Services You Can Provide the CSE Community</center><br>
<br>
<input type="checkbox" name="radio" value="Java"> Java Tutoring<br>
<input type="checkbox" name="radio" value="Computer" checked> Computer Fixing<br>
<input type="checkbox" name="radio" value="PHP" checked> PHP Tutoring<br>
<br><br>
<select name="availabilty">
<option value="blank"></option>
<option value="Java">Morning</option>
<option value="Computer">Evening</option>
<option value="Service">Afternoon</option>
</select>
<br><br>
<center><input type="submit" value="Submit"></center>
</form>
</div>
</body>
</html>
Here is my PHP form:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Registration Page</title>
</head>
<body>
<?php include "header.html";?>
<?php include "navigation.html";?>
<div style="text-align:center">
<p>netID: <?php echo $_POST["netID"]?></p>
<p>Email: <?php echo $_POST["email"]?></p>
<p>First Name <?php echo $_POST["fname"]?></p>
<p>Last Name: <?php echo $_POST["lname"]?></p>
<?php
$netID = $email = $fname = $lname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$netID = test_input($_POST["netID"]);
$email = test_input($_POST["email"]);
$fname = test_input($_POST["fname"]);
$lname = test_input($_POST["lname"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "myUser";
$password = "newpassword";
$dbname = "myproject";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysql_select_db("$dbname") or die( 'Error'. mysql_error() );
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysql_query("insert into ProfileInformation (netID, email, fname, lname, radio, availabilty)
values
('$_POST[netID]','$_POST[email]','$_POST[fname]','$_POST[lname]','$_POST[radio]','$_POST[availabilty]')")
or die(mysql_error());
echo "Done!!!!";
$stmt->close();
$conn->close();
?>
</body>
</html>
It seems to be reading '' as a username somewhere but I'm not sure though.
Thanks in advance. It is greatly appreciated.
You need to pick one api and use it rather than mix n match - however, saying that it would be better to use prepared statements rather than embedding the $_POST variables directly in the sql. Incidentally the names within $_POST need to be quoted unless they exist as constants!
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$conn->query("insert into ProfileInformation (netID, email, fname, lname, radio, availabilty)
values
( '{$_POST['netID']}', '{$_POST['email']}', '{$_POST['fname']}', '{$_POST['lname']}', '{$_POST['radio']}', '{$_POST['availabilty']}' )") or die(mysql_error());
echo "Done!!!!";
$conn->close();
Now that you have the issue of the connection sorted ( btw - what was the issue? You should perhaps share the reason it was failing for future readers ) the sql you presented initially is vulnerable to sql injection. The preferred method would be to use a prepared statement like the following:
if( isset( $_POST['netID'], $_POST['email'], $_POST['fname'], $_POST['lname'], $_POST['radio'], $_POST['availabilty'] ) ) {
$host = 'localhost';
$uname = 'xxx';
$pwd = 'xxx';
$db = 'xxx';
$conn = new mysqli( $host, $uname, $pwd, $db );
if ( !$conn ) {
die("Connection failed: " . mysqli_connect_error() );
}
$sql='insert into `ProfileInformation` ( `netID`, `email`, `fname`, `lname`, `radio`, `availabilty` ) values ( ?,?,?,?,?,? );';
$stmt=$conn->prepare( $sql );
if( $stmt ){
$netid=$_POST['netID'];
$email=$_POST['email'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$radio=$_POST['radio'];
$avail=$_POST['availabilty'];
/*
use i for integers
use s for strings
*/
$stmt->bind_params( 'isssss', $netid,$email,$fname,$lname,$radio,$avail );
$result=$stmt? 'Success!' : 'Fail!';
$stmt->close();
$conn->close();
} else {
echo 'Error creating statement';
}
} else {
echo 'One or more required POST variables are not set';
}
check your phpmyadmin. The user myUser and password newpassword that you used i think this is not exists.go phpmyadmin->user Accounts and check.you can try to do this:-
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myproject";

Refresh a form after submission

I need to create a form that will check it fills; if true, refresh itself after submit button is clicked.
viewing.php post to be display in earliest submission first with timestamp in descending order.
I have this connected to my local database to store and display data entered.
I have tried every code from forums and youtube but nothing works.
Below is the code:
index.php:
<style rel="stylesheet" type="text/css">
body {
left:20px;
font-size:15pt;
}
label, input, textarea{
left:20px;
margin:5px 5px 5px 5px;
font-size:15pt;
}
div {
width:50%;
background-color:lightgrey;
}
</style>
</head>
<body>
<div> <!--id="auto"-->
<form name="ajax" action="insert.php" method="post" id="contact">
<br>
<label>Please Enter Your Comments :</label>
<br><br>
<label>Name :<span>*</span>
<input type="text" name="Name" id="Name" value="" placeholder="Name" autocomplete="off"/>
</label>
<br>
<label>Enter Your Wishes : <span>*</span>
<br>
<textarea name="Comment" rows="10" cols="30" id="Comment" placeholder="Message" autocomplete="off"></textarea>
</label>
<br>
<input type="submit" value="Submit" onclick="aa();"/>
<input type="reset" value="Clear"/>
</form>
</div>
<script type="text/javascript">
location.refresh(true);
$('#contact').submit(function () {
sendContactForm();
return false;
});
</script>
</body>
</html>
insert.php:
<?php
session_start();
require 'config.php';
if(isset($_POST['Name'], $_POST['Comment'])){
$fields = [
'Name' => $_POST['Name'],
'Comment' => $_POST['Comment']
];
foreach ($fields as $field => $data) {
if (empty($data)){
$errors[] = 'The '.$field . ' field is required.';
}
}
}
else {
$errors[] = 'Error.';
}
// This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
foreach ($params as &$var) {
// check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
unset($var);
}
}
// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);
$ID = $_POST['ID'];
$Name = $_POST['Name'];
$Comment = $_POST['Comment'];
/*$db_host = 'localhost:8889';
$db_username = 'root';
$db_password = 'root';
$db_name = 'Event';*/
mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name);
// search submission ID
$query = "SELECT * FROM 'demo' WHERE 'Name' = '$ID'";
$sqlsearch = mysql_query($query);
$resultcount = mysql_numrows($sqlsearch);
if ($resultcount > 0) {
mysql_query("UPDATE `demo` SET
`Name` = '$Name',
`Comment` = '$Comment',
WHERE `ID` = '$ID'")
or die(mysql_error());
} else {
mysql_query("INSERT INTO `demo` (ID, Name, Comment) VALUES ('$ID','$Name', '$Comment') ")
or die(mysql_error());
}
header('Location: index.php');
?>'
viewing.php:
<style rel="stylesheet" type="text/css">
body {
font-size:20pt;
}
</style>
<body>
<?php
require 'config.php';
$conn = mysqli_connect( $db_host, $db_username, $db_password, $db_name);
// Create connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Comment FROM demo";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//echo "<table><tr><th>Name</th><th>Comment</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "<tr><td>".$row["Name"]." ".$row["Comment"]."</td></tr>";
echo "<fieldset>From : ".$row["Name"]."<br>".$row["Comment"]."<br></fieldset><br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
config.php:
<?php
/*Configuration Settings*/
$db_username = 'root';
$db_password = 'root';
$db_name = 'Event';
$db_host = 'localhost';
$port = 8889;
$socket = 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock';
?>

Categories