php - Insert doesn't enter values to form - php

Hi guys i dont know what im doing wrong but my tables are correct, php error is on and it doesnt insert
I can get both first name and email echoed
<?php
if (isset($_POST['subs'])) {
function html_escape($html_escape) {
$html_escape = htmlspecialchars($html_escape, ENT_QUOTES | ENT_HTML5, 'UTF-8');
return $html_escape;
}
$name=html_escape($_POST['name']);
$email=html_escape($_POST['email']);
if (empty($name) || empty($email)) {echo"<div class='alert alert-danger'>Please enter both name and email address</div>";}
else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo"<div class='alert alert-danger'>Invalid email address, please enter a correct email address!</div>";
}
else {
echo "INSERT into subs (first_name, email) VALUES ('$name','$email')";
$insert=mysql_query("INSERT into subs (first_name, email) VALUES ('$name','$email')");
if ($insert) {echo"<div class='alert alert-success'>Thank you for subscribing with us</div>";}
}
}}
?>

first of all, are you connected to mysql before running your query?
$conn=mysql_connect('localhost', 'your_db_username', 'your_db_password');
if(!$conn){
die('Cannot connect to mysql');
}
mysql_select_db('your_db_name');
Then, when you're sure you're connected to the db and your query is still not working, add or die(mysql_error()) after your query like this, this will help you know what's going wrong with your insert:
$insert=mysql_query("INSERT into subs (first_name, email)
VALUES ('$name','$email')")
or die(mysql_error());

As a general point, using the PDO class is preferred, and may give you more information about what the problem is.
e.g.
$pdo = new \PDO('mysql:host=localhost;dbname=<database_name>', '<database_username>', '<database_password>');
$sql = "INSERT into subs (first_name, email) VALUES (:name,:email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$result = $stmt->execute();
This gives a lot of benefits. Take my word for it, or give "benefits of PDO" a quick Google.

$query = "INSERT INTO subs (first_name, email) VALUES ('" . $name . "','" . $email . "') ";
$insert = mysql_query($query);

Related

Inserting data into multiple different data tables

I was trying to insert data into multiple data tables. It's only working for single data tables, I'm just wondering how I would be able to insert data into two data tables. I've been struggling with this issue for the past few hours and can't seem to get to the bottom of it. If anyone has any advice please let me know. :)
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost","ivodatat","","");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Inputs for security
$fname = mysqli_real_escape_string($link, $_REQUEST['fname']);
$sname = mysqli_real_escape_string($link, $_REQUEST['sname']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$phone = mysqli_real_escape_string($link, $_REQUEST['phone']);
$mac = mysqli_real_escape_string($link, $_REQUEST['mac']);
$installer = mysqli_real_escape_string($link, $_REQUEST['installer']);
$status = mysqli_real_escape_string($link, $_REQUEST['status']);
// Insert Query
$sql1 = "INSERT INTO leadlist (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
$sql2 = "INSERT INTO $installer (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
if (mysqli_multi_query($link, $sql1, $sql2)){
mysqli_close($conn);
header("Location: installercontrol.php");
exit;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close The Connection
mysqli_close($link);
?>
To use mysqli_multi_query you need to append the queries to each other as it only takes one query argument. From the manual:
Executes one or multiple queries which are concatenated by a semicolon.
Try this instead:
mysqli_multi_query($link, $sql1 . ';' . $sql2)
You should probably also update your error message:
echo "ERROR: Could not able to execute $sql1;$sql2. " . mysqli_error($link);

Unable to insert data into MySQL database using PHP

I am unable to insert data into MySQL database. I do not know the reason since no error is triggered. I am using XAMPP on windows to run local server. Here is the code. It would be great if someone could help.
I am always getting "Values not inserted" output. I also tried printing the $query when I got exact values I entered through a form in the VALUES ('$email', ...) part of the SQL query.
<?php
$dbconnect = mysqli_connect("localhost","root","","id3626001_login_details");
if (!$dbconnect)
{
die("Connection Failed" .mysqli_connect_error());
}
if (!mysqli_select_db($dbconnect, "id3626001_login_details"))
{
echo "Could not connect to Database";
}
if (isset($_REQUEST['username']) && ($_SERVER["REQUEST_METHOD"] == "POST")){
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
// Inserting values into the database through a query
$query = "INSERT INTO user_registration (ID, email, username, password) VALUES ('$email', $username', '".md5($password)."')";
if (!mysqli_query($dbconnect, $query))
{
echo "Values not inserted";
}
$result = mysqli_query($dbconnect, $query);
if($result){
echo "Registration Successful";
}
}
?>
there is a problem in your query,
1) your column counts and count of values you are passing are not the same (must be same
2) you forgot to put ' (quote befor $username')
change your query to
// Inserting values into the database through a query
$query = "INSERT INTO user_registration ( email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
When you are testing you should not only print only query, you should also copy that query and run it directly into database through [(localhost/phpmyadmin)> select your databse > SQL ] and see what error are displaying there when firing a query.
UPDATE
for #Akintunde 's suggestion
for security concerns you should not be using these kind of insertion methods which is fully open to SQL injections you must follow some rule to avoid to get your script being target of sql injection
use Prepared Statements instead for database operations
Here in your query you forgot to put upper quote '-> $username',
$query = "INSERT INTO user_registration (email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
Here we are not passing Id as a param so you need to make id auto increment in database for that table.
and why are to passing your query twice into mysqli_query() you can check for once like,
$result = mysqli_query($dbconnect, $query);
if ($result)
{
echo "Registration Successful";
}
else{
echo "Values not inserted";
}

