Cant connect mysql and php - php

I tried to connect my MySQL database kuvarskir with my PHP code. Then inputted this into html:
<?php
include "mysql.php";
$recepti = execute_sql("SELECT * FROM recepti");
foreach($recepti as $recept)
{
?>
<article>
<h2><?=$recept["naziv"]?></h2>
<i><?=$recept["sastojci"]?></i>
<p><?=$recept["uputstvo"]?></p>
</article>
<?php
}
?>
but its not working.
i think there is error with mysql.php file, here's the code:
<?php
function init_sql()
{
global $conn;
$host = "localhost";
$db = "kuvarskir";
$username = "root";
$password = "root";
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$conn = new PDO("mysql:host=$host;dbname=$db", $username, $password, $pdo_options);
}
catch(PDOException $e)
{
die("Database connection failed!");
}
}
function execute_sql($sql, $params=[])
{
global $conn;
if ($conn == null)
init_sql();
try
{
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$data = array();
if ($stmt->columnCount() == 0) //INSERT / UPDATE
return $stmt->rowCount();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
$data[] = $row;
return $data;
}
catch(Exception $e)
{
die("somting glitched. error is: $e");
}
}
?>
maybe, there is problem with my localhost, which is localhost:8080/phpmyadmin
also here is picture of database

Related

Connection is not defined

