PHP Written out to screen when using PDO - php

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.

Related

SQL show row count in php

I got this little code with name telephone and mail data. I need to show count of people registered with php how can I do that? What should I add to the code?
<?php
$servername='localhost';
$username='1106428';
$password='';
$dbname = "1106428";
try {
$adsoyad = $_POST['adsoyad'];
$mail = $_POST['mail'];
$tel = $_POST['tel'];
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
/* set the PDO error mode to exception */
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO ufc3 (adsoyad,mail,tel)
VALUES ('$adsoyad', '$mail','$tel')";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
If you only use php form to add user, you car just make a Count with sql and you get the number but if you have 2 way or more to add user you can add a new variable to you database like addedfrom and you set it to php.

PHP script works on my local pc but not on my server

I have a simple PHP script, to take the data enter on a form and store it in mysql database. When I run it on my PC it enters the data correctly, but, when I run it from my online server it display my PHP script on a new page!
Here is my code:
<?php
$servername = "localhost";
$username = "theuser";
$password = "thepassword";
$dbname = "thedb";
$cName['c_name'] = isset($_POST['c_name']);
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO the_tb (c_name,c_reg,c_tel1,c_tel2,f_name,l_name,m_tel,email_addr1,email_addr2,p_addr1,p_addr2,p_city,p_county,p_code,p_country,contact_message,yes_no) VALUES ('$_POST[c_name]','$_POST[c_reg]','$_POST[c_tel1]','$_POST[c_tel2]','$_POST[f_name]','$_POST[l_name]','$_POST[m_tel]','$_POST[email_addr1]','$_POST[email_addr2]','$_POST[p_addr1]','$_POST[p_addr2]','$_POST[p_city]','$_POST[p_county]','$_POST[p_code]','$_POST[p_country]','$_POST[contact_message]','$_POST[yes_no]')";
// use exec() because no results are returned
$conn->exec($sql);
echo "'$_POST[c_name]','$_POST[c_reg]','$_POST[c_tel1]','$_POST[c_tel2]','$_POST[f_name]','$_POST[l_name]','$_POST[email_addr1]','$_POST[email_addr2]','$_POST[p_addr1]','$_POST[p_addr2]','$_POST[p_city]','$_POST[p_county]','$_POST[p_code]','$_POST[p_country]','$_POST[contact_message]','$_POST[yes_no]'.";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
As I said it works on my local workstation. Now I have checked that I have the same version on PHP installed as well as all the relevant modules and all seem to be the same.
I know that I have made a mistake somewhere but for the life of me I cannot see where. Could one you guys PHP expert can tell me where I went wrong?
Thank you kindly

Unable to update data in MySQL using PHP PDO Prepared

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.

Undefined property: PDO::$connect_error

I am trying to use $dbc->connect_error to check if any error occurs while trying to connect to my databease. I always get an error page saying:
Notice: Undefined property: PDO::$connect_error in
C:\xampp\htdocs\add_products_processing.php on line 7
I am using Windows7 with XAMPP v3.2.2. The full code is shown below. I am sure that the username and the password are correct. Any advice?
<?php
$dsn = 'mysql:host=localhost;dbname=technoglance';
$username = 'root';
$password = 'password';
$dbc = new PDO($dsn, $username, $password);
if ($dbc->connect_error) {
die("Connection failed: " . $dbc->connect_error);
}
$main_class =filter_input(INPUT_POST, 'main_class');
$brand =filter_input(INPUT_POST, 'brand');
$model =filter_input(INPUT_POST, 'model');
$description =filter_input(INPUT_POST, 'description');
$quantity =filter_input(INPUT_POST, 'quantity');
$adding_date =filter_input(INPUT_POST, 'adding_date');
$sell_price =filter_input(INPUT_POST, 'sell_price');
$buying_price =filter_input(INPUT_POST, 'buying_price');
if(!empty($main_class)){
try{
$query = "INSERT INTO products (main_class, brand, model, description, quantity, adding_date, sell_price, buying_price ) VALUES ('$main_class', '$brand', '$model', '$description', '$quantity', now(),'$sell_price', '$buying_price' );";
// set the PDO error mode to exception
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbc->exec($query);
echo "Thank you. The record has been sent successfully.<br><br>";
}
catch(PDOException $e){
echo $query . "<br>" . $e->getMessage()."<br><br>";
}
}
else{
echo '<h1>Please use the contact form or don\'t leave an empty field!</h1>';
}
?>
Here is what your code should be
<?php
$dsn = 'mysql:host=localhost;dbname=technoglance;charset=utf8';
$username = 'root';
$password = 'password';
$dbc = new PDO($dsn, $username, $password);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// filtering omitted
if(!empty($main_class)){
$query = "INSERT INTO products (main_class, brand, model, description, quantity, adding_date, sell_price, buying_price ) VALUES (?,?,?,?,?,?,?,?);";
$data = [$main_class,$brand,$model,$description,$quantity,$adding_date,$sell_price,$buying_price];
$dbc->prepare($query)->execute($data);
echo "Thank you. The record has been sent successfully.<br><br>";}
else{
echo '<h1>Please use the contact form or don\'t leave an empty field!</h1>';
}
PDO will report it's errors already, without any extra code required.
and you should be using prepared statements
If we have a look at the PDO manual and look up for the PDO class there is no connect_error property anywhere. But if we check mysqli manual we see it right there. You have to choose a database library and stick to it, they cannot be mixed.
I always recommend to configure PDO to throw exceptions as you already do (although connection errors in particular will always through an exception no matter your settings) and not care to catch them unless you want to do something specific with them.
There is no connect_error. You should use exception:
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Or if you do not want exception you can try errorCode and errorInfo

How to fix server error 500 when executing PHP script?

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.

Categories