Connecting mysql database using PDO in external PHP file [duplicate] - php

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
I have an Index.php which has a form for fetching user details when that form is submitted it fires the data to a new program.php for validation in program.php I've linked db.php in which I've the connection to the database, code of db.php is given below:
<?php
$link=mysql_connect('localhost', 'root', '') or die ("mysql_connect_error()");
$dbselect=mysql_select_db('test',$link) or die ("Error while connecting the database");
?>
since using it this way sql injections are possible, so I tried changing it to code given below:
<?php
$hostname='localhost';
$username='root';
$password='';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=test",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
but I am getting an error when I connect submit the form. Inside my program.php I have called db.php by include "db.php";. Since I am new to PDO, I am not sure where am I going wrong.
Updated program.php code
<?php
if($_POST)
{
include "link_db.php";
if ($_POST[admin_sign_up])
{
$fname=$_POST[fname];
$lname=$_POST[lname];
$id =$_POST[id];
$id_pass=$_POST[id_pass];
$sql="insert into admin_database(fname, lname, id, id_pass)
value ('$fname','$lname','$id','$id_pass')";
mysql_query($sql);
$error=mysql_error();
if(empty($error))
{
echo "<script>alert('Registration Successful...')</script>";
header("Location:index.php",true);
}
else
{
echo "Registration Failed...<br> Email Id already in use<br>";
echo "<a href='failed.php'>Click to SignUp again</a>";
}
}
if ($_POST[admin_login])
{
$id =$_POST[id];
$id_pass=$_POST[id_pass];
$sql="select * from admin_database where id = '$id' and id_pass= '$id_pass'";
$result=mysql_query($sql);
echo mysql_error();
$row=mysql_fetch_array($result);
$rowcnt=mysql_num_rows($result);
if($rowcnt==1)
{
session_start();
$_SESSION['id']=$id;
$_SESSION['fname']=$row['fname'];
$_SESSION['lname']=$row['lname'];
$_SESSION['varn']="Y";
echo "Login Successfully....";
header("Location:home.php",true);
}
else
{
$id =$_POST[id];
$id_pass=$_POST[id_pass];
$sql="insert into adminfailure(id, id_pass, date_time)
value ('$id','$id_pass',NOW())";
mysql_query($sql);
$error=mysql_error();
if(empty($error))
{
Echo "Invalid Login ID or Password....";
header("Location:fail.php",true);
}
else
{
echo "incorrect details";
}
}
}
if ($_POST[logout])
{
header("location:destroy.php",true);
}
}
?>
Updated Errors which I get
Notice: Use of undefined constant test_sign_up - assumed 'test_sign_up' in B:\XAMPP\htdocs\test\program.php on line 6
Notice: Undefined index: test_sign_up in B:\XAMPP\htdocs\test\program.php on line 6
Notice: Use of undefined constant test_login - assumed 'test_login' in B:\XAMPP\htdocs\test\program.php on line 32
Notice: Use of undefined constant id - assumed 'id' in B:\XAMPP\htdocs\test\program.php on line 35
Notice: Use of undefined constant id_pass - assumed 'id_pass' in B:\XAMPP\htdocs\test\program.php on line 36
No database selected
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in B:\XAMPP\htdocs\test\program.php on line 41
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in B:\XAMPP\htdocs\test\program.php on line 42
Notice: Use of undefined constant id - assumed 'id' in B:\XAMPP\htdocs\test\program.php on line 56
Notice: Use of undefined constant id_pass - assumed 'id_pass' in B:\XAMPP\htdocs\test\program.php on line 57
incorrect details
Notice: Use of undefined constant logout - assumed 'logout' in B:\XAMPP\htdocs\test\program.php on line 73
Notice: Undefined index: logout in B:\XAMPP\htdocs\test\program.php on line 73

