Sending Variables to MySQLi - php

i have been staring at this page for half an hour trying to figure out where i am going wrong. The first two variables are found and inserted into database, however the last two, 'email' and 'password' are not found, not inserted into database but still however pass the if statement. Any help will be much appreciated.
Form.php
<form name="signup" method="POST" action="signup.php">
<label for="signupFirstName">First Name</label>
<input type="text" id="signupFirstName" name="signupFirstName" />
<label for="signupLastName">Last Name</label>
<input type="text" id="signupLastName" name="signupLastName"/>
<label for="signupEmail">Email</label>
<input type="text" id="signupEmail" name="signupEmail" />
<label for="signupConfirmEmail">Confirm Email</label>
<input type="text" id="signupConfirmEmail" name="signupConfirmEmail"/>
<label for="signupPassword">Password</label>
<input type="text" id="signupPassword" name="signupPassword"/>
<label for="signupConfirmPassword">Confirm Password</label>
<input type="text" id="signupConfirmPassword" name="signupConfirmPassword"/>
<button name="submit" type="submit" >Submit Form</button>
</form>
signup.php
<?php
if (isset($_POST['signupFirstName']) || isset($_POST['signupLastName']) || isset($_POST['signupEmail']) || isset($_POST['signupPassword']) ) {
echo $_POST['signupEmail'];
$mysqli = new mysqli('localhost', 'user1', 'password', 'db2');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO members (First_Name, Last_Name, Email, Password) VALUES (?,?,?,?)");
$stmt->bind_param('ssss',$sample,$lastName,$email,$password);
// escape the POST data for added protection
$sample = isset($_POST['signupFirstName'])
? $mysqli->real_escape_string($_POST['signupFirstName'])
: '';
$lastName = isset($_POST['signupLastName'])
? $mysqli->real_escape_string($_POST['signupLastName'])
: '';
$email = isset($_POST['signupEmail'])
? $mysqli->real_escape_string($_POST['signupEmail'])
: '';
$password = isset($_POST['signupPassword'])
? $mysqli->real_escape_string($_POST['signupPassword'])
: '';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
}
else{
echo "broken";
}
?>

You seem to be binding the params to your query before you actually set the variables. Move the bind_param() call above the execute() call.
You can also refactor your code to take out a lot of the junk. Example below:
<?php
function arr_get($array, $key) {
if (isset($array[$key])) {
return $array[$key];
}
return '';
}
if (isset($_POST['signupFirstName']) || isset($_POST['signupLastName']) || isset($_POST['signupEmail']) || isset($_POST['signupPassword']) ) {
echo $_POST['signupEmail'];
$mysqli = new mysqli('localhost', 'user1', 'password', 'db2');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO members (First_Name, Last_Name, Email, Password) VALUES (?,?,?,?)");
$stmt->bind_param('ssss', arr_get($_POST, 'signupFirstName'), arr_get($_POST, 'signupLastName'), arr_get($_POST, 'signupEmail'), arr_get($_POST, 'signupPassword'));
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
}
else {
echo "broken";
}
?>

Related

PHP Form No Errors Not Inserting

I have a form, below, that was working for a while, however for some reason the code has now stopped inserting what the user would input via the form. Once the form was working, the only things I changed were the style, and nothing on the database site, or with the insertion of the data.
I get zero errors when I hit the Submit button, and it takes me to the page that I want the form to take the user too.
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="name" id="Name">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="email">
</p>
<input type="submit" value="Submit">
and my PHP code is:
<?php
$link = mysqli_connect("localhost", "root", "root", "travelsite");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_REQUEST['name']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
// attempt insert query execution
$sql = "INSERT INTO subscribe (name, email) VALUES ('$name', '$email')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Try using $_POST['name'] and $_POST['email'].
Also as mentioned on the comments: you got your variables mixed up. (thx #NitinP)
Try also using a prepare statement like:
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "INSERT INTO subscribe (name, email) VALUES (?, ?)")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $name, $email); /*or $first_name*/
/* execute query */
mysqli_stmt_execute($stmt);
printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));
/* close statement */
mysqli_stmt_close($stmt);
}
For more information see the link under Procedural style

The PHP linked to this form isn't submitting entries to my database

