I am trying to insert into a database through PHP. However, when I connect to the PHP file I get server 500 error. Would anyone be able to spot what I am doing wrong?
<?php
include 'db-security.php';
function db_login()
{
$userName = filter_input(INPUT_POST, "userName");
$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$statement = $link->prepare("INSERT INTO user(username, password)
VALUES($userName, $password)");
//execute the sql statement.
$statement->execute();
}
db_login();
?>
Updated:
I have discovered the error occurs when i add filer_input or $_post to the php.
<?php
include 'db-security.php';
function db_login() {
global $conn;
// use my eaxmple to filter input to get the data out of the form, because security.
//$userName = filter_input(INPUT_POST, "userName");
$userName = $_POST['userName'];
$password = $_POST['password'];
//$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$stmt = $conn->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
//execute the sql statement.
}
db_login();
?>
db-security.php
<?php
include_once 'conf.php';
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $conn;
// Try and connect to the database, if a connection has not been established yet
if(!isset($conn)) {
// Load configuration as an array. Use the actual location of your configuration file
try
{
$conn = new PDO("mysql:host=localhost;port=3307;dbname=database", DB_USERNAME,DB_PASSWORD);
// stores the outcome of the connection into a class variable
$db_msg = 'Connected to database';
}
catch(PDOException $e)
{
$conn = -1;
$db_msg = $e->getMessage();
}
//$conn = new PDO(DB_HOST,DB_USERNAME,DB_PASSWORD , MAIN_DB);
}
}
db_connect();
?>
Where is $link defined? In 'db-security.php'? If yes then you have a variable scope problem. Just pass $link in the function call. This would have to be done for all functions.
define function as = function db_login($link)
call function like = db_login($link);
EDIT:
Don't use a function for 'db-security.php' it should be like this:
<?php
$conn = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>
This is not complete code, just a sample. Now $conn is in the global variable scope and using global in the functions will work. Or just pass $conn to the function and not use global at all.
EDIT2:
Below are the working sample scripts. You need to change some information to match your setup. I'm not sure why the function is called db_login() since the function actually adds the user/password into the 'user' table.
conf.php
<?php
define('DB_USERNAME', 'test');
define('DB_PASSWORD', '123456');
?>
db-security.php
<?php
include_once 'conf.php';
try
{
$conn = new pdo("mysql:host=localhost; dbname=test; charset=utf8", DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
die('Unable to connect to database!');
}
?>
main script
<?php
include 'db-security.php';
function db_login()
{
global $conn;
$userName = $_POST['userName'];
$password = $_POST['password'];
$stmt = $conn->prepare("INSERT INTO user(username, password) VALUES(:usrname, :pswd)");
$stmt->bindParam(':usrname', $userName);
$stmt->bindParam(':pswd', $password);
$stmt->execute();
}
db_login();
?>
So you need to bind your parameters after prepare statement
$stmt = $link->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
I have been looking at your code and I would advice you to try a different approach. I've been wrapping my head around this subject for a while when learning PHP. Best advice i've had is that you can best try when fetching information from the DB is using a try/catch statement everytime. Sounds annoying or problematic but it easy to overlook and well written maintained code because you know every try catch block will execute or catch the error atleast.
With PDO being one of the best solutions because it can connect with multiple databases the best way to execute getting information from the Database is this:*
I am gonna give you my example of something i wrote. I don't want to write it all out in your situation because i feel that's something you can better do to learn what went wrong and i hope this gives you a step in the right direction.
database.php
$serverName = "";
$dbName = "";
$userName = "";
$password = "";
try {
$db = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password);
// Set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
}
catch(PDOException $e){
echo"Connection failed: " . $e->getMessage();
exit;
}
?>
index.php Executing a simple commmand get firstName from employers
<?php
require_once 'database.php';
try
{
$sQuery = "
SELECT
firstName
FROM
employees
";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
while($aRow = $oStmt->fetch(PDO::FETCH_ASSOC))
{
echo $aRow['firstName'].'<br />';
}
}
catch(PDOException $e)
{
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
?>
Good luck and i hope my index.php is helpful in showing you how I find is the best way momentarily to talk to the database.
Related
I created a function to connect to the db in php:
function fn_connect($is_write = false)
{
$host = '127.0.0.1';
$db = 'name_db';
if ($is_write) {
$user = 'user_write';
$pwd = 'password_write';
} else {
$user = 'user_read';
$pwd = 'password_read';
}
$conn = new mysqli($host, $user, $pwd, $db);
if ($conn->connect_error) {
die('The database is not available. Please, try again later.');
}
return $conn;
}
When I need to connect, im calling it (and closing it) like this
$conn = fn_connect(true);
$stmt = $conn->prepare($q);
$stmt->execute();
....
$stmt->close();
$conn->close();
I thought it will be a good idea to verify if the connection exists, that way, I guess, I save connecting to the db every time for nothing, like this:
if (!isset($conn)) $conn = fn_connect(true);
$stmt = $conn->prepare($q);
$stmt->execute();
....
$stmt->close();
if (isset($conn)) $conn->close();
Is this a good idea, a good practice? Should I jut connect normally and let Apache/PHP do the rest (no need to verify nothing)?
It is good practiose and good style to check the connection, before letting php try to get or send data.
What is not good style is to use die in your connection, because it leaves a broken page.
Better is to design the page so that page still works when the connection is broken.
i'm currently using mysqli procedure to write code which i want to change it in pdo because in mysqli i'm mysqli_escape_string whereas i dont how to change it in pdo
here is my mysqli attempt
<?php
if(isset($_GET['id1'])){
$id=$_GET['id1'];
$result=GetWordsById(mysqli_escape_string($conn,$id));//Here GetWordsById is a function calling store procedure
if(mysqli_num_rows($result)>0)
$row=mysqli_fetch_array($result);
$word=$row['word'];
$meaning=$row['meaning'];
$synonym=$row['synonym'];
$antonym=$row['antonym'];
}
?>
below is my function.php
function GetWordsByID($id){
include("conn.php");
$result=mysqli_query($conn,"CALL GetWordsById($id)");//Here GetWordsById is my store procedure
return $result;
}
Here i want to know how i can change both function and main php script calling function where i'm using mysqli_escape_string to pdo i'd appreciate some help
To PDO,
your db connection file will look like this,
<?
$servername = "localhost";
$username = "username"; // Enter your db username
$password = "password"; // Enter your db password
$dbname = "myDBPDO"; // Enter your db name
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $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();
}
?>
Now comes your code,
<?
if(isset($_GET['id1'])){
$id=$_GET['id1'];
$result=GetWordsById($id);//Here GetWordsById is a function calling store procedure
if($result->fetchColumn()>0){
$row=$result->fetch(PDO::FETCH_ASSOC);
$word=$row['word'];
$meaning=$row['meaning'];
$synonym=$row['synonym'];
$antonym=$row['antonym'];
}
}
and function,
function GetWordsByID($id){
include("conn.php");
$result=$conn->prepare(" ");//Here sql statement
$result->execute();
return $result;
}
This is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=site", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("UPDATE site_users SET users_email_verified = :users_email_verified WHERE users_email = :users_email ");
$stmt->bindParam(':users_email_verified', $users_email_verified,PDO::PARAM_STR);
$stmt->bindParam(':users_email',$_GET["email"],PDO::PARAM_STR);
$users_email_verified = "yes";
$stmt->execute();
echo "done";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
But it does not update the record.
But If I write the email directly inside $user_email variable (manually), like this
$users_email = "xyz#example.com";
Then the code works.
I do not understand why? How to fix it?
You have set the binding to be INTEGERS instead of STRINGS here:
$stmt->bindParam(':users_email_verified', $users_email_verified,PDO::PARAM_INT);
$stmt->bindParam(':users_email',$_GET["email"],PDO::PARAM_INT);
You should use PDO::PARAM_STR instead.
It also appear that you're not reporting errors, so you should check your web server's error logs for additional information.
I am having issues trying to insert information into the database. When I run the database connection in a different file it works fine on its own. But when I do the ->prepare it writes the PHP, starting from that point, out to the screen. Then I moved my PDO connection to the register.php file. That didn't help either. The only thing that changed is that now it writes out the PHP to screen from ->setAttribute onwards.
Here is the PHP code I use in register.php:
<?php
//include '../database_connect/connect.php';
PDO::getAvailableDrivers();
$db = new PDO('mysql:host=127.0.0.1;dbname=local_db', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$dob = $_POST['dob'];
//$_POST['day'] . $_POST['month'] . $_POST['year'];
//$final_dob = date('d-m-Y', strtotime($dob));
try {
$sql_query = 'INSERT INTO user_data (username, password, email, first_name, last_name) VALUES (?,?,?,?,?)';
$query = $db->prepare($sql_query);
} catch (PDOException $e)
echo $e->getMessage();
?>
This is what I used in the commented connect.php and it didn't write PHP out to the browser.
<?php
// Get available driver, check if it's installed
//print_r(PDO::getAvailableDrivers());
$db = new PDO('mysql:host=127.0.0.1;dbname=local_db', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*try {
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
} */
?>
I know that the password is not hashed, but this problem hit me before starting to work that out.
I found the problem. I don't know the reason, but when I pressed the submit button in my index.php, it redirected me to E://{file_path} and not localhost/{file_path}. Now it is running okay. Thanks for everybody's help.
EDIT: The problem is that the errors are not being displayed. This is just to clarify everyting.
I just learned what a PDO is, and I decided to test how it works. From the tutorials I've checked, you have to use the following line to display errors: $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
So anyways, I used this line, made sure that my query had an error and it still didn't display any errors. The connection to the database works, it always returned me an error when it couldn't connect. Anyways, here my code:
<?php
// Connection to the mysql database using PDO
$mysql_host = "hidden";
$mysql_dbname = "hidden";
$mysql_username = "hidden";
$mysql_password = "hidden";
try {
$DBH = new PDO("mysql:host=$mysql_host;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->prepare("SELECT username FROM username");
} catch (PDOException $e) {
echo "Error connecting to the database:" . $e->getMessage();
}
?>
You don't get any errors because
$DBH->prepare("DELETE use FROM blob");
doesn't execute, only prepares a query to be executed.
Replace that line of code with:
$stmt = $DBH->prepare("DELETE use FROM blob");
$stmt->execute();
You need to execute it
$stmt = $DBH->prepare("DELETE use FROM blob");
$stmt->execute();
Otherwise it doesn't actually run the query.