PHP is not sending values to database using a simple form - php

Hello I am using PHPStorm and I am trying to send data to my database using php.
When the form is submitted my database creates a new id which is set to auto-increment but the values are empty!
This is my html form in a file called create_account.php
<!DOCTYPE>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>NABI| Find the perfect music teach today!</title>
<link rel="stylesheet" href="css/normalize.css">
<meta name="viewport" content="width=device-width, initial-scale =1.0, user-scalable=no">
</head>
<body>
<form method="post" action="info.php">
<input type="text" name="name" id="name">
<input type="submit" value="send">
</form>
</body>
</html>
Here is my info.php file
<?php
$host = "localhost";
$user = "root";
$db = "nabi_data";
$pass = "";
$name = filter_input(INPUT_POST, 'name');
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO just_name (name)
VALUES ('$name')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
This is how my database table looks like
just_name

If you put an echo, Does It return the name value?
....
Try to get name field content with $_POST['name'];

To avoid the "undefined index" error, you may want to do something like this:
if ($_POST and !empty($_POST['name'])) {
$host = "localhost";
$user = "root";
$db = "nabi_data";
$pass = "";
$name = filter_input(INPUT_POST, 'name');
// debugging step to check to see what you're getting back from the filter_input call (or write it to a log)
var_dump($name); exit;
if ($name != '') {
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO just_name (name) VALUES ('$name')";
$conn->exec($sql);
echo "New record created successfully";
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
else {
// filtered name was blank; raise an error and/or redirect them to create_account.php
}
$conn = null;
}
else {
// handle this case; maybe just redirect back to create_account.php
}
The biggest key is to check that "name" exists in the $_POST (also accessible through the $_REQUEST global variable); you can do that through isset() or empty().
(And yes, as others have suggested, checking the value you get in $name after the filter_input call would be a great thing to verify if you haven't already.)

"Thank you #Parene but this is what I get when I set $name = $_POST['name']; ---Notice: Undefined index: name in C:\Users\Vanessa\PhpstormProjects\nabi\info.php on line 6--- – Vanessa Charles 5 mins ago"
$name = filter_input(INPUT_POST, 'name'); you're getting undefined index because you're not checking if it's empty or not.
You need to use a conditional statement for it while checking if it's "empty".
$name = filter_input(INPUT_POST, 'name');
if(!empty($name)){
// do something as in "enter" it in the database
$name = $name;
$sql = "INSERT INTO just_name (name)
VALUES ('$name')";
// ... rest of your query here
}
Edit:
Modify your code to read as this and copy/paste it exactly as show and reload it while clearing your cache.
I also added ticks to the name column, sometimes that helps.
<?php
$host = "localhost";
$user = "root";
$db = "nabi_data";
$pass = "";
if(!empty($_POST['name'])){
$name = $_POST['name'];
}
else {
echo "Something went wrong.";
}
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO just_name (`name`) VALUES ('$name')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
A prepared statement should be used for this though.
http://php.net/pdo.prepared-statements
I.e. as a prepared statement:
<?php
$host = "localhost";
$user = "root";
$db = "nabi_data";
$pass = "";
if(!empty($_POST['name'])){
$name = $_POST['name'];
}
else {
echo "Something went wrong.";
}
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO just_name (`name`) VALUES (:name)");
$stmt->bindParam(':name', $name);
$stmt->execute();
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

The issue is you're using PhpStorm built-in web server which has issues with POST.
As of PHP 5.4.0, the CLI SAPI provides a built-in web server, try using that by selecting "PHP Built-in Web Server" type of Run/Debug Configuration.
Or try this manually:
cd ~/www/your_project
php -S localhost:8000
Here's the manual page

Related

Data not inserting into database when using pdo

i am learning pdo and i tried to play with CRUD method. I am trying to insert data into database using pdo but it isn't inserting. Below is my code
<?php
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT ));
try {
$query = $connect->prepare("INSERT INTO users(username, password) VALUES(?,?)");
$query->execute(array($username, $password));
echo "data";
}
catch (PDOException $event) {
echo $event->getMessage();
}
?>
i have this index file named as index.php
<?php
require_once 'db.php';
session_start();
session_regenerate_id();
?>
<!DOCTYPE html>
<html>
<head>
<title>Sign-Up/Login Form</title>
</head>
<?php
if ($_SERVER['REQUEST_METHOD'] == '$_POST') {
if (isset($_POST['login'])) {
require 'login.php';
}
elseif (isset($_POST['register'])) {
require 'register.php';
}
}
?>
<body>
<form action="index.php" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="register" value="Submit">
</form>
</body>
</html>
my db.php looks like
<?php
try {
$connect = new PDO('mysql:dbname=pdologin;host=localhost', 'root', '$$$$');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $event) {
$event->getMessage();
}
?>
The problem is that your code never reaches your require scripts (login.php or register.php) because your conditional is incorrect.
You have: if ($_SERVER['REQUEST_METHOD'] == '$_POST')
It should be if ($_SERVER['REQUEST_METHOD'] == 'POST')
You're going to end up with something like below while learning or doing some small script that will need a connection, in the long run wrapping this stuff in a function or using a small helper or framework can make this a little easy. Great idea to learn but its still tedious boiler plate no matter how many years you write this stuff.
<?php
//db settings that are typically in a config somewhere
$db_servername = "localhost";
$db_username = "username for your database";
$db_password = "password for your database";
$db_name = "your_db_name";
try {
$connect = new PDO("mysql:host=$db_servername;dbname=$db_name, $db_username, $db_password");
// set the PDO error mode to exception
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
}catch(PDOException $e){
//echo "Connection failed: " . $e->getMessage();
}
$sth = $connect->prepare("INSERT INTO users(username, password) VALUES(:username,:password)");
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT );
$sth->bindValue(':username', $username, PDO::PARAM_STR);
$sth->bindValue(':password', $password, PDO::PARAM_STR);
$sth->execute();
as a example my team now just writes database binding code like
<?php
//array of ids to insert
$binds['ids'] = array(1,3,4,5,6,7,9,08098);
//Database class is auto included with every script
$success = Database::query('insert into my_table (id) values(:ids)',$binds);
connect first
$connect = mysqli_connect("localhost","root","root","my_db");
then remove the parameters when executing
$query->execute();
try this
<?php
$connect = mysqli_connect("localhost","root","root","my_db");
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT );
try {
$query = $connect->prepare("INSERT INTO users(username, password) VALUES('$username', '$password')");
$query->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}
?>