Inserting Multiple values into MySQL database using PHP

I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.

How to insert data into MySQL using MySQLi?

I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.

Input in database failure

I'm having trouble with the following code:
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$hash', '$lastname', '$email', '$email')";
mysqli_query($MyConnection, $sql);
if(!mysqli_query($MyConnection, $sql)) {
echo 'We are sorry, there are some problems with saving your data. Please try again within a few minutes.';
}
else {
echo 'We have succesfully saved your data. An activation e-mail will now be send to the e-mail address that you
have provided us.';
}
I get no direct errors as due to mistyping or misusing a function. I do get however the message of the if-statement in a failure, the "We are sorry(..)" text.
There must be a problem with the execution of the mysqli_query($MyConnection, $sql) function. But I don't see where it is.
P.S. I can't post images, because my reputation is below 10. (Which is quite weird to limit it to that point)
As some of you have provided most / all of the code:
<?php
// Opens the connection of the MySQL Database
$MyConnection = mysqli_connect('fdb6.biz.nf', '1446018_amp', '-')
or die("Could not connect to the database, please try again");
mysqli_select_db($MyConnection,'Users');
mysqli_connect_errno();
// Website Url:
$website = 'http://www.askmephilosophy.co.nf/';
// Information provided by the user
$username = $_POST['username'];
$password = $_POST['password']; // Will get encrypted.
$lastname = $_POST['lastname'];
$email = $_POST['email'];
// A higher "cost" is more secure but consumes more processing power
$cost = 5;
// Create a random salt
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
// Prefix information about the hash so PHP knows how to verify it later.
// "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter.
$salt = sprintf("$2a$%02d$", $cost) . $salt;
// Hash the password with the salt
$hash = crypt($password, $salt);
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$hash', '$lastname', '$email', '$email')";
mysqli_query($MyConnection, $sql);
var_dump(mysqli_error($MyConnection));
if(mysqli_query($MyConnection, $sql)) {
echo 'We have succesfully saved your data. An activation e-mail will now be send to the e-mail address that you
have provided us.';
}
else {
echo 'We are sorry, there are some problems with saving your data. Please try again within a few minutes.';
mysqli_error($MyConnection);
}
mysqli_close($MyConnection);
?>
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$hash', '$lastname', '$email')";
This is your first issue; your table has four columns, and you're passing it three. This query is guaranteed to fail.
mysqli_query($MyConnection, $sql);
if(!mysqli_query($MyConnection, $sql)) {
You're calling the query function twice. You can do this with a single call:
if(!mysqli_query($MyConnection, $sql)) {
// add some error handling code here
// store the return value of mysqli_error() somewhere
echo 'We are sorry, there ar....';
Since you're using mysqli_, you should also be using prepared statements; I hope at least you're sanitising the database inputs before you try to add them to the database.
Why do you only have 3 values, it doesn't match the number of items you are trying to Insert (4) ...
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$username', '$hash', '$lastname', '$email')";
EDIT:
I would probably write it like this
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
({$username}, {$hash}, {$lastname}, {$email})";
EDIT:
Your password cannot be '-'
I would update your connection info like so:
$db = new mysqli('fdb6.biz.nf', 'user', 'pass', 'Users');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
EDIT AGAIN:
$myConnection = new mysqli('fdb6.biz.nf', 'user', 'pass', '1446018_amp');
$myConnection->mysqli_select_db($MyConnection,'Users');
try adding, I think you forgot this. Values always have to equal to columns
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$username', '$hash', '$lastname', '$email')";
First of all you are inserting twice that records, as there are two instances of mysqli_query($MyConnection, $sql);. You can just remove the first.
The problem here is that you are inserting 3 values in 4 fields.
Anyway you can get the specific error with
mysqli_error($MyConnection);
Add it at the end your echo forever or var_dump(mysqli_error($MyConnection)); in a new line.

Categories