Insert sql statement in php Error: No database selected - php

So I'm attempting to make a registration form. I've made a php MySQL class which uses the constructor to make the connection with new MySQLi() for verifyLogin function and mysql_connect() for my addElement function.
The error is with my addElement function, the SQL statement writes out properly but it doesn't seem to connect to the database. I've checked that all the names are correct. Any ideas?
<?php
class MySQL {
private $connection;
private $conn;
private $databaseName;
function __construct($dbServer, $dbUser, $dbPassword, $dbName) {
$this->connection = new MySQLi($dbServer, $dbUser, $dbPassword, $dbName)
or die('PROBLEM CONNECTING TO DATABASE');
$this->conn = mysql_connect($dbServer, $dbUser, $dbPassword);
echo $this->conn;
$databaseName = $dbName;
}
function verifyLogin($table, $email, $password) {
$query = "SELECT *
FROM ?
WHERE email = ?
AND password = ?
LIMIT 1";
if($statement = $this->connection->prepare($query)) {
$statement->bind_param('sss', $table, $email, $password);
$statement->execute();
if($statement->fetch()) {
$statement->close();
return true;
}
else {
return false;
}
}
}
function addElement($table, $firstName, $lastName, $email, $mobile, $password,
$faculty, $campus) {
$query = "INSERT INTO $table (first_name, last_name, email, mobile, password, faculty, campus_location)
VALUES('$firstName', '$lastName','$email','$mobile',
'$password','$faculty','$campus');";
echo $query;
mysql_select_db($this->databaseName, $this->conn);
if(!mysql_query($query)) {
die('Error: ' . mysql_error());
}
mysql_close($this->connection);
}
}
?>

To select a database in MySQLi, you need to select it like so:
$db = new mysqli("localhost", "my_user", "my_password", "database_name");
or
$db = new mysqli("localhost", "my_user", "my_password");
$db->select_db('database_name');
as opposed to MySQL:
$db = mysql_connect('localhost', 'my_user', 'my_password');
$db_selected = mysql_select_db('database_name', $db);
MySQLi : http://www.php.net/manual/en/mysqli.select-db.php
MySQL : http://www.php.net/manual/en/function.mysql-select-db.php

You are mixing the mysql and the mysqli php drivers.
Since the mysql driver is deprecated I would suggest going with the mysqli.
PHP Documentation:
http://www.php.net/manual/en/book.mysqli.php
Good Overview to get you started:
http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/

Related

linking my database to my server on xampp for the first time [duplicate]

I'm working on streamlining a bit our db helpers and utilities and I see that each of our functions such as for example findAllUsers(){....} or findCustomerById($id) {...} have their own connection details for example :
function findAllUsers() {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
die("Connection to DB failed: " . $con->connect_error);
} else {
sql = "SELECT * FROM customers..."
.....
.....
}
}
and so on for each helper/function. SO I thought about using a function that returns the connection object such as :
function dbConnection ($env = null) {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
return false;
} else {
return $con;
}
}
Then I could just do
function findAllUsers() {
$con = dbConnection();
if ($con === false) {
echo "db connection error";
} else {
$sql = "SELECT ....
...
}
Is there any advantages at using a function like this compared to a Class system such as $con = new dbConnection() ?
You should open the connection only once. Once you realize that you only need to open the connection once, your function dbConnection becomes useless. You can instantiate the mysqli class at the start of your script and then pass it as an argument to all your functions/classes.
The connection is always the same three lines:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli($srv, $usr, $pwd, $db, $port);
$con->set_charset('utf8mb4');
Then simply pass it as an argument and do not perform any more checks with if statements.
function findAllUsers(\mysqli $con) {
$sql = "SELECT ....";
$stmt = $con->prepare($sql);
/* ... */
}
It looks like your code was some sort of spaghetti code. I would therefore strongly recommend to rewrite it and use OOP with PSR-4.

convert mySQL to mySQLi - using a class

The previous programmer had used a class called database that has the connection string and a bunch of functions. I now have to convert this to MySQLi and I am at a loss.
class database {
var $sql='';
var $result='';
function database( $host='localhost', $user, $pass, $db) {
// perform a number of fatality checks, then die gracefully
if (!function_exists( 'mysql_connect' )) {
//or die( 'FATAL ERROR: MySQL support not available. Please check your configuration.' );
exit();
}
bla..bla..bla - bunch of code goes here
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysql_query($sql);
return $result;
}
}
I tried
var $link=mysqli_connect('localhost', $user, $pass);
to use as
$result = mysqli_query($link,$sql);
but I can not use expression as a variable value and I don't know what else to do.
Thanks a bunch! :)
try to use this.
I think it solves your problem.
<?php
$link = mysqli_connect("localhost", $user, $pass, $databaseName);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
mysqli_set_charset($link, "utf8");
?>
just bring the $link in every query.
$link = mysqli_connect("localhost", $user, $pass, $db);
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysqli_query($link,$sql);
return $result;
}