In your code, you first create a connection to the database, then you set it to null.
Whenever you try to access the $dbh object after that, it will be null.
$dbh = new PDO("mysql:host=$hostname;dbname=test",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh = null; // <= Right here.
Remove the $dbh = null; line, and you should be able to use the object as intended.
The $dbh object it not just a "link" as you do in your mysql_* code, but it is a object that you use to call the database, this is not the same object that you use in your mysql_* calls.
i.e., You can not use the earlier mysql_* code and just pass the pdo object into the call instead of the mysql link.
So the code will differ a bit from your earlier code.
Example:
// Earlier code using `mysql_* API`:
$sql="select * from admin_database where id = '$id' and id_pass= '$id_pass'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// Would look something like this using PDO:
$statement = $dbh->prepare('SELECT * FROM admin_database WHERE id =:id AND id_pass =:idpass');
// Here you can either use the bindParam method, or pass the params right into the execute call:
$statement->execute(array('id' => $id, 'idpass' => $id_pass);
$row = $statement->fetch();
I'd recommend reading up on PDO in the docs if you have issues with converting the code.
Further recommendations:
When you are including a file like this, one you only want to be included once per script run, its always a good idea to make sure that it is only included once. This can be done by using the include_once keyword instead of just include. Now, if you use include, this will include the script if possible, if it cant, it will keep run the script, and the script will crash when you try to use the varaiables set in the file.
Instead of using include in this case, I would recommend using the require (or rather require_once) keyword. Which will include the file, and if it cant, stop execution of the script and display an error message (if you have error reporting on).

You have to change not only db.php but ALL the queries over your code. And always use prepared statements to pass variables to queries. Otherwise PDO won't protect you from injections.
At the moment I am writing tutorial on PDO, it is still incomplete but can give you basics you may start from.

Related

ILLEGAL & UNINITIALIZED string offset error [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Illegal string offset Warning PHP
(17 answers)
Closed 5 years ago.
I'm having trouble fixing my errors, the functions are working fine but i need to get rid of the errors
i have this following errors:
Warning: Illegal string offset 'userID' in C:\xampp\htdocs\checkout.php on line 15
Notice: Uninitialized string offset: 0 in C:\xampp\htdocs\checkout.php on line 15
Fatal error: Call to a member function fetch_assoc() on boolean in C:\xampp\htdocs\checkout.php on line 19
and heres my code:
CHECKOUT.PHP
<?php
// include database configuration file
include 'dbConfig.php';
include 'login.php';
// initializ shopping cart class
include 'Cart.php';
$cart = new Cart;
// redirect to home if cart is empty
if($cart->total_items() <= 0){
header("Location: index.php");
}
// set customer ID in session
$_SESSION['sessCustomerID'] = $sessData['userID']; //this is the ID for the logged in user
// get customer details by session customer ID
$query = $db->query("SELECT * FROM users WHERE id =".$_SESSION['sessCustomerID']);
$custRow = $query->fetch_assoc();
?>
LOGIN.PHP
<?php
session_start();
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
if(!empty($sessData['status']['msg'])){
$statusMsg = $sessData['status']['msg'];
$statusMsgType = $sessData['status']['type'];
unset($_SESSION['sessData']['status']);
}
?>
<div class="container">
<?php
if(!empty($sessData['userLoggedIn']) && !empty($sessData['userID'])){
include 'user.php';
$user = new User();
$conditions['where'] = array(
'id' => $sessData['userID'],
);
$conditions['return_type'] = 'single';
$userData = $user->getRows($conditions);
?>
DBCONFIG.PHP
<?php
//DB details
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'dbblair';
//Create connection and select DB
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($db->connect_error) {
die("Unable to connect database: " . $db->connect_error);
}
?>
Line 15:
$_SESSION['sessCustomerID'] = $sessData['userID'];
Both error messages that refer to this line are very clear.
Warning: Illegal string offset 'userID' in C:\xampp\htdocs\checkout.php on line 15
$sessData is a string (this is what the error says and line #3 of login.php confirms this statement).
Individual string characters can be accessed using the square bracket syntax (similar to arrays) but the offset must be an integer. The offset is a string in your code, and this is what the error says (a string is not a legal value for the offset).
Notice: Uninitialized string offset: 0 in C:\xampp\htdocs\checkout.php on line 15
Because it expects an integer for the offset and you use a string instead, the interpreter converts the string to number and the result is 0. The message says that the offset 0 does not exist in the string (and this is correct, as $sessData is ''). As a result, $_SESSION['sessCustomerID'] is initialized with the empty string.
For PHP the two messages above are just a warning and a notice (i.e. the script can continue) but in fact they reveal a serious error in your code.
The string offset and the way you use $sessData in login.php tell that $sessData must always be an array. It's unexplainable why do you set it to an empty string. Line #3 of login.php should read:
$sessData = !empty($_SESSION['sessData']) ? $_SESSION['sessData'] : array();
Lines 18 and 19:
$query = $db->query("SELECT * FROM users WHERE id =".$_SESSION['sessCustomerID']);
$custRow = $query->fetch_assoc();
The error:
Fatal error: Call to a member function fetch_assoc() on boolean in C:\xampp\htdocs\checkout.php on line 19
Information about this error was asked and answered dozen of times on [so]. I won't repeat the answer here.
mysqli::query() returns
FALSE when the query has syntax errors or refers to object that does not exist in the database. In this case, the query ends with WHERE id= because $_SESSION['sessCustomerID'] is empty, as explained above.
But $_SESSION['sessCustomerID'] is still empty on the first page load, even if you fix the initialization of $sessData. Apart from using prepared statements (see the linked answer for details), you should not issue a query to the database if you know in advance you won't get any result (this happens when $_SESSION['sessCustomerID'] is empty).

mysql database search remote host or page name [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 5 years ago.
The purpose of my lab is to have the user search through a database called "pageVistis" from what they enter in the field. They can search through the remote host or page name. I have Been having trouble fixing an error that i am recieving saying "Notice: Undefined variable: searchtype in C:\xampp\htdocs\pageVisitsLab\DataBC.php on line 23
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in C:\xampp\htdocs\pageVisitsLab\DataBC.php:25 Stack trace: #0 {main} thrown in C:\xampp\htdocs\pageVisitsLab\DataBC.php on line 25". Also the code is form a file called "DataBC.php". If any extra information is needed please let me know and i will edit this post and include it thank you.
include "interface.php";
if(isset($_POST['submit'])) {
$sName = $_POST['sN'];
$sHost = trim($_POST['sH']);
if(!$sName || ! $sHost) {
echo "<p> Please enter a search </p>";
exit;
}
/*switch ($sName) {
case 'sName':
case 'sHost':
break;
default:
echo "<p> Invalid search type and please try again </p>";
}
*/
$query = "SELECT page_name, visit_date, previous_page, request_method, remote_host, remote_port FROM visitInfo
WHERE $searchtype= ?";
$stmt = $databse -> prepare($query);
$stmt-> bind_param('s',$sName);
$stmt-> execute();
$stmt->store_result();
$stmt->bind_result($pageName,$visitDate,$previouPage,$requestMethod,$remoteHost,$remotePort);
echo "<p> The number of items found: .$stmt->num_rows</p>";
while ($stmt->fetch()) {
echo "<p><strong>page Name: ".$pageName."</strong></p>";
echo "Visit Date: ".$visitDate."<br>";
echo "Previous Page: ".$previouPage. "<br>";
echo " Request Method: ".$requestMethod. "<br>";
echo "Remote Host: ".$remoteHost. "<br>";
echo "Remote Port: ".$remotePort. "<br>";
}
$stmt->free_result();
$databse->close();
}
?>
I think your problem is in your query, is $searchtype a variable you define in php? maybe in that interface.php.
If you want to use a php variable in a mysql query then that is not the correct way of doing it.

Undefined Variable PHP + MySQL [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I know stackoverflow disapproves of repeat questions, but bear with me as I have scanned many similar questions without finding specific resolutions that will help me. (Mostly they mention things about avoiding database insertions)
I encounter these error messages:
here db connection success
Notice: Undefined variable: firstname in C:\xampp\htdocs\practice_connection_app\submit.php on line 10
Notice: Undefined variable: lastname in C:\xampp\htdocs\practice_connection_app\submit.php on line 10
Notice: Undefined variable: conn in C:\xampp\htdocs\practice_connection_app\submit.php on line 11
Fatal error: Call to a member function exec() on null in C:\xampp\htdocs\practice_connection_app\submit.php on line 11
The first result simply shows that I have connected to my database which I made using phpMyadmin.
Here is my relevant code (my html submission page which calls on a php action):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>student info</title>
</head>
<body>
<br>
Enter your first name and last name in the corresponding boxes.
<br>
<form action="submit.php" method="POST">
First: <input type="text" name="firstname"/>
<br>
Last: <input type="text" name="lastname"/>
<br>
<input type="submit">
</form>
</body>
</html>
the database connection (I think)
<?php
echo 'here';
$dsn = 'mysql:host=localhost;dbname=practice_students';
$username = 'test_usr';
$password = 'pa55word';
try {
$db = new PDO($dsn, $username, $password);
echo 'db connection success';
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
AND my php submit page
<?php
echo 'here ';
$dsn = 'mysql:host=localhost;dbname=practice_students';
try {
$db = new PDO($dsn);
echo 'db connection success';
$sql = "INSERT INTO people (firstname, lastname)
VALUES ('$firstname', '$lastname')";
$conn->exec($sql);
echo "Now we know your name! Hi," . " " . $firstname . " " . $lastname;
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
I understand that I may need to do some 'cleaning up' to avoid database insertions, but for now I would just like to know how I can ensure my submissions are going to the database and can be returned.
Thanks in advance!
Not sure which manual you ahve been reading to end up with that code....
You need to access your POST variables (using $_POST['firstname']) AFTER sanitizing them of course....
EDIT:
To access the POSTed variable, you can do the following:
$firstname = $_POST['firstname'];
But you really need some santization going on, you could use php's filter_var:
$firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
Though, you can do better than that, and be very strict in what you allow through your filters / sanitizers... Please go investigate this part after you get your code "working" :)

How do I solve the "Undefined variable" error on php [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
login.php
<?php
function login()
{
$con = mysqli_connect("localhost", "XXX", "XXX") or die('Could not connect to server');
mysqli_select_db('$con', "store") or die('Could not connect to database');
}
?>
validate.php
Line 10 - ERROR - Notice: Undefined variable: con in C:\wamp\www\store\admin\validate.php
Line 10 - Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\wamp\www\store\admin\validate.php
Line 12 - Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\wamp\www\store\admin\validate.php
<?php
session_start();
include ("../mylibrary/login.php");
login();
$userid = $_POST['userid'];
$password = $_POST['password'];
$query = "SELECT userid, name from admins where userid = '$userid' and password = PASSWORD('$password')";
$result = mysqli_query($con, $query); (**Line 10)
if (mysqli_num_rows($result) == 0)(**Line 12)
{
echo "<h5>Sorry, your account was not validated.</h5><br>\n";
echo "Try again<br>\n";
} else
{
$_SESSION['store_admin'] = $userid;
header("Location: admin.php");
}
?>
I tried to figure out something wrong. Let me know thanks.
See this
mysqli_select_db('$con'
^ ^
Variable don't get parsed in single quotes.
Either remove them or use double " quotes.
Note: Make sure that all your POST arrays contain values and that the form you're using is indeed using a POST method and elements hold their respective name attributes.
You're also open to an SQL injection here.
Use a prepared statement.
References:
https://en.wikipedia.org/wiki/SQL_injection
https://en.wikipedia.org/wiki/Prepared_statement
Also consider using password_hash() to store your passwords:
http://php.net/manual/en/function.password-hash.php (Read the entire manual).
You are mixing up local and global variables.
$con is not available outside the login function.
If you add global $con; as the first line of the login function, its available outside of the function as well.
Have a look at the php manual: http://php.net/manual/en/language.variables.scope.php
PS: While its not the source of the problem, read Fred's answer too.

database connection error fatal errors

having an issue with connecting to my DB (been a long long day) - so anyway I am creating a simple search query into my DB but getting scripting errors - so here is my code:
<?php
mysqli_connect("localhost", "my username", "my password");
mysqli_select_db("smudged");
$search = mysqli_real_escape_string(trim($_POST['searchterm']));
$find_image = mysqli_query("SELECT * FROM 'smd_images' WHERE 'img_description' LIKE'%$search%'");
while($row = mysqli_fetch_assoc($find_image))
{
$name = $row['name'];
echo "$name";
}
?>
Here is my error:
search.php on line 4 Warning: mysql_select_db(): A link to the server could not be established in /marble/search.php on line 4 Fatal error: Call to undefined function mysql_real_escape_sring() in /marble/search.php on line 6
Typo. Instead of mysql_real_escape_sring() you probably meant mysql_real_escape_string()

Categories