This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
I am new to PDO, and i am currently trying to convert all of my mysql_query's to PDO-> and I keep getting an error of an undefined variable $db
here is my code for the Database connection page:
$host = "localhost";
$user = "root";
$password = "";
$dbname = "XXXX";
global $db;
$db = new PDO("mysql:host=$host;dbname=$dbname;charset=UTF8", $user, $password);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Edit: my register function that is having problems
<?php
###########################
# #
# Database Authentication #
# #
###########################
require('Database.php');
require('Bcrypt.php');
require('Session.php');
function register($username, $password, $email){
if($username != null && $email != null && $password != null){
/*
$check = $database->prepare("SELECT * FROM users WHERE Username = '$username' OR Email = '$email'");
$sql = $check->execute();
if(count($check) > 0){
echo "The username or email address you entered is already in use, please try another combination";
}
I currently have this commented out to test the INSERT query below
*/
if(true){
$salt = create_salt($username);
$password = hash_pass($password, $salt);
$query = $db->prepare("INSERT INTO users (Username, Password, Email) VALUES('$username', '$password', '$email')");
$query->execute();
return true;
}
else{
echo "Something went wrong with inserting into table";
return false;
}
}
else{
echo "Please fill in all of the information in order to register";
return false;
}
}
When running this i get
Notice: Undefined variable: db in ...\Authentication.php on line 33
You need to move the global $db; statement from where it is into the function scope.
See "Example #1 Using global" here.
A quick fix would be to pass your $db into the function register so it will be available inside this functions scope. Make sure you drop the global keyword from your $db variable first, and you will need to update any other scripts using the function register() and pass in the $db variable:
function register($username, $password, $email, $db){
//now you will have $db available inside this scope
Hope this helps, however as a sidenote this is rather clunky and you should probably focus on setting up your application to use classes instead.
You seem to be declaring $db as global before it has been declared.
Related
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
I am a beginner, and just took a few lessons from this youtube course:
https://www.youtube.com/watch?v=TSX72_O7QYY&index=116&list=PL442FA2C127377F07
I have written this code.
<?php
$db_host = 'localhost';
$db_username = 'root';
$db_password = 'awesome11';
$db_connError = '<br>Cannot connect<br>';
$db_connConf = '<br>Connect to db<br>';
$db_name = 'codelib';
$db_table = 'codes';
$db_conn = mysqli_connect($db_host,$db_username,$db_password,$db_name);
if($db_conn){
mysqli_select_db($db_conn,$db_table);
echo $db_connConf;
}else{
echo $db_connError;
}
$query = "SELECT 'id' FROM `codes'";
if($run = mysqli_query($db_conn,$query)){
echo 'query is ok';
}else{
echo 'query failed';
}
?>
The function mysqli_connect() works fine. But msqli_query() does not work. It always says that query failed.
Besides msqli_query(), the simple msqli() also never works!
I cannot even create a variable like this one:
$mysqli = new mysqli($db_host,$db_username,$db_password,$db_name)
You have a typo in your query line, change the following:
$query = "SELECT 'id' FROM `codes'";
to this:
$query = "SELECT `id` FROM `codes`";
You used a single quote (') instead of reverse quote (`)
I'm having a problem connecting to mysql database in XAMPP. It always takes time to load this segment of php code. What might be the problem?
<?php
session_start();
//redirect function
function returnheader($location){
$returnheader = header("location: $location");
return $returnheader;
}
$connection = mysqli_connect("localhost:85","root","") OR die(mysqli_error());
$db_select = mysqli_select_db("pts",$connection) OR die(mysqli_error());
$errors = array();
if(isset($_POST["iebugaround"])){
//lets fetch posted details
$uname = trim(htmlentities($_POST['uname']));
$passw = trim(htmlentities($_POST['psw']));
//check username is present
if(empty($uname)){
//let echo error message
$errors[] = "Please input a username";
}
//check password was present
if(empty($passw)){
//let echo error message
$errors[] = "Please input a password";
}
if(!$errors){
//encrypt the password
$passw = sha1($passw);
$salt = md5("userlogin");
$pepper = "ptsbtr";
$passencrypt = $salt . $passw . $pepper;
//find out if user and password are present
$query = "SELECT * FROM users WHERE username='".mysqli_real_escape_string($uname)."' AND password='".mysqli_real_escape_string($passencrypt)."'";
$result = mysqli_query($query) OR die(mysqli_error());
$result_num = mysqli_num_rows($result);
if($result_num > 0){
while($row = mysqli_fetch_array($result)){
$idsess = stripslashes($row["id"]);
$firstnamesess = stripslashes($row["firstname"]);
$username = stripslashes($row["username"]);
$_SESSION["SESS_USERID"] = $idsess;
$_SESSION["SESS_USERFIRSTNAME"] = $firstnamesess;
$_SESSION["SESS_USERNAME"] = $username;
setcookie("userloggedin", $username);
setcookie("userloggedin", $username, time()+43200); // expires in 1 hour
//success lets login to page
returnheader("users-area.php");
}
} else {
//tell there is no username etc
$errors[] = "Your username or password are incorrect";
}
}
} else {
$uname = "";
}
?>
And this is the error after loading it for minutes.
Warning: mysql_connect(): MySQL server has gone away in C:\xampp\htdocs\peopletrackingsystem\login.php on line 10
Warning: mysql_connect(): Error while reading greeting packet. PID=6940 in C:\xampp\htdocs\peopletrackingsystem\login.php on line 10
Warning: mysql_connect(): MySQL server has gone away in C:\xampp\htdocs\peopletrackingsystem\login.php on line 10
Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\peopletrackingsystem\login.php on line 10
(backstory: my Apache is also having a problem with localhost/127.0.0.1. It only appears blank page every time I try to access it with just localhost. So I always put the port every time I try to access it. I already removed all unnecessary port in hosts file. I already change the listen port of the httpd.conf and the Server name too with the port in it)
You can't add the port in "localhost:85", try it like this:
$connection = mysqli_connect("localhost","root","") OR die(mysqli_error());
So I am attempting to connect to a database on an end device from one of my servers, however I'm getting the following error:
Can't connect to data source '<user>' because I can't work out what driver to use (it doesn't seem to contain a 'dbi:driver:' prefix and the DBI_DRIVER env var is not set) at <script> line 18
My lines of code are the following. I removed some private information of course.
my $sHDS = shift || "<host>";
my #rows;
my $cust = '<customer name>';
my $dsn = 'dbi:Sybase:' . $sHDS;
my $user = '<user>';
my $pass = '<password>';
my $hDb = DBI::connect($dsn, $user, $pass)
or die "Can not connect to ICM Database $DBI::errstr";
Anyone see where I am going wrong?
The correct call has the format
DBI->connect($dsn, $user, $password)
which is subtly but significantly different from
DBI::connect($dsn, $user, $password)
The first call is equivalent to the call
DBI::connect( 'DBI', $dsn, $user, $password )
and the connect function in DBI actually expects your dsn to be specified in the 2nd argument it receives.
The two errors are as below:
Notice: Undefined variable: HawA_Homes in C:\wamp\www\HawA_CIS241\InsertRecord.php on line 48
Notice: Undefined variable: HawA_Homes in C:\wamp\www\HawA_CIS241\InsertRecord.php on line 56
I've checked my names and they appear correct and I am not sure how to proceed now.
Code is as below:
<?php
$hostName = "localhost";
$databaseName = "test";
$userName = "root";
$password = "";
$tableName = "HawA_Homes";
//try to connect report error if cannot
$db = new mysqli($hostName, $userName, $password, $databaseName) or die(" Could not connect:" . mysql_error());
print(" Connection successful to host $hostName <br /> <br />"); //report connection success
//Get data to create a new record
$Address = $_REQUEST["address"];
$DateBuilt = $_REQUEST["dateBuilt"];
$Value = $_REQUEST["value"];
$Size = $_REQUEST["size"];
$Number_of_floors = $_REQUEST["floors"];
$sql = "INSERT INTO $HawA_Homes('Address','DateBuilt','Value','Size','Number_of_floors')VALUES{'$Address','$DateBuilt','$Value','$Size','$Number_of_floors')"; //Create insert query for new record
//try to query dataase / store returned results and report error if not successful
if(!$result =$db->query($sql))
{
//die('There was an error running the query[' .$db->error . ']';
}
print("SQL query $sql successful to database: $HawA_Homes <br /><br />"); //report sql query successful.
?>
You have these notices because the variable $HawA_Homes isn't declared in your code before being used at line 48 and 56. (These are just notices, they are not critical errors, you can avoid displaying them by adding error_reporting(E_ALL & ~E_NOTICE); at the begining of your code, like explained here)
In fact, you used $HawA_Homes instead of $tableName in these lines. Replace them, you won't have notices anymore for these lines.
Something is wrong with this code.
#!/use/bin/perl
use strict;
use warnings;
use Frontier::Daemon;
use DBI;
sub credentials {
my ($username, $password) = #_;
my $tablename = "users";
my $user = "db_user";
my $pw = "db_pass";
$dbh = DBI->connect('DBI:mysql:database;host=localhost', $user, $pw, {RaiseError => 1});
$sql = "SELECT username, password FROM $tablename";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
if ($sth->rows > 0) {
$login_response = "Login Successful";
} else {
$login_response = "Invalid Credentials";
return {'login' => $login_response};
die();
}
}
$methods = {'login.credentials' => \&credentials,};
Frontier::Daemon->new(LocalPort => 8080, methods => $methods)
or die "Couldn't start HTTP server: $!";
This is another problem with your code - you're not doing anything with the supplied username and password. You need to add a where clause to your SQL statement, so:
my $sql = 'SELECT * FROM users WHERE username = ? AND password = ? ';
my $sth = $dbh->prepare($sql);
$sth->execute($username, $password);
However, given that your example is selecting all records from the 'users' table, I'd have thought that credentials() would at least be returning some rows. However, I'm afraid that I've not used Frontier::Daemon in the past, so I'm not able to help on that front.
I also can't see how this code would work given that you are using strictures. $dbh, $sql, $sth and $login_response haven't been declared. So make sure that you're using 'my' in the right places - as per my example above.
To fix the problems you mentioned with returning the correct string - the logic in your if statement isn't quite right. You are returning the string 'Login Successful' when there's a successful login and the hashref { login => $login_response } when no user could be found.
I think the confusion arose from the layout of the braces. I must stress that you try and indent you code properly, which will make it much more readable to yourself and other developers when debugging and maintaining the code in the future.
The following logic should do the job.
if($sth->rows > 0){
return "Login Successful";
}
return "Invalid Credentials";