Updating data in DataBase with PHP

I have a simple script that should Update variable in a column where user login equals some login.
<?PHP
$login = $_POST['login'];
$column= $_POST['column'];
$number = $_POST['number'];
$link = mysqli_connect("localhost", "id3008526_root", "12345", "id3008526_test");
$ins = mysqli_query($link, "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'");
if ($ins)
die ("TRUE");
else
die ("FALSE");
?>
but it doesn't work. It gives me - FALSE. One of my columns name is w1 and if I replace '$column' in the code with w1 it works fine. Any suggestions?
Simply remove quotes: '$column' = should be $column =
Your code is open for SQL Injection, use prepared statements.
change this "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'"
to this "UPDATE test_table SET '".$column."' = ".$number." WHERE log = '".$login."'"
It's possible that your error is to do with the $column being set as a string with single quotation marks? Because it returns false, it suggests that you have a MySQL error of some sort.
To find out what the error message is, on your else block, rather than dying with a "FALSE" message, try use mysqli_error($link) - this should give you your error message
If removing the quotes surrounding the $column doesn't work, you could try the PDO method. Here's the snippet:
function insertUser($column, $number, $login) {
try
{
$connect = getConnection(); //db connection
$sql = "UPDATE test_table SET $column = '$number' WHERE log = '$login'";
$connect->exec($sql);
$connect = null;
} catch (Exception $ex) {
echo "EXCEPTION : Insert failed : " . $ex->getMessage();
}
}
function getConnection() {
$servername = "localhost";
$dbname = "my_db";
$username = "root";
$password = "12345";
try {
$connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo "EXCEPTION: Connection failed : " . $ex->getMessage();
}
return $connection;
}
Regarding $number, I'm not sure the datatype for the $number whether quotes or not is needed so experiment with or without quotes to see which one works.
And the getConnection() function is in separate PHP file where it will be included in any PHP files that calls for database connection.

I am trying to add some data in database using PHP, but it does not work

This is my PHP code starting and used connection type is PDO.
//connection with server
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=gujaratoil", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['submit']))
{
//at the beginning null value is set
$name = $emailaddress="";
$sql = "INSERT INTO
registration(name,emailaddress)VALUES('$_POST[name]','$_POST[emailaddre
ss]')";
}
?>
I have tried all the solutions available; what should I do to solve this issue? I am using a PDO connection.
When using PDO you should use prepared statements rather than directly embedding variables in the SQL.
The reason, I believe, given the code above why the insert was failing was / is due to the lack of quotes around field names within $_POST[] ~ ie $_POST[name] which is likely to be causing undeclared constant errors
$name=$_POST['name'];
$email=$_POSt['emailaddress'];
$sql='insert into `registration` ( `name`, `emailaddress` ) values ( :name, :email )';
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bindParam(':name',$name);
$stmt->bindParam(':email',$email);
$stmt->execute();
}

Separate connection from PDO

I am new to PDO. I try to understand.
What is the best way to separate the connection from the rest with PDO?
For instance. I have this code that works well:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully <br>";
$sql = "SELECT podcast, text
FROM bookmarks
WHERE data = :data";
$statement = $conn->prepare($sql);
$data = 1;
$statement->bindValue(':data', $data);
$statement->execute();
echo $statement->rowCount() . " records SELECTED successfully <br>";
$rows = $statement->fetchAll();
foreach($rows as $row){
echo $row['podcast'] . '<br>';
echo $row['text'] . '<br>';
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
It could be useful to have the connection in a separate file. I tried that and it works well but I am not sure if it is the best way to do it. Is it ok to have the try-catch only with the connection?
index.php:
include("includes/connetion.php")
$sql = "SELECT podcast, text
FROM bookmarks
WHERE data = :data";
$statement = $conn->prepare($sql);
$data = 1;
$statement->bindValue(':data', $data);
$statement->execute();
echo $statement->rowCount() . " records SELECTED successfully <br>";
$rows = $statement->fetchAll();
foreach($rows as $row){
echo $row['podcast'] . '<br>';
echo $row['text'] . '<br>';
}
$conn = null;
connection.php:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// $conn = new PDO("sqlite:/Applications/MAMP/db/sqlite/podcast", $username, $password); //Lite
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully <br>";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I tried that and it works well but I am not sure if it is the best way to do it.
As long as your code is a usual spaghetti as shown above, it's all right with include.
Is it ok to have the try-catch only with the connection?
quite contrary, there shouldn't be a try catch with the connection as well:
"Catch an exception only if you have a handling scenario other than just reporting it. Otherwise just let it bubble up to a site-wide handler (note that you don't have to write one, there is a basic built-in handler in PHP, which is quite good)."
If you are trying to catch possible exception you have to do it everywhere you communicate with database. So you have to wrap try-catch also around code which ask database for some data.
Another step is to separate concepts of getting data from database representing them (sending them to output as you do it). You can check some MVC concept - how to do it.

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

Categories