checking if a database exists - php

The code below works fine except it throws a warning when connecting to a database that does not exist. This works fine in product where errors are off, but I would rather not have errors if I don't need to.
function cpanel_db_connect($dbname) {
// normalize
$dbname = convert_to_slug($dbname);
$dbname = CPANEL_USER . '_' . $dbname;
$dbuser = CPANEL_USER . '_' . CPANEL_DB_USER;
// connnect database
$mysqli = new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);
if ($mysqli->connect_error) {
return false;
}
return $mysqli;
}

It's not a good practice to suppress warnings/errors using the # sign in PHP. You could accidentally suppress an invalid username or password message and you would never know it.
A more appropriate way of checking if the database exists is creating a new instance of Mysql or Mysqli (without specifying the default database) and executing the following query (similar to Marc B's comment):
SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME='my_database_name'
Then you can check the value of the key exists to see if the database is there or not.
Here's a sample code:
// statement to execute
$sql = 'SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME="my_database_name"';
// execute the statement
$query = $mysqli->query($sql);
// extract the value
$row = $query->fetch_object();
$dbExists = (bool) $row->exists;
It is a bit longer but it's safer.

$mysqli = #new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);
The above works!

This works, just replace $dbname in this code:
if (empty (mysql_fetch_array(mysql_query("SHOW DATABASES LIKE '$dbname' ")))){
echo "DB does Not exist"; }else{ echo "DB exists!";}

Updating to MYSQLI:
$conn = new mysqli('localhost', 'root', '');
$dbname='test';
if (empty (mysqli_fetch_array(mysqli_query($conn,"SHOW DATABASES LIKE '$dbname'"))))
{
echo "DB not exist<br>";
}
else
{
echo "DB exist<br>";
}

Here's how to connect to DB server without selecting a DB, and only connecting if DB exists:
$mysqli = new mysqli($db_biz['server'], $db_biz['user'], $db_biz['password']);
$query = 'SHOW DATABASES LIKE "' . $db_biz['dbName'] . '"';
$resShowBizDB = $mysqli->query($query);
if ($resShowBizDB->num_rows == 1) { //Found database
$mysqli->select_db($db_biz['dbName']);
if ($mysqli->connect_errno) { //Check for errors
var_dump($mysqli);
echo "Failed to connect to biz database: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$mysqli->set_charset('utf8');
} else { //Didn't find DB
die('<h1>ERROR</h1><p>Found no database</p>');
}

Related

PHP Mysqli_query returns successful, but no insert into my table

I have tried debugging and cannot seem to get to the bottom of this problem. My query returns successful, however nothing is inserted into my table within my database. I am working on a CRUD application to enter holdings of cryptocurrency, and this is simply the Create button. My function gets to the very end of the if statement, and Mysqli_query returns a 1. Could this be issues with permissions in PHPAdmin? Or possibly something to do with Ports?
The code below:
$con = createDB();
if (isset($_POST['create'])){
createData();
}
function createData(){
$username = textboxValue('Username');
$BTC = textboxValue('BTC');
$ETH = textboxValue('ETH');/*$ETH =(isset($_POST['ETH']) ? $_POST['ETH'] : '');*/
$DASH = textboxValue('DASH');
if($username && $BTC && $ETH && $DASH){
$sql = "INSERT INTO cryptoholdings(username,BTC_holdings,ETH_holdings,DASH_holdings)
VALUES('$username','$BTC','$ETH','$DASH')";
if($GLOBALS['con']->query($sql) ){ /*(mysqli_query($GLOBALS['con'],$sql))*/
$GLOBALS['con']->commit();
echo "Record Successfully inserted...!";
}
else{
echo "Error Recording Data <br>" . mysqli_error($GLOBALS['con']);
}
}
else{echo "Provide all data in textboxes.";
}
}
function createDB(){
$servername='localhost';
$username='root';
$password='password';
$dbname='holdings';
//create connection to our database "holdings"
$con=mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection Failed: ". mysqli_connect_error());
}
//create Database
$sql= 'CREATE DATABASE IF NOT EXISTS $dbname';
if(mysqli_query($con,$sql)){
$con = mysqli_connect($servername,$username,$password,$dbname);
$sql= 'CREATE TABLE IF NOT EXISTS cryptoholdings(
username VARCHAR(25) NOT NULL,
BTC_holdings FLOAT(11) NOT NULL,
ETH_holdings FLOAT(11) NOT NULL,
DASH_holdings FLOAT(11) NOT NULL)';
if(mysqli_query($con,$sql)){
return $con;}
else{
echo "Error when Creating Table...";
}
}
else{
echo "Error while creating Database...". mysqli_error($con);
}
}
function textboxValue($value){
$textbox = mysqli_real_escape_string($GLOBALS['con'],trim($_POST[$value]));
if(empty($textbox)){
return false;
}
else{
return $textbox;
}
}
First check that the connection was very okay by echoing something from the db or by doing sth on the db. 2nd try using another method other than the global con being used. For the purpose of testing and finding solution, I recommend you create a simpler table (of one or 2 fields) and try inserting into the fields. I recommend this method of connection below.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