I have the following code
<?php
$host = "localhost";
$dbname = "hawkI";
$user = "root";
$password = "";
$userExist = false;
$userIP = null;
$userHasFinish = null;
$userLastPage = null;
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
function getIPforBDD(){
return $_SERVER['REMOTE_ADDR'];
}
function UpdateUserProfile()
{
$requete = "SELECT * FROM users WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
if($resultat->rowCount() == 0)
exit();
foreach($result as $ligne)
{
$userIP = $ligne['ip'];
$userhasFinish = $ligne['finish'];
$userLastPage = $ligne['lastPage'];
}
}
function CheckUserPosition()
{
UpdateUserProfile();
if(!$userExist)
AddUser();
return GetUserStatus();
}
function GetUserStatus()
{
$page;
if($userHasFinish)
$page = "end.php";
else
$page = $userLastPage;
return $page;
}
function AddUser()
{
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
function SavePageInBDD($page){
$requete = "UPDATE users SET lastPage = '.$page.' WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
}
?>
But, I have a problem when I use it
( ! ) Notice: Undefined variable: dbh in C:\wamp64\www\HawkI\bdd.php
on line 66
I do not understand correctly how PHP work it's the first time I use it, but I tried to make
global $dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
That doesn't work too.
Also, it seems that value that are put outside of functions are not global like it would be in js, how can I make something accessible from everywhere (like file that include that file)
Thanks
Better way would be to do something like this:
function getDB(){
$dbh = null;
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
return $dbh;
}
And than in your functions do this:
function AddUser()
{
$dbh = getDB();
if(!is_null($dbh)){
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
}
To use $dbh inside a function, you need to include global keyword inside the function scope.
You can find the global keyword explanation here http://php.net/manual/en/language.variables.scope.php#language.variables.scope.global
function AddUser()
{
global $dbh;
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
You may use like this
$host = "localhost";
$dbname = "hawkI";
$user = "root";
$password = "";
$userExist = false;
$userIP = null;
$userHasFinish = null;
$userLastPage = null;
$dbh = NULL;
function db () {
try {
if ($GLOBALS['dbh']===NULL){
$GLOBALS['dbh'] = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
}
return $GLOBALS['dbh'];
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
function SavePageInBDD($page){
$dbh = db();
$requete = "UPDATE users SET lastPage = '.$page.' WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
}

External file with PDO connection not working

I realize this question has been asked in some form or another multiple times, but none of the solutions on the other versions of this question work for me.
These two files have no issues:
/blog/login.php
<?php
include('core/init.php');
if (empty($_POST) === false){
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) || empty($password)) {
$errors[] = 'Missing username and/or password.';
} else if (user_exists($username) === false) {
$errors[] = 'User doesn\'t exist.';
}else if (user_active($username) === false) {
$errors[] = 'User account not activated.';
}else {
//
}
print_r($errors);
}
?>
/blog/core/init.php
<?php
require('database/connect.php');
require('functions/users.php');
require('functions/general.php');
session_start();
$errors = array();
?>
I'm just including them to show you how connect.php is require()'d (indirectly) in users.php.
/blog/core/database/connect.php
<?php
$dbname = "xxx_forms";
$servername = "mysql.xxx.com";
$usr= "xxx_xxx";
$pass = "xxxxxxxx";
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $usr, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
This connection itself doesn't trigger any errors...
/blog/core/functions/users.php
<?php
function user_exists($username) {
$ret = '';
try {
$sql = "SELECT COUNT(id) FROM registration WHERE user = '$username';";
$q = $pdo->query($sql);
$f = $q->fetch();
$ret = $f[0];
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
return ($ret == 1) ? true : false;
}
However, when we get to users.php, I always get an error at the $q = $pdo->query($sql); line, apparently because PHP doesn't know what $pdo is. On the other hand, when I include the code from connect.php, so that it is not in an external file (exactly like below, but not commented out):
function user_exists($username) {
//$dbname = "xxx_forms";
//$servername = "mysql.xxx.com";
//$usr= "xxx_xxx";
//$pass = "xxxxxxxx";
$ret = '';
try {
//$pdo = new PDO("mysql:host=$host;dbname=$dbname", $usr, $pass);
$sql = "SELECT COUNT(id) FROM registration WHERE user = '$username';";
$q = $pdo->query($sql);
$f = $q->fetch();
$ret = $f[0];
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
return ($ret == 1) ? true : false;
}
...everything works the way it is supposed to.
How do I make it work when the PDO connection is done in the external file connect.php?
Further to my comment, you need to do something like this:
/config.php
<?php
define('DS',DIRECTORY_SEPARATOR);
define('DB_HOST','localhost');
define('DB_NAME','database');
define('DB_USER','root');
define('DB_PASS','');
define('ROOT_DIR',__DIR__);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
# Add the connection function
require_once(FUNCTIONS.DS.'connect.php');
# Start session
session_start();
# Get the connection
$pdo = connect();
/functions/connect.php
function connect()
{
$pdo = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
/functions/user_exists.php
<?php
function user_exists($pdo,$username)
{
$ret = 0;
try {
$sql = "SELECT COUNT(id) as count FROM registration WHERE user = :username";
$q = $pdo->prepare($sql);
$q->execute(array(":username"=>$username));
$f = $q->fetch(PDO::FETCH_ASSOC);
$ret = $f['count'];
}
catch (PDOException $e) {
die("Could not connect to the database ".DB_NAME.":" . $e->getMessage());
}
return ($ret == 1);
}
Here is an example of use:
/index.php
<?php
# Add the basic stuff
require(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Add our functions
require(FUNCTIONS.DS.'user_exists.php');
require(FUNCTIONS.DS.'general.php');
# Example of use
print_r(user_exists($pdo,'username#email.com'));

PDO object cant acess inside function

In my project i had a file called connection.inc.php which is managing the data base connection using PDO.
include/connection.inc.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
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);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
i included this file in various other pages and it worked perfectly for me. But when i tried to acess the $conn object inside a function it not working. How to fix this problem.
You could do global $conn on top of your functions, but don't. I suggest wrapping it in a singleton instead.
<?php
class Connection {
private static $conn = null;
private $connection = null;
private function __construct() {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
try {
$this->connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage(); // Should look into a different error handling mechanism
}
}
public static function getConnection() {
if (self::$conn === null) {
self::$conn = new self();
}
return self::$conn->connection;
}
}
You can access it via Connection::getConnection()
This also has the advantage of not initializing the connection if the current request doesn't need to use it.
Honestly the simplest method is to set the connection inside of a function then you can use that function in other functions.
Example:
error_reporting(E_ALL);
ini_set('display_errors', 1);
function dataQuery($query, $params) {
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host='.DB_HOSTNAME.';dbname='.DB_DATABASE, DB_USERNAME, DB_PASSWORD);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step to close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
How To Use In Another Function:
function doSomething() {
$query = 'SELECT * FROM `table`';
$params = array();
$results = dataQuery($query,$params);
return $results[0]['something'];
}
You need to update your file as
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
//// define global variable
global $connection
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
/// assign the global variable value
$connection = $conn ;
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
Now you can call it any of your function like
function mytest(){
global $connection;
}
The best practice would be to pass the $conn as argument to the function.
But if you really need the function to have no arguments but still use a global variable, then adding this line in your function before using the variable should do the trick:
global $conn; // I want to use the global variable called $conn

PHP Select with PDO Call to a member function prepare() on a non-object error

I'm getting a Call to a member function prepare() on a non-object error in my PHP when using PDO to select data that was sent via an AJAX call.
Searching around on StackOverflow I've found many answers to this error, but none work to fix my problem.
The weird part is that the other PHP files use the same PDO calls and work successfully, but this one is giving me the non-object error only.
To note, the PDO connection is identical to the other pages where it works, so I know that's not causing the problem.
Also, I have tested that the AJAX data sent is being received, and that is working too.
PHP Code
$mysql_user = "NotTelling";
$mysql_password = "DefinatelyNotThis";
try
{
$dbh = new PDO("mysql:host=somehost;dbname=somename", $mysql_user, $mysql_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$inPword = $_POST['password'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$loggedin = "";
$password_hash = "";
$loggedinstatus = "";
$pts = "";
function getLoginInfo()
{
$sth = $dbh -> prepare('SELECT pword, loggedin, points FROM login WHERE uname = :uname');
$sth->bindParam(':uname', $username, PDO::PARAM_STR);
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo $row['pword'];
echo $row['loggedin'];
echo $row['points'];
}
$password_hash = $fetch['pword'];
$loggedinstatus = $fetch['loggedin'];
$pts = $fetch["points"];
if($password_hash === null || $loggedinstatus === null || $pts === null)
{
die(json_encode(array("message" => "none")));
}
else
{
return "more";
}
}
function checkLoginCreds()
{
if(crypt($inPword, $password_hash) === $password_hash)
{
switch($loggedinstatus)
{
case "no":
$sel = $dbh->prepare("UPDATE login SET loggedin='yes' WHERE uname = ?");
$sel->execute(array($username));
return "AllGood";
break;
defaut:
return "alreadyin";
break;
}
}
else
{
return "BadLogin";
}
}
if(getLoginInfo() === "more")
{
echo json_encode(array("message" => checkLoginCreds()));
}
getLoginInfo();
}
catch(PDOException $e)
{
echo $e->getMessage();
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
Finally, here's the output when I var_dump() the PDO connection.
object(PDO)#1 (0) {}
For this to work, you need to use the global variable scope, explained here: http://php.net/manual/en/language.variables.scope.php
$mysql_user = "NotTelling";
$mysql_password = "DefinatelyNotThis";
try
{
$dbh = new PDO("mysql:host=somehost;dbname=somename", $mysql_user, $mysql_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$inPword = $_POST['password'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$loggedin = "";
$password_hash = "";
$loggedinstatus = "";
$pts = "";
function getLoginInfo()
{
global $dbh, $username, $password_hash, $loggedinstatus, $pts;
$sth = $dbh -> prepare('SELECT pword, loggedin, points FROM login WHERE uname = :uname');
$sth->bindParam(':uname', $username, PDO::PARAM_STR);
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo $row['pword'];
echo $row['loggedin'];
echo $row['points'];
}
$password_hash = $fetch['pword'];
$loggedinstatus = $fetch['loggedin'];
$pts = $fetch["points"];
if($password_hash === null || $loggedinstatus === null || $pts === null)
{
die(json_encode(array("message" => "none")));
}
else
{
return "more";
}
}
function checkLoginCreds()
{
global $dbh, $inPword, $password_hash, $loggedinstatus, $username;
if(crypt($inPword, $password_hash) === $password_hash)
{
switch($loggedinstatus)
{
case "no":
$sel = $dbh->prepare("UPDATE login SET loggedin='yes' WHERE uname = ?");
$sel->execute(array($username));
return "AllGood";
break;
defaut:
return "alreadyin";
break;
}
}
else
{
return "BadLogin";
}
}
if(getLoginInfo() === "more")
{
echo json_encode(array("message" => checkLoginCreds()));
}
getLoginInfo();
}
catch(PDOException $e)
{
echo $e->getMessage();
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
But this can get messy very quickly.
I suggest you put the variables in an array or using OOP for a more robust solution: http://php.net/manual/en/language.oop5.php
This is how you can define it in a class..
class someClass {
private $db;
public function __construct(){
$this->dbconnect();
}
private function dbconnect() {
try { //try connection
$dbh = new PDO('mysql:host=localhost;dbname=somenane', 'usernane', 'pass');
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbh = $dbh;
} catch (Exception $e) { //connection failed
die("Oh no! It seems we took too long to respond");
}
}
public function getLoginInfo() {
$sth = $this->dbh->prepare('SELECT pword, loggedin, points FROM login WHERE uname = :uname');
$sth->bindParam(':uname', $username, PDO::PARAM_STR);
//cont the code
}
}
Not sure if it's good enough..but it will work..

PHP MySQL connection error

guys!I got a littile trouble.
There is connection.inc.php in "includes" folder:
<?php
function dbConnect($usertype, $connectionType = 'mysqli') {
$host = 'localhost';
$db = 'testdb';
if ($usertype == 'read') {
$user = 'readuser';
$pwd = 'testpass';
} elseif ($usertype == 'write') {
$user = 'writeuser';
$pwd = 'testpass';
} else {
exit('Unrecognized connection type');
}
if ($connectionType == 'mysqli') {
return new mysqli($host, $user, $pwd, $db) or die('Cannot open database');
} else {
try {
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch(PDOException $e) {
echo 'Cannot connect to database';
exit;
} // end of try block
} // end of $connectionType if
} // end of function
I use Linux for this test,and the lastest xampp 1.7.4
But things become worse when I use the following code:(I already have created my DB, and two users 'readuser' and 'writeuser')
<?php
// I use mysqli extension to connect my DB
require_once(includes/connection.inc.php);
// connect to DB
$conn = dbConnect('read');
// I need to get some picture infomations from images table
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error());
// find out how many records were retrieved
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>
And when I load it in my browser:
Fatal error:Call to a member function query() on a non-object in /opt/lampp/htdocs/mysqli.php on line 9
So I guess $conn is not a object now,but It works when I write this code:
<?php
$host = 'localhost';
$user = 'readuser';
$pass = 'testpass';
$db = 'testdb';
$sql = 'SELECT * FROM images';
$conn = new mysqli($host, $user, $pass, $db);
$result = $conn->query($sql) or die(mysqli_error());
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>
And it outputs:We have 8 pictures in DB
That's really a strange thing,I can't figure it out...Thanks guys!
Try saving the new mysqli() result as a variable, then return that variable instead. That logic makes no sense, I know, but I've had problems like that before.
$a = new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
return $a;

Categories