I have a form on a website I'm working on which needs to submit information to a MySQL database. I'm primarily a web designer, and PHP is somewhat new to me. I've written this PHP code as the action for my HTML form, which is below:
<?php
//only process if $_POST isn't empty
if ( ! empty( $_POST ) ){
//connect to mysql
$mysqli = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
//check connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
//insert data
$sql = ("
INSERT INTO `table` (`ID`, `u_fname`, `u_lname`, `u_email`)
VALUES (NULL, '{$mysqli->real_escape_string($_POST['u_fname'])}', '{$mysqli->real_escape_string($_POST['u_lname'])}', {$mysqli->real_escape_string($_POST['u_email'])}')");
$insert = $mysqli->query($sql);
//print response from sql
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_id}";
}
else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
//close connection
$mysqli->close();
}
?>
The relevant HTML form is here:
<div class="form-container">
<form action="signupform.php" method="post" class="isubmit" name="signup" onsubmit="swal({
type: 'success',
title: 'Thanks!',
showConfirmButton: false,
timer: 1500
})">
<input required type="text" name="u_fname" class="first-name" placeholder="First Name">
<input required type="text" name="u_lname" class="last-name" placeholder="Last Name">
<input required type="text" name="u_email" class="email" placeholder="Email">
<button class="isubmit submit-text" type="submit">submit</button>
</form>
</div>
The HTML and PHP files are separate but in the same directory. I'm aware the PHP needs to be made more secure to avoid injection, but that is not my issue. The issue is that when the submit button is pressed, the PHP does not send the entries to my database. The database remains unchanged, and what I need is for the information from the form fields to populate the database table when the user hits the submit button on the HTML form. Any help with my code or suggestions of a better method would be greatly appreciated.
Remove the mysqli_real_escape_string from your string in your query and set a variable to equal your post value. Your 'id' also needs to be removed from the insert as the ID in your database should be an auto increment. Added in an error validation and prepared statement to help prevent sql injection.
//insert data
<?php
if(!empty($_POST)) {
if(isset($_POST['submit'])){
//connect to mysql
$mysqli = mysqli_connect( 'localhost', 'user', 'pass', 'dbname' );
//check connection
if (!$mysqli) {
die( 'Connect Error: ' . mysqli_error());
}
$u_fname = mysqli_real_escape_string($mysqli, $_POST['u_fname']);
$u_lname = mysqli_real_escape_string($mysqli, $_POST['u_lname']);
$u_email = mysqli_real_escape_string($mysqli, $_POST['u_email']);
//VALIDATION ARRAY
$error = [
"u_fname"=> '',
"u_lname"=> '',
"u_email"=> ''
];
if($u_fname == '') {
$error['u_fname'] = "Please Enter Your First Name";
}
if($u_lname == '') {
$error['u_fname'] = "Please Enter Your Last Name";
}
if($u_email == '') {
$error['u_fname'] = "Please Enter Your Email";
}
else {
//IF NO ERRORS INSERT DATA
$stmt = mysqli_prepare($mysqli, "INSERT INTO `table` (`u_fname`, `u_lname`, `u_email`) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sss', $u_fname, $u_lname, $u_email);
mysqli_stmt_execute($stmt);
//print response from sql
if ($stmt ) {
echo "Success!";
}
else {
die("Error" . mysqli_error());
}
//close connection
mysqli_close($mysqli);
}
}
}
?>
And for the Form
<div class="form-container">
<form action="signupform.php" method="post" class="isubmit" name="signup">
<input required type="text" name="u_fname" class="first-name" placeholder="First Name">
<span><?php echo isset($error['u_fname']) ? $error['u_fname'] : ''?></span>
<input required type="text" name="u_lname" class="last-name" placeholder="Last Name">
<span><?php echo isset($error['u_lname']) ? $error['u_lname'] : ''?></span>
<input required type="text" name="u_email" class="email" placeholder="Email">
<span><?php echo isset($error['u_email']) ? $error['u_email'] : ''?></span>
<button class="isubmit submit-text" type="submit" name="submit">submit</button>
</form>
</div>

Form data into database using PHP

I've created a HTML form that inserts user data into a database using MySQL and PHP.
HTML form:
<form action="index.php" method="POST" >
<div class="container">
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" id="username" name="username" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="psw" name="psw" required>
<label for="email"><b>Email address</b></label>
<input type="text" placeholder="Email address" id="email" name="email" required>
<input type="submit" value="Submit" name="Submit">
</div>
</form>
index.php:
// Create connection
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Could not connect to MySQL: ' .mysqli_connect_error());
if(isset($_POST['Submit'])) {
$USER = (isset($_POST['username']) ? $_POST['username'] : null);
$PASSWORD = (isset($_POST['psw']) ? $_POST['psw'] : null);
$EMAIL = (isset($_POST['email']) ? $_POST['email'] : null);
$stmt = $dbc->prepare("INSERT INTO webapp_db.users (username, password, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $USER, $PASSWORD, $EMAIL);
$stmt->execute();
echo "New records created successfully";
} else{
die('Error: '.mysqli_error($dbc));
}
$stmt->close();
$dbc->close();
And I don't get any errors. It says: "New records created successfully" but nothing has been created
Any idea where the problem is? Thank you in advance
Try wrapping the checks into isset() statements like so:
// Create connection
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die('Could not connect to MySQL: ' .mysqli_connect_error());
if(isset($_POST['Submit'])) {
$USER = (isset($_POST['username']) ? $_POST['username'] : null);
$PASSWORD = (isset($_POST['psw']) ? $_POST['psw'] : null);
$EMAIL = (isset($_POST['email']) ? $_POST['email'] : null);
$stmt = $dbc->prepare("INSERT INTO webapp_db.users (username, password, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $USER, $PASSWORD, $EMAIL);
$stmt->execute();
echo "New records created successfully";
} else{
die('Error: '.mysqli_error($dbc));
}
$stmt->close();
$dbc->close();
Ok, remember that execute function returns a boolean. Try to check if the query were executed with success or not:
$executed = $stmt->execute();
if ($executed == true) { // or just "if ($executed) {" if you prefer
echo "New records created successfully";
} else {
echo "Oops! Something went wrong";
}
But if you need something more precise, ... try with errorInfo function, that returns an array.
if ($executed == 1) {
echo "New records created successfully";
} else {
print_r($stmt->errorInfo());
}

Trying to post only one single column into database

Here is my code that inserts data into a database table, but I want grab data and display it inside those div below:
<?php
// only proccss the form if $_POST isn't empty
if ( ! empty( $_POST ) ) {
// connect to MySQL
$mysqli = new mysqli( 'localhost', 'root', '', 'mydb' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// insert our data
$sql = "INSERT INTO table1 ( name, email ) VALUES ('{$mysqli->real_escape_string($_POST['name'])}', '{$mysqli->real_escape_string($_POST['email'])}' )";
$insert = $mysqli->query($sql);
// print response from MySQL
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_id}";
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
// close our connection
$mysqli->close();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input name="name" type="text">
<input name="email" type="email">
<input type="submit" value="Add">
</form>
Display each name and email here like:
<div class="name">Get Name Here from Database</div><div class="email">Get Email Here from Database</div>
The code above works on posting but I want to make it like, whenever I go to same page it must display that data rom database below the form.
Try to use binds variables and prepared statements:
<?php
$mysqli = new mysqli("localhost", "user", "pass", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST['scriptname'])) {
$scriptname = $_POST['scriptname'];
$stmt = $mysqli->prepare("INSERT INTO appslist(listall) VALUES (?)");
$stmt->bind_param('s', $scriptname);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Script Name: <input type="text" name="scriptname">
<input type="submit">
</form>
Ouput:
1 Row inserted.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Getting a thrown exception error when trying to update db

I created a page where I can edit user information. I am only performing a prepared statement off of one db table called 'users' and in the users db table I have a column called group where I can assign users different permission levels. I am outputting the current data for the user I selected onto this page, so if a user has a group level of 1, in the option field it will show 1. I then have 4 other options which I list the other values at 2, 3, 4, and 5. Whenever I try to submit the form I am getting an exception error from my user class "There was a problem updating!". There update function is below where the exception error is...
public function update($fields = array(), $id = null) {
if(!$id && $this->isLoggedIn()) {
$id = $this->data()->id;
}
if(!$this->_db->update('users', $id, $fields)) {
throw new Exception('There was a problem updating!');
}
}
I believe my prepared statement and form is sound other than possibly the group option area. I want the current group number to be displayed in the option box and if I do not need to update it, I want to be able to click submit and not have any issues and I want to be able to update the group integer.
This is the part I am not sure if it is correct or enabling me to do this..
<div class="field">
<label for="group">Group</label>
<select name="group" required>
<option value=''><?php echo htmlentities($group); ?></option>
<option value="1">Bench</option>
<option value="2">Spectator</option>
<option value="3">Team Member</option>
<option value="4">Commissioner</option>
<option value="5">Creator</option>
</select>
</div>
Here is my prepared statement and form...
<?php
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("SELECT firstname, lastname, email, username, `group` FROM users WHERE id = ?");
if ( false===$stmt ) {
// Check Errors for prepare
die('prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param("i", $_GET['id']);
if ( false===$stmt ) {
// Check errors for binding parameters
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
if ( false===$stmt ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
//Check errors for execute
//if(!$stmt->execute()){trigger_error("there was an error....".$con->error, E_USER_WARNING);}
$stmt->bind_result($firstname, $lastname, $email, $username, $group);
$stmt->store_result();
if ($stmt->fetch()) { ?>
<form action="" method="post">
<div class="field">
<label for="firstname">First Name</label>
<input type="text" name="firstname" class="inputbar" value="<?php echo htmlentities($firstname); ?>" required>
</div>
<div class="field">
<label for="lastname">Last Name</label>
<input type="text" name="lastname" class="inputbar" value="<?php echo htmlentities($lastname); ?>" required>
</div>
<div class="field">
<label for="email">Email</label>
<input type="email" class="inputbaremail" name="email" value="<?php echo htmlentities($email); ?>" required>
</div>
<div class="field">
<label for="username">Username</label>
<input type="text" class="inputbar" name="username" value="<?php echo htmlentities($username); ?>" required>
</div>
<div class="field">
<label for="group">Group</label>
<select name="group" required>
<option value=''><?php echo htmlentities($group); ?></option>
<option value="1">Bench</option>
<option value="2">Spectator</option>
<option value="3">Team Member</option>
<option value="4">Commissioner</option>
<option value="5">Creator</option>
<!--<input type="text" class="inputbar" name="group" value="<?php //echo htmlentities($group); ?>" required>-->
</select>
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<label for="signinButton">
<input type="submit" id="signinButton" value="Update">
</label>
</form>
<?php } else { ?>
User <?php echo htmlentities($_GET['id']); ?> not found.
<?
} ?>
Does anyone see anything that would be preventing this to go through?
UPDATE:
public function update($fields = array(), $id = null) {
if(!$id && $this->isLoggedIn()) {
$id = $this->data()->id;
}
echo $this->_db->update('users', $id, $fields);
}
//if(!$this->_db->update('users', $id, $fields)) {
//throw new Exception('There was a problem updating!');
//}
//if(!$this->_db->update('users', $id, $fields)) {
// throw new Exception('There was a problem updating!')->getMessage();
//}
//}
NEW CODE WITH INSERT PREPARED STATEMENT ADDED. STILL NOT SENDING
if(isset($_POST['submit'])){
$firstname = Input::get('firstname');
$lastname = Input::get('lastname');
$email = Input::get('email');
$username = Input::get('username');
$group = 1;
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt2 = $con->prepare("INSERT INTO users (firstname, lastname, email, username, `group`) VALUES (?, ?, ?, ?, ?");
if ( false===$stmt2 ) {
// Check Errors for prepare
die('User Request prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt2->bind_param('sssssi', $firstname, $lastname, $email, $username, $group);
if ( false===$stmt2 ) {
// Check errors for binding parameters
die('User Request bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
$stmt2->execute();
if ( false===$stmt2 ) {
die('User Request execute() failed: ' . htmlspecialchars($stmt2->error));
}
}
//Prepared statement that gets user info
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("SELECT firstname, lastname, email, username, `group` FROM users WHERE id = ?");
if ( false===$stmt ) {
// Check Errors for prepare
die('prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param("i", $_GET['id']);
if ( false===$stmt ) {
// Check errors for binding parameters
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
if ( false===$stmt ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
//Check errors for execute
//if(!$stmt->execute()){trigger_error("there was an error....".$con->error, E_USER_WARNING);}
$stmt->bind_result($firstname, $lastname, $email, $username, $group);
$stmt->store_result();
if ($stmt->fetch()) { ?>
Trying to use try/catch...
public function update($fields = array(), $id = null) {
if(!$id && $this->isLoggedIn()) {
$id = $this->data()->id;
}
//echo $this->_db->update('users', $id, $fields);
//if(!$this->_db->update('users', $id, $fields)) {
//throw new Exception('There was a problem updating!');
//}
try {
if(!$this->_db->update('users', $id, $fields)) {
throw new Exception('There was a problem updating!');
}
}
catch(Exception $e) {
echo "An error occurred";
throw $e;
}
finally {
//This overrides the exception as if it were never thrown
return "\nException erased";
}
try {
echo asdf();
}
catch(Exception $e) {
echo "\nResult: " . $e->getMessage();
}
I get this error..
An error occurred
Warning: Cannot modify header information - headers already sent by (output started at /home4/db/public_html/example.com/classes/User.php:46) in /home4/db/public_html/example.com/classes/Redirect.php on line 14
Line 45 of my user class is this..
echo "An error occurred";

Categories