php add prepared statements to database

I want to implement the prepared statement to my script but really cant get it to work. I already have alot of functions so i want as little change as possible.
I think it would be best to have a prepared statement function? So when i get user inputs I could call that functions instead of query.
The database.php class
class MySQLDB {
var $connection; // The MySQL database connection
/* Class constructor */
function MySQLDB() {
global $dbsystem;
$this->connection = mysqli_connect ( DB_SERVER, DB_USER, DB_PASS, DB_NAME ) or die ( 'Connection Failed (' . mysqli_connect_errno () . ') ' . mysqli_connect_error () );
}
/**
* query - Performs the given query on the database and
* returns the result, which may be false, true or a
* resource identifier.
*/
function query($query) {
return mysqli_query ( $this->connection, $query );
}
};
/* Create database connection */
$database = new MySQLDB ();
this is how I call the database from another class.
$q = "UPDATE users SET name = '$name', started = '$time' WHERE id = '$id';";
$result = mysqli_query ( $database->connection, $q );
In your case I would do something a little cleaner, like this:
<?php
class MySQLDB{
private function openConnection(){
// If you don't always use same credentials, pass them by params
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Assign conection object
return $conn;
}
private function closeConnection($conn){
$conn->close();
}
function updateUserById($id, $name, $startedTime){
$conn = $this->openConnection();
$sqlQuery = "UPDATE users SET name = ?, started = ? WHERE id = ?";
if ($stmt = $conn->prepare($sqlQuery)) {
// Bind parameters
$stmt->bind_param("ssi", $name, $startedTime, $id);
// Execute query
$stmt->execute();
if ($stmt->errno) {
die ( "Update failed: " . $stmt->error);
}
$stmt->close();
}
$this->closeConnection($conn);
}
} // Class end
Now, to use it, you just have to do this:
<?php
$myDBHandler = new MySQLDB;
$myDBHandler->updateUserById(3, "Mark", 1234);

Connect to DB and Activites by OOP in PHP

Hi I am having some issues connecting to my DB using OO PHP. My script is below. I have been going at this for a while now. This is just a test script as I am fairly new to OOP. Please don't be harsh
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$mysqli = new mysqli($host, $username, $password, $db);
if (!$mysqli){
echo "error in connecting to database";
}
else{
echo "success in connecting to database";
}
}
public function query(){
$result = $mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
Usage...
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
Your main problem is that you aren't storing a value into your class' $mysqli property. You need to use $this->mysqli in your constructor and query method instead of $mysqli.
Secondly, this class adds nothing that the mysqli class doesn't already have. You might as well simply use
$DB = new mysqli('localhost', 'root', 'xxxx', 'yyyy');
if ($DB->connect_error) {
throw new Exception($DB->connect_error, $DB->connect_errno);
}
The problem is, you are accessing the class property without $this. The $mysqli should be in $this->mysqli in constructor function.
You are using mysqli property as Object of mysqli class.
Then you can use the query function of mysqli property object(In Database class) by $this->mysqli->query("SELECT * FROM inventory") in query function.
Updated Code:
<?php
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->mysqli = new mysqli($host, $username, $password, $db);
/* check connection */
if ($this->mysqli->connect_errno) {
printf("Connect failed: %s\n", $this->mysqli->connect_error);
exit();
} else {
echo "success in connecting to database";
}
}
public function query(){
$result = $this->mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
Try this:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_error()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}

How I call my mysqli in order page?

I have this in db.php page:
function db_connect(){ $link = new mysqli(localhost, user, pass, table); }
And this is in other page:
require_once("db.php");
function register($username, $email, $password){
global $link;
$query = "INSERT INTO proyecto.user (username, password, email)
VALUES ('$username', '$password', '$email')";
$result = mysqli_query($link, $query);
}
But it doesn't work when I call "register". How should I call the function "db_connect"?
You can do it like this (PDO connection):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
You can make it become a global variable if you want.
$GLOBALS['db'] = $db;
Note that this is pdo, an example of a PDO database operation for your case, note that this uses prepared statements and is therefor quite safe from sql injections, and is quite easy to use:
function register($username, $email, $password){
$query = "INSERT INTO user (username, password, email) VALUES (:username, :password, :email)"; // Construct the query, making it accept a prepared variable search.
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':username' => $username,
':password' => $password,
':email' => $email
)); // Here you insert the variable, by executing it 'into' the prepared query.
if($result)
{
return true;
}
return false
}
And you can call it like this:
$registerSuccess = register($username, $email, $password);
have db_connect() return the $link, or make $link global in db_connect()
function db_connect() {
return new mysqli(localhost, user, pass, table);
}
function register($username, $email, $password) {
$link = db_connect();
$query = "INSERT INTO proyecto.user (username, password, email)
VALUES ('$username', '$password', '$email')";
$result = mysqli_query($link, $query);
}

Categories