how to convert mysqli_set_charset($conn,"utf8") into PDO format in MYSQL?

I trying to solve the UTF8 problem. So far i manage to test out and it works in mysqli connection.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tesddddt";
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM customer";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["uid"]. " - Name: " . $row["username"]. " " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
I manage to Insert and Select data with characters shown in it's language format correctly with the above coding.
However, when I try to do it in PDO , it shows 1 error when I insert data.
public function __construct(){
try {
$conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user_name, $this->db_pass);
mysqli_set_charset($conn,"utf8"); // <- added here
$this->conn=$conn;
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
I got this error
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, object given in...
My php project is using PDO and hence need to get this work in PDO format. Anyone know how to settle this?
You try to connect via PDO and then change the charset via mysqli, without having a mysqli connection, that is what's causing the warning.
In PDO the charset usually is being specified within the connection string, like this:
$conn = new PDO("mysql:host=yourhost;dbname=yourdbname;charset=utf8");

Web design PHP SQL Query issue

This is one of my functions in my function.php file. Right now I'm just trying to get it to output 1 or 0 depending if the username is in the MYSQL DB.
function retrieve_single($col, $table, $item, $con) {
require_once('include/global.php');
$sql = "SELECT * FROM users WHERE username = Username1";
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($conn->connect_error) {
trigger_error('Database connection failed: '.$conn->connect_error, E_USER_ERROR );
}
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
echo $rows_returned;
}
}
I keep changing stuff around trying to figure out what's wrong with it, all I know it is a sql error I keep getting. As of right now I have it written without the variables because of trying to figure out the problem.
The global.php:
$DBServer = 'localhost'; $DBUser = 'root'; $DBPass = ''; $DBName = 'social';
Can anyone help me out! I know the problem is simple, as this is my first time having this problem
The error you say that you're getting and you haven't shown us, is caused by this:
WHERE username = Username1 ";
^ ^ // missing quotes
It needs to have single quotes placed around Username1
I.e.:
WHERE username = 'Username1'";
If you're not already doing so, add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Your function is very confusing. How are you calling it in the rest of your code?
function retrieve_single($col, $table, $item, $con) {
require_once('include/global.php');
$sql = "SELECT * FROM users WHERE username = Username1";
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($conn->connect_error) {
trigger_error('Database connection failed: '.$conn->connect_error, E_USER_ERROR );
}
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
echo $rows_returned;
}
}
So your interface to retrieve_single() has the following $col, $table, $item and $con. But where are they used in the function? They seem 100% not used at all. So you are just calling it like retrieve_single() and hope it works? Seems odd.
Then within your function your query is this:
$sql = "SELECT * FROM users WHERE username = Username1";
Which makes little sense. It should at least have single quotes around it like this:
$sql = "SELECT * FROM users WHERE username = 'Username1'";
But it seems like it should be a variable like this:
$sql = "SELECT * FROM users WHERE username = '$Username1'";
But that said, where would $Username1 come from? Perhaps—looking at your interface variables—that should be $item like this:
$sql = "SELECT * FROM users WHERE username = '$item'";
Perhaps the whole function needs to be refactored to accommodate all the oddities I noticed like this:
function retrieve_single($col, $table, $item, $con) {
require_once('include/global.php');
$sql = "SELECT $col FROM $table WHERE username = '$item'";
if ($con->connect_error) {
trigger_error('Database connection failed: '.$con->connect_error, E_USER_ERROR );
}
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
echo $rows_returned;
}
}
Using this refactored function you would access it like this outside of the function:
$con = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
retrieve_single('*', 'users', 'Username1', $con);
Then again, no idea how you are actually using your function in your larger code so this is me just winging it based on what you have presented. As it stands, the function itself—as you have presented it—is just problematic.

