hi I avec a php file (inc.db.php) which contains my config to connect to my db.
Into this file I have something like
$dbh = new PDO(DSN, USER, PASS);
In a other file I included inc.db.php and in one function I want to use the $dbh variable.
My function is :
function getPassword($utilisateur) {
$uid = addslashes( $utilisateur );
$sql = "SELECT password FROM cc_users WHERE uid='$uid'";
$sth = $dbh->query($sql);
$result = $sth->fetchAll();
if (count($result) == 1) {
return TRUE;
} else {
return FALSE;
}
}
I got an error
PHP Notice: Undefined variable: dbh in /....
How I can do to use the variale included in a external file?
From the PHP Manual:
Any variable used inside a function is by default limited to the local
function scope.
(...)
In PHP global variables must be declared global inside a function if
they are going to be used in that function.
(...)
A second way to access variables from the global scope is to use the
special PHP-defined $GLOBALS array.
You'll avoid the error changing the function to this:
function getPassword($utilisateur) {
global $dbh;
$uid = addslashes( $utilisateur );
$sql = "SELECT password FROM cc_users WHERE uid='$uid'";
$sth = $dbh->query($sql);
$result = $sth->fetchAll();
if (count($result) == 1) {
return TRUE;
} else {
return FALSE;
}
}
But the usage of global variables is considered a bad practice.
Also, using addslashes won't protect your query against SQL injection attacks.
Prepare the SQL statements or use the quote method.
Related
Below is some code that works fine, however it used mysql_* and i dont want that anymore. I have tried to redo this section in mysqli but it's not working. I can post my entire code if you wish, but i am certain i know where the issue lies. Below is the code:
Old:
public function verifyDatabase()
{
include('dbConfig.php');
$data = mysql_query("SELECT client_id FROM clients WHERE client_email_address = '{$this->_username}' AND client_password = '{$this->_pass_sha1}'");
if(mysql_num_rows($data))
{
list($this->_id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
{
return false;
}
}
New:
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows)
{
list($this->_id) = #array_values($data->fetch());
return true;
}
else
{
return false;
}
}
I'm still learning mysqli and not quite ready for PDO stuff as i found that a little confusing. As i say, this whole script works perfectly with mysql_* but not so much with mysqli. When i try and log in my form doesnt display any errors nor does it push forward to the next page, so i know its this bit that is the issue
it is advised to use a helper function, either with old mysql or modern mysqli
public function verifyDatabase()
{
$sql = "SELECT client_id FROM clients WHERE email = ? AND password = ?";
return $this->db->getOne($sql ,$this->_username,$this->_pass_sha1);
}
Also note that dbConfig.php should not be included in the every method but, but only once. While DB handler should be assigned to a class variable in the constructor.
Change your code to this. I'm not saying it will fix problems but will be better.
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows > 0)
{
$result = $data->fetch();
$this->_id = $result['client_id'];
return true;
}
else
{
return false;
}
}
You can also put var_dump($result); after the $result = $data->fetch(); line to print out what exactly is being returned.
I'm trying to implement these two functions in a separate file functions.php and call it in index.php
function is_field($column, $table, $requested) {
$is_field_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($column, $table, $requested) {
$get_content_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$get_content_result = $mysqli->query($get_content_query);
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content_content = $get_content_row["content"];
$get_content_result->close();
return $content;
}
I have tried it over and over again and I have no idea why it wont work. The first one is returning 1 for valid or 0 for invalid. The second retrieves the content from a specific cell in the MySQL table. Any help would be much appreciated.
You're using $mysqli inside the function, but you never pass the MySQLi resource itself. Consider writing your function like this:
function is_field($mysqli, $column, $table, $requested) {
Or, create a class that takes a MySQLi resource and reference it with $this->mysqli inside your function.
Also, code like this may be another issue:
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
You're not checking whether $is_field_result is false; therefore, the next statement causes a fatal error, because a property can't be fetched from something that's not an object.
if (($is_field_result = $mysqli->query($is_field_query)) === false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
It turns out the reason it was not working was I needed to add an extra field into the function to accept the passing of $mysqli from the connection.
function is_field($mysqli, $column, $table, $requested) {
$is_field_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($is_field_result = $mysqli->query($is_field_query)) == false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($mysqli, $column, $table, $requested) {
$get_content_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($get_content_result = $mysqli->query($get_content_query)) == false) {
die($mysqli->error);
}
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content = $get_content_row["content"];
$get_content_result->close();
return $get_content;
}
Can someone please tell me why my function is not working?
function myappsbdo($sqlquery, $tabname)
{
try
{
$pdo = new PDO("mysql:host=127.0.0.1;port=3306;dbname=myapps","root","");
}
catch (PDOException $e)
{
echo "Problème de connexion";
exit();
}
$sql = $sqlquery;
$result = $pdo->query($sql);
$tabname = $result->fetchALL(PDO::FETCH_NUM);
}
I do a var_dump of the variable I chose for my $tabname and it's an empty array. There is suppose to have my db data in it...
Thanks!
EDIT: this is how I call it.
myappsbdo("SELECT * FROM categorie", $tab1);
The function argument $tabname was passed by value, therefore your subsequent assignment to that variable changes only the value of the function-scoped variable $tabname and not of the calling-scoped variable $tab1.
You want to pass by reference instead:
function myappsbdo($sqlquery, &$tabname) {
// ^---- notice the ampersand character
// etc.
$tabname = $result->fetchALL(PDO::FETCH_NUM);
}
Or, alternatively, return the resultset:
function myappsbdo($sqlquery) {
// etc.
return $result->fetchALL(PDO::FETCH_NUM);
}
$tab1 = myappsbdp('SELECT * FROM categorie');
Note that you probably ought to make your PDO object static, so that the database connection can be reused in successive function calls.
I am try to make an PDO sql inside function but it doesn't work. got no response from it. it works when not using function. my purpose is to make my code small. anyone can shed a light. thanks.
function Test() {
$get_name = $smt->prepare("SELECT * FROM customer WHERE id = '1'");
$get_name->execute();
foreach ($get_name as $temp) {
$name = $temp['name'];
$address = $temp['address'];
$phone = $temp['phone'];
$page = $temp['page'];
}
eval("\$page = \"$page\";");
echo $page;
eval("\$page = \"$page\";");
echo $page;
}
Test();
I'd probably refactor your code to something like:
function getCustomerInfo(PDO $pdo, $customerId)
{
// use a prepared statement that can get you info on any customer
$statement = $pdo->prepare(
"SELECT * FROM customer WHERE id = :customerId LIMIT 1");
// get the result resource from the database
$result = $statement->execute(array(
':customerId' => $customerId
));
// fetch the first row in the result as an associative array
// and return it to the caller.
return $result->fetchFirst(PDO::FETCH_ASSOC);
}
// use your connection in place of $pdo
$customerData = getCustomerInfo($pdo, 1);
// now you can do stuff with your data
var_dump($customerData);
This is better because it does not rely on global state, functions should never-ever-ever do that. and it uses prepared, parameterized sql that makes it faster and the function more useful for customers other that the one where id=1.
You need to make the pdo instance global within the function
function Test() {
global $smt;
I have been turning and twisting this to the best of my non-existing PDO knowledge, but still without any luck.
the code:
function write($id, $data) {
global $dbcon;
$id = mysql_real_escape_string($id);
$data = mysql_real_escape_string($data);
$sql = $dbcon->exec("INSERT INTO `sessions`
(`session_id`, `session_data`,
`session_expire`, `session_agent`,
`session_ip`, `session_referrer`)
VALUES
(\"".$id."\", \"".$data."\",
\"".time()."\",\"".($this->session_encryption($_SERVER['HTTP_USER_AGENT']))."\",
\"".($this->session_encryption($_SERVER['REMOTE_ADDR']))."\", \"".($this->session_encryption((isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_^~#&|=+;!,(){}[].?%*#'))))."\")
ON DUPLICATE KEY UPDATE
`session_data` = \"".$data."\",
`session_expire` = \"".time()."\"");
return true;
}
Give me the following error:
Fatal error: Call to a member function exec() on a non-object
on the
$sql = $dbcon->exec(
line.
I have been trying to solve this all evening, but without any luck.
This is my PDO connection script:
require_once(INC_PATH.'/config.php');
$dsn = "$db_type:host=$db_host;port=$db_port;dbname=$db_name;charset=$db_charset";
try{
$dbcon = new PDO($dsn, $db_user, $db_pass);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$dbcon = null; //Close database connection.
}
catch(PDOException $e){
echo $e->getMessage();
}
Hope one of you kind souls out there can help me, I would deeply appreciate it!
Thanks.
UPDATE:
I have a global.php file which looks like this:
//Load database
require_once(INC_PATH.'/database.php');
//Load session handler
require_once(INC_PATH.'/class_sessions.php');
$Sessions = new SessionManager();
session_start();
The database.php is included before the sessions class, and when I view the website, it does not give any errors on this part of the sessions class (which is before the write function:
function read($id) {
global $dbcon;
$data = '';
$id = mysql_real_escape_string($id);
$sql = $dbcon->prepare("SELECT
`session_data`
FROM
`sessions`
WHERE
`session_id` = '".$id."'");
$sql->execute();
$a = $sql->columnCount();
if($a > 0) {
$row = $sql->fetchObject();
$data = $row['session_data'];
}
return $data;
}
Are you sure your connection script is getting executed? Try checking if $dbcon is set. Also, you may be missing global $dbcon within the connection script.
By the way, since you're already using PDO, might I recommend you use placeholders in your query:
$sql = "INSERT INTO `sessions`
(`session_id`, `session_data`, `session_expire`,
`session_agent`, `session_ip`, `session_referrer`)
VALUES
(:session_id, :session_data, :session_expire,
:session_agent, :session_ip, :session_referrer)
ON DUPLICATE KEY UPDATE
`session_data` = :session_data,
`session_expire` = :session_expire";
$params = array(
':session_id' => $id,
':session_data' => $data,
':session_expire' => time(),
':session_agent' => $this->session_encryption($_SERVER['HTTP_USER_AGENT']),
':session_ip', => $this->session_encryption($_SERVER['REMOTE_ADDR']),
':session_referrer' => $this->session_encryption((isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_^~#&|=+;!,(){}[].?%*#';
);
$stmt = $dbcon->prepare($sql);
if ($stmt->execute($params) === FALSE) {
// handle error
}
First check that the global object is not being overwritten by another function. I strongly suggest you use Dependency injection instead of globals.
$Sessions = new SessionManager($dbcon);
And inside the Session Management class you can do something like
class SessionManager
{
protected $db;
public function __construct($db) { $this->db = $db; }
public function read($id)
{
$stmt = $this->db->prepare("SELECT session_data
FROM sessions
WHERE session_id = ?");
$stmt->execute(array($id));
return $stmt->fetchColumn();
}
}
And secondly, since you are using PDO, you dont need to call mysql_real_escape_string(), use prepared statements and placeholders :)