I have a variable called $message which outputs the message contents when an action is performed to give the user some feedback however I keep getting an undefined variable error from PHP.
It's really weird because sometimes it works fine and other times it just returns the error message. Can anyone tell me what I'm doing wrong.
Just to confirm, this is a variable which is purely for storing messages. This isn't something which is "POSTED' from a form. Its generated within the PHP file itself.
An example of its usage:
<?php
session_start();
include "../includes/db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_SESSION['username'];
$sql = $db_conx->prepare("SELECT username, user_record_id FROM login_details
WHERE username = :username");
$sql->bindParam(':username', $username, PDO::PARAM_STR);
$sql->execute();
$user_record_id = $sql->fetchColumn(1);
$proposal = $_POST['proposal_id'];
$insertRec = $db_conx->prepare("INSERT INTO student_saved (proposal_id, user_record_id) VALUES (:proposal, :user_record_id)");
$insertRec->bindParam(':user_record_id', $user_record_id, PDO::PARAM_STR);
$insertRec->bindParam(':proposal', $proposal, PDO::PARAM_STR);
$insertRec->execute();
$message = "<p class='text-success'> Proposal Added To Your Favourites <span class='glyphicon glyphicon-ok'/></p>";
}
catch(Exception $e)
{
if( $e->getCode() == 23000)
{
$message = 'This proposal has already been saved to your favourites';
}
else
{
$message = $e->getMessage();
}
}
die($message);
?>
Any help would be much appreciated!
Related
Having trouble find a PHP script to helps users to get authenticated into a form using already existing credentials database, tried several scripts but everyone of them seems to get stuck on the same code $sth->execute(array("uname" => $_POST["username"], "upass" => $encryptedpassword));. For the record, we already have an existing credentials database used to for another web application, for testing purpose I've created a dummy database with plain text users' credentials, see next.
<?php
$encryptedpassword = md5($_POST['password']);
$db_myHost = "SERVERNAME";
$db_myUser= "sa";
$db_myPassword = "PASWORD";
$db_myDatabase = "DATABASE"
$dbconn = new PDO("sqlsrv:server=$db_myHost;Database=$db_myDatabase",$db_myUser,$db_myPassword);
try
{
$dbPDO = new PDO('sqlsrv:server='.$db_myHost.';Database='.$db_myDatabase, $db_myUser, $db_myPassword);
$dbPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo "Error!: " . $e->getMessage() . "
";
die();
}
//Check user credentials
$sth = $dbconn->prepare("SELECT * FROM wblgntst WHERE uname = :username AND upass = :password");
//CODE CAUSING ISSUE
$sth->execute(array("uname" => $_POST["username"], "upass" => $encryptedpassword));
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
session_start();
$_SESSION['userName'] = $row['uname'];
header("Location: list.php");
}
?>
ERROR
PHP Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid
parameter number: parameter was not defined in
C:\inetpub\wwwroot\salesportal\php\login.php on line 28
Stopped looking for some scripts, found the real solution: Zubrag.com
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.
i have a problem with the realization of a registration form. My php script should check if the user email is already in use.
if the email is in use the php script should show an error message, if it is not the registration is successfully completed.
$email = $_POST['email'];
try{
$sql = "SELECT count(mail) FROM user WHERE mail = '$email'";
$result = $pdo->exec($sql);
}catch(PDOException $e){
echo $e;
exit(); }
if($result == 0){
//registration complete }
else{
//email already in use }
my problem is that i obtain always 0 as result also if the email is already inside the database. But if i execute that sql code inside my xampp' server i obtain 1 so the code works perfectly.
Thank you to all for help :)
You need to do this:
$email = $_POST['email'];
try{
$sql = "SELECT mail FROM user WHERE mail = :email";
$sql = $pdo->prepare($sql);
$sql->execute(array(':email'=> $email));
}catch(PDOException $e){
echo $e;
exit(); }
if($sql->rowCount() == 0){
//registration complete }
else{
//email already in use }
I converted my login page to use PDO but now it's not working. I've run through all kinds of code examples and I can't figure out where I'm going wrong. This looks perfect to me. Also error reporting is fully enabled and yet I don't get any errors. I just get the browser error for the page being "incorrectly configured". FYI, this is a SQL db
//Code
<?php
require ("../Android/connect_db.php");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$query_unpw = $db->prepare("
SELECT member_mast.company_name
FROM member_mast
WHERE username = ?
AND password = ?
");
//$username = $_POST['username'];
//$password = $_POST['password'];
$username = 'abc';
$password = 'abc';
$name = "name";
$query_unpw->bindValue(1, $username, PDO::PARAM_STR);
$query_unpw->bindValue(2, $password, PDO::PARAM_STR);
$query_unpw->execute();
$count = $query_unpw->rowCount();
if ($count > 0) {
while ($row = $query_unpw->$fetch(PDO::FETCH_ASSOC)) {
$name = $row['company_name'];
}
echo $name;
} else {
echo "Username/Password is invalid";
}
} catch(PDOException $e) {
die($e->getMessage());
}
?>
Now the only thing I've been able to figure out after commenting out different pieces of code is that if I comment out the username and password, like this
//$username = 'abc';
//$password = 'abc';
Then the page loads and just gives me my else echo of "Username/Password is invalid". However I don't think I'm using them wrong and I know they are correct. So the obvious question is am I blind, what's wrong here? The bonus question is, since I will be using _POST for these variables when this works, am I properly sanitizing the user inputs? Still really new to PDO and I want to make sure I'm doing this right. Thanks for the help!
Problem is here:
$query_unpw->$fetch
It must be:
$query_unpw->fetch()
It's a method, so skip that $ sign.
I suggest you to use ini_set('display_errors', "On") while developing.
Have a look through the code below. This is supposed to check whether or not a database contains a given user. If the it does, it just returns true. If it doesn't, then it returns false.
Anyway, regardless of the user and password existing in the database, for some reason it will not evaluate to true! ! !
function databaseContainsUser($email, $password)
{
include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
try
{
$sql = 'SELECT COUNT(*) FROM wl_user
WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute("USE $dbname");
}
catch (PDOException $e)
{
$error = 'Error searching for user. ' . $e->getMessage();
include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
exit();
}
$row = $s->fetch(PDO::FETCH_NUM);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
Any help would be appreciated
For some unknown reason you are passing "USE $dbname" string to execute.
remove that string.
Also, you are trying to catch an exception but apparently don't tell PDO to throw them.
And you are catching it only to echo a message, which is a big no-no.
I've explained the right way recently in this answer
If your problem is different, you have to ask (or better - google for this very problem).
Refer to PDO tag wiki for the proper connect options including database selection and error reporting.
Try this
try
{
$pdo = new PDO('mysql:host=localhost;dbname=yourDbName;', 'root', '',
array(PDO::ATTR_PERSISTENT => true));
$sql = 'SELECT count(*) FROM user WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute();
}
This is local server example, just change yourDbName to your db name. I just run this code on my local server and it is working.