Error occurred ... no database selected

I'm trying to connect to a database, check a column for whether a value exists or not, then execute a function based on whether or not that value exists.
Here's my code.
$con = mysql_connect('localhost','root','','users');
$sql = "SELECT * FROM allUsers WHERE username = '".mysql_real_escape_string($_POST["username"]) . "'";
$result = mysql_query($sql,$con) or die("Error occurred in [$sql]: " . mysql_error());
$count = mysql_num_rows($result);
if ($count != 0){
echo "Username is already taken";
echo "$count";
mysql_close($con);
}
else{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
The thrown error is:
Error occurred in [SELECT * FROM allUsers WHERE username = 'Admin']: No database selected.
I'm almost entirely sure that it comes from the $result line, but haven't a clue as to why.
I feel like this is a simple solution, and I'm just missing something minor.
I'm very new to MySQL (today is my first day, actually), so please keep solutions as simple as possible.
You forgot to call mysql_select_db after connecting:
$con = mysql_connect('localhost','root','');
mysql_select_db('users', $con);
Unlike MySQLi or PDO, mysql_* libraries does not take database as argument on the connection string, however if you were to migrate to either MySQLi or PDO.
MySQLi:
$con = new mysqli('localhost', 'root', '', 'users');
PDO:
$con = new PDO('mysql:host=localhost;dbname=users', 'root', '');
In MySQLi your code would look like this:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database = "users";
$con = mysqli_connect($host,$user,$pass,$database);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$stmt = $con->prepare("SELECT * FROM allUsers WHERE username = ? LIMIT 1");
$stmt->bind_param('s',$_POST["username"]);
if (!$stmt->execute())
die('Failed to excute with error ' . $con->error);
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if ($count > 0)
{
echo "Username is already taken.";
}
else
{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
I think your error is quite obvious, you need to specify the database you want.
mysql_select_db("databaseName", $con);
With that taken care of, please, please don't use mysql_ libraries the are vulnerable to SQL injection and will soon be removed.

Php mysql create database if not exists

I want to create a database. Why is not the db created with this code?
$dbname = 'regulations_db';
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_num_rows(mysql_query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '". $dbname ."'"))) {
echo "Database $dbname already exists.";
}
else {
mysql_query("CREATE DATABASE '". $dbname ."'",$con);
echo "Database $dbname created.";
}
This is working, but I think the first one is the best practice:
if (mysql_query("CREATE DATABASE IF NOT EXISTS regulations_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
Just do a simple mysql_select_db() and if the result is false then proceed with the creation.
As an example, check out the first answer here by another very smart StackOverflower.
<?php
// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Make my_db the current database
$db_selected = mysql_select_db('my_db', $link);
if (!$db_selected) {
// If we couldn't, then it either doesn't exist, or we can't see it.
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
mysql_close($link);
?>
Three steps to fix this:
Don’t specify the database name when connecting.
Your SQL statement should be CREATE DATABASE IF NOT EXISTS php1.
Call mysqli_select_db($link, 'php1') to make that the default database for your connection.
If you're using MySQLi Object-oriented method, you can use following code, this code is similar to previous answer and only the method is different, I just put this because if anyone using MySQLi Object-oriented method, you can use this code directly.
$servername = "localhost";
$username = "mysql_user";
$password = "user_password";
$dbName = "databaseName";
// Connect to MySQL
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// If database is not exist create one
if (!mysqli_select_db($conn,$dbName)){
$sql = "CREATE DATABASE ".$dbName;
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
}else {
echo "Error creating database: " . $conn->error;
}
}
Furthermore you can refer W3school site here.
Good Luck! :D

Categories