So i've been having an issue with NetBeans code completion. I'm currently trying to set up a database connection that i can use in my other files. Inside of my connection.php file, I have access to all of the usual database methods. My end goal is to use prepared statements for my queries.
However, when i am inside my register.php file, with connection.php required at the top, suddenly code completion doesn't work anymore. I get the generic popup. This is the file i would like to actually use those prepared statements in. I would also like to avoid having to open a new connection in every file.
So my question to you is, is it me or is it NetBeans?
connection.php
$host = "localhost";
$username = "root";
$pass = "password";
$database = "LoganWebsiteUserLogin";
try {
$conn = new PDO('mysql:host=localhost;dbname=' . $database . ';charset=utf8mb4', $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected Successfully!";
} catch (PDOException $e) {
echo "Connection failed! " . $e->getMessage();
}
register.php
<?php
require 'connection.php';
// Create session variables
$_SESSION['firstName'] = $_POST['firstName'];
$_SESSION['lastName'] = $_POST['lastName'];
$_SESSION['email'] = $_POST['email'];
// trying to access $conn from connection.php here, however autocomplete for
// it is not working. NetBeans doesn't know that $conn is a PDO
$conn->
It works in PhpStorm but not in Netbeans. But anyway, global variables are not recommended and lead to unwanted side effects. Maybe try a different approach.
Example:
connection.php
<?php
function db(): PDO
{
static $pdo = null;
if (!$pdo) {
$host = "localhost";
$username = "root";
$password = "password";
$database = "LoganWebsiteUserLogin";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
];
$pdo = new PDO("mysql:host=$host;dbname=$database;charset=utf8mb4", $username, $password, $options);
}
return $pdo;
}
register.php
<?php
require_once __DIR__ . '/connection.php';
// Create session variables
$_SESSION['firstName'] = $_POST['firstName'];
$_SESSION['lastName'] = $_POST['lastName'];
$_SESSION['email'] = $_POST['email'];
// Works :-)
db()->
Related
I can't Update my Database with PHP. I don't get any errors but it doesn't change anything!
Here is my file:
<?php
include_once 'dbh.inc.php';
?>
<?php
$id = $_GET['verId'];
$name = $_GET['verName'];
echo $id;
echo $name;
$sql = "UPDATE allusers SET ver = '1' WHERE idUsers = '$id';";
?>
The variables are defined and work.
Here's the dbh.inc.php file:
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "loginsystem";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: ".msqli_connect_error());
}
?>
Other files that use dbh.inc.php work fine.
Thanks for your help.
You need to execute your SQL, but the way you are using MySQLi is very wrong. Let me show you how to get started with a simple query.
First in your dbh.inc.php (you should name it properly too) you should have the following code:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new \mysqli("localhost", "root", "", "loginsystem");
$conn->set_charset('utf8mb4');
Do not use root for connection. Create a valid MySQL user with a proper password.
Then in your main PHP file, you can use it as follows:
<?php
include_once 'dbh.inc.php';
$id = $_GET['verId'];
$name = $_GET['verName'];
echo $id;
echo $name;
// prepare -> bind data -> execute
$stmt = $conn->prepare("UPDATE allusers SET ver='1' WHERE idUsers=?");
$stmt->bind_param('s', $id);
$stmt->execute();
I used here what is called a prepared statement. You can learn more about MySQLi here: https://phpdelusions.net/mysqli_examples/update
I'm trying to make a MySQL & PHP based control panel for my community. And I've made a settings.php file with arrays with configs. I have class files for functions but there is MySQL function, which will not connect with data I've entered on settings.php..
I've tried other config file options, but none of them works...
on settings.php I have MySQL data like this:
$config['database']['host'] = "---";
$config['database']['user'] = "---";
$config['database']['password'] = "---";
$config['database']['database'] = "---";
And on userdata.php class file, where I'm trying to use those config variables I have:
$mysql = new mysqli($config['database']['host'], $config['database']['user'], $config['database']['password'], $config['database']['database']);
obviously, on userdata.php I have also required the settings.php..
I was expecting the output to be correct, but it shows only 'wrong MySQL data' errors...
I got it working with settings.php file like:
$config = array (
'db_host' => 'xxx',
'db_user' => 'xxx',
'db_pass' => 'xxx',
'db_database' => 'xxx'
and userdata.php like:
include 'settings.php';
$host = $config['db_host'];
$user = $config['db_user'];
$pass = $config['db_pass'];
$database = $config['db_database'];
$mysql = new mysqli($host, $user, $pass, $database);
you can try this way in connection.php file
<?php
include_once("path/config.php");
function OpenCon()
{
$dbhost = $config['database']['host'];
$dbuser = $config['database']['user'];
$dbpass = $config['database']['password'];
$db = $config['database']['db'];
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n".
$conn -> error);
return $conn;
}
Please tell me that where is error. I am in tention due to this,
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\kalooo1\includes\db.php:2 Stack
trace: #0 C:\xampp\htdocs\kalooo1\index.php(21): include() #1 {main}
thrown in C:\xampp\htdocs\kalooo1\includes\db.php on line 2
db.php
<?php
mysql_connect("localhost","root","");``
mysql_select_db("kalooo");
?>
index.php(21)
include("includes/db.php");
You are getting that error simple because you are using a newer version of php that does not support mysql_* functions, those functions have been depreciated and completely removed from the latest version of php.
You should use mysqli prepared functions or pdo prepared statements.
using mysqli to connect to database you will use it like this:
<?php
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "yourdatabse";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
using PDO, you would connect like this:
<?php
$host = 'localhost';
$db = 'yourdb';
$user = 'yourusername';
$pass = 'yourpassword';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
?>
The are good tutorials on the net that you can use to better your understanding, I personally enjoy this site https://phpdelusions.net/pdo You should visit it you will be a pro in no time.
use mysqli_connect("localhost","root","","db_name");
or use
store this in separate php file.
include that file like this. include 'db.php';
try this....
try this
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
I'm using this same block of code in numerous PHP files and sometimes in the same PHP file (e.g., when there's an if/else. I know there's a better way, but I'm not quite sure how to do it. I want to replace this big block with something, but not sure what fits. require maybe?
$hostname = 'localhost';
$database = 'dev_testing';
$username = 'root';
$password = 'XXXXXX';
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The answers by #maalls and #TahaPaksu are good, but #marcB's comment is even better: usually you'd want to connect to the database only once per script execution. I don't want to kick you right in the direction of dependency injection, but as an intermediate solution, I'd like to suggest this class, which looks roughly like a singleton, but is actually the Memoization pattern implementation (see also PHP Design Patterns for other pattern examples).
Anyway: the code:
class Database() {
static private $connection = null;
public static function getConnection() {
if (static::$connection === null) {
$hostname = 'localhost';
$database = 'dev_testing';
$username = 'root';
$password = 'XXXXXX';
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
static::$connection = $dbh;
}
return static::$connection;
}
}
In your script you can call it using
$dbh = Database::getConnection();
You can call that line as often as you like but it will only connect to the database the first time it's called for that script. Subsequent calls will just return the same connection. This will save quite some overhead on your database.
Create a separate file (for ex. "connection.php"), put the code in it, and everywhere you need it, include the following at the begining of your code:
require_once('connection.php');
you can use a global function which you include in top of your php files:
require_once("db.php");
file db.php:
function db_connect(){
$hostname = 'localhost';
$database = 'dev_testing';
$username = 'root';
$password = 'XXXXXX';
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
and in your files:
$dbh = db_connect();
...
// don't forget to close db before you open a new connection!
$dbh = null;
I have a table on PHPmyamdmin, and when i try to select it with the following code:
*<?php
//connect.php
session_start();
$server = 'localhost';
$username = 'zimmer';
$password = '';
$database = 'csgopit';
if(!mysql_connect($server, $username))
{
exit('Error: could not establish database connection');
}
if(!mysql_select_db($database))
{
exit('Error: could not select the database');
}
?>*
i get this error when i open the page in localhost:
Error: could not select the database
In the database i have 4 tables, one of them is users and i have manually added the user "zimmer" to it, i'm using this to create and experiment forum in my learning experiences, also, using this same code as a "connect.php" if i use it as for example on another file simply by using this line
using connect.php or include connect.php
would it work in a login or would it load only the user zimmer?
I started with PHP couple of days ago so sorry for the rookie question.
Try PDO.
$handler = '';
$server = 'localhost';
$username = 'zimmer';
$password = '';
$database = 'csgopit';
try {
$this->handler = new PDO('mysql:host='. $server .';dbname='. $database . ';charset=utf8', $username, $password);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
But you also mentioned you added the user "zimmer" to the users table. This is different than your $username you pass to connect to the database.
Did you set up a username and password to a database?