Connect MYSQL using php and creating Database if not exist - php

Im trying to learn php with best methods and practice but im not able to get proper output as per the code as there is no error!
is it a good method to create the database if not exist because im not getting output echo "Database $dbname created successfully\n";
<?php
$user = "root";
$pwd = "";
$server = "localhost";
$dbname = "xyz";
//Connecting to MYSQL
$db_conn = mysqli_connect($server,$user,$pwd);
if (!$db_conn) {
die("Connection Error".mysqli_error());
}
echo "Connected Successfully";
$db_select = mysqli_select_db($db_conn,$dbname);
if (!$db_select) {
// If we couldn't, then it either doesn't exist, or we can't see it.
//Create Database Query
$db_create = "CREATE DATABASE $dbname";
$db_selected = mysqli_query($db_conn,$db_create);
if ($db_selected) {
echo "Database $dbname created successfully\n";
mysqli_select_db($db_conn,$dbname);
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
?>

i got a solution out of it !
please check weather its a good method and best practice to add database !
$db_conn = mysqli_connect($server,$user,$pwd);
if (!$db_conn) {
die("Connection Error".mysqli_error());
}
echo "Connected Successfully";
$db_select = mysqli_select_db($db_conn,$dbname);
if (!$db_select) {
// If we couldn't, then it either doesn't exist, or we can't see it.
//Create Database Query
$db_create = "CREATE DATABASE IF NOT EXISTS $dbname";
$db_selected = mysqli_query($db_conn,$db_create);
if ($db_selected) {
echo "Database $dbname created successfully\n";
} else {
echo 'Error creating database: ' . mysqli_error() . "\n";
}
}
else{
echo "Database $dbname is connected";
}

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";
?>

I have sort of php code, in this i want to send connection variable ($conn) into another page so that i can create table for database dynamically

<?php
$a = $_GET['host'];
$b = $_GET['username'];
$c = $_GET['password'];
$d = $_GET['db_name'];
define("localhost",$a);
define("username",$b);
define("password",$c);
define("db",$d);
$conn = mysqli_connect(localhost,username,password);
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt create database query execution
$sql = "CREATE DATABASE $d ";
if(mysqli_query($conn, $sql)){
echo "Database demo created successfully";
header("Location:create_table.php");
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
In this i need to send $conn with header to send it to create_table.php page.
because i am getting details of connection from user. so i cannot include this file into create_table.php . please help to find out how can i send connection variable into another file.
<?php
$server= "localhost";
$user= "root";
$pass= "";
$conn= mysqli_connection($server, $user, $pass);
if(!$conn){
echo "Database Connection Install Failed ! ".mysqli_errno() ;
}
else {
echo "Database Connection Establiseh Successfully! ";
}
?>

Logic operation failure in php

I want to do some logic operation before updating the data in MySQL. However, I think there are some problems in my logic operation. I do not know which line causes the problem. Can anyone help?
<?php
session_start();
if ($_POST['meetingid'] > $_SESSION["id"]){
echo "ERROR: Wrong Meeting_ID. Update failed.<br>";
}
else if(empty($_POST['date'])) {
echo "ERROR: No empty data field is allowed. Update failed. (Date field)<br>";
}
else if(empty($POST['committee'])) {
echo "ERROR: No empty data field is allowed. Update failed. (Committee field)<br>";
}
else if(empty($_POST['session'])) {
echo "ERROR: No empty data field is allowed. Update failed. (Session field)<br>";
}
else{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'admin123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$meetingid = $_POST['meetingid'];
$date = $_POST['date'];
$committee = $_POST['committee'];
$session = $_POST['session'];
$sql = "UPDATE `meeting` SET `Date`='$date' ,`Committee`='$committee' ,`Session`='$session' WHERE `Meeting_ID`='$meetingid'" ;
mysql_select_db('imo resolution v.2');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
else{
echo "Updated data successfully<br>";
}
mysql_close($conn);
}
?>
Here is the code refactored (untested)
Some notes about what has changed:
Changed the initial condition because what would happen if $_POST['meetingid'] was less than $_SESSION['id'] but not equivalent.
Combined the empty() statements together. Your code before would not display correctly if your form had more than 1 empty field.
mysql_ functions are deprecated. Don't use them! Use mysqli_ instead.
Added some basic santisation through mysqli_real_escape_string() function
Removed mysql_select_db() as you can set the database through mysqli_connect()
Updated the code to check whether the INSERT statement was successful
<?php
session_start();
if ($_POST['meetingid'] !== $_SESSION['id']) {
echo 'ERROR: Wrong Meeting ID';
} else if (empty($_POST['date']) || empty($_POST['committee']) || empty($_POST['session'])) {
echo 'Error inserting due to empty field';
print_r($_POST);
} else {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbdb = 'imo_reslution_v.2';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbdb);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
$meetingid = mysqli_real_escape_string($conn, $_POST['meetingid']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$committee = mysqli_real_escape_string($conn, $_POST['committee']);
$session = mysqli_real_escape_string($conn, $_POST['session']);
$sql = "UPDATE `meeting` SET `Date`='$date' ,`Committee`='$committee' ,`Session`='$session' WHERE `Meeting_ID`='$meetingid'" ;
$retval = mysqli_query( $sql, $conn );
if( mysqli_infected_rows() == 0 ) {
die('Could not update data: ' . mysqli_error());
}else {
echo "Updated data successfully<br>";
}
mysqli_close($conn);
}
?>
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
As per mulqin suggestion (untested)
try to use prepared statement to avoid sql injections
<?php
session_start();
if ($_POST['meetingid'] !== $_SESSION['id']) {
echo 'ERROR: Wrong Meeting ID';
} else if (empty($_POST['date']) || empty($_POST['committee']) || empty($_POST['session'])) {
echo 'Error inserting due to empty field';
print_r($_POST);
} else {
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "root"; //username
$password = "admin123"; //password
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,`imo_resolution_v.2`) or die("Opps some thing went wrong");
$stmt = $conn->prepare("UPDATE `meeting` SET `Date`=? ,`Committee`=? ,`Session`=? WHERE `Meeting_ID`=? ");
$stmt->bind_param('ssii',$date,$committee,$session,$meetingid);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$row_count= $stmt->affected_rows;
$stmt->close();
$conn->close();
if($row_count>0)
{
echo "Updated data successfully<br>";
}
else
{
echo "Not Updated";
}
}
?>

No Database Selected - Error

I work with the following example-code:
<?php
// Create connection
$conn = mysqli_connect('mysql3.00*****', 'a7552070******', 'fjewifn****');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO diequizapp(appid, itemid, data) VALUES ('John', 'bon', 'jovi')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
but I get an No Database selected back.
Can somebody please tell my why ?
I took this example from a tutorial.
Auf Wiedersehen, Andre
You need to pass the database that you want to select data from as the last parameter in mysqli_connect(host, username, password, database)
You can also take the second approach and use the mysqli_select_db($connection, DATABASE) function
you did not given the database name try like this
$dbname = "****"; //database name
$dbhost = "localhost"; // host name localhost
$dbusername = "***"; // username of the mysql
$dbpassword = "***"; // password of the mysql
$link = mysqli_connect($dbhost,$dbusername,$dbpassword,$dbname);
if (mysqli_connect_errno($link))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
then run your query........

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