mySQL Fails When executed from PHP without Error Message - php

I'm trying to execute an SQL Statement but it fails without producing an error message. Please can you let me know what is going wrong?
I'm using the same database connection that I've used successfully in other pages for SELECT, and INSERT statements. I've tested the SQL statement successfully in phpMyAdmin. But when executed from php it fails without error message, all other statement in the site work fine.
Database connection include
<?php
$servername = "xxxxxx";
$username = "xxxxxx";
$password = "xxxxxx";
$dbname = "xxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
// Connect to DB
include 'incDBConnection.php';
$SQL = "SELECT * from tbl_Properties";
echo "<br/> <br />";
if ($conn->query($SQL) === TRUE) {
echo "Record updated successfully";
} else {
echo "<br/> <br />Error updating record: " . $conn->error;
}

Related

Fatal error: Uncaught mysqli_sql_exception: Unknown database 'test_db'. I keep getting this error even though I programatically created the database

Here is the code
<?php
$servername = "localhost";
$usrname = "root";
$pwd = "";
$db = "test_db";
// connect to the database
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
if (!$conn){
die('connection failed' . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS test_db";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
?>
I am not sure what is going on as I am sure i made no errors while typing. As it keeps showing me that there is an unknown database despite the fact i made a CREATE DATABASE statement.
I do not know if there is something else i need to do but by all measures the code should work.
It is supposed to echo the "Database created successfully" or the error message.
`<?php
$servername = "localhost";
$usrname = "root";
$pwd = "";
//$db = "test_db";
// connect to the database
$conn= mysqli_connect($servername, $usrname, $pwd);
if (!$conn){
die('connection failed' . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS test_db";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
?>`
Your code is fine, You just have to remove $db from mysqli_connect().
Because you are requesting to connect "test_db" to this database which already not exists.
<?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);
?>
Reference
How do I create a database if it doesn't exist, using PHP?
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
You are trying to connect to a database that did not initially exist, so you get a fatal error.
Try creating new database using try catch blocks
try{
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
}cath(Exception $e){
//your code
}

How to Create a postgresql database from a PHP form

I'm working in a web app with PHP and Postgresql. I`m looking for a PHP code to create a database online using a PHP form that sends the name, template, UTF8, etc.
Something like this for MYSQL but for with Postgresql:
<?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);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>

PHP: Is it possible to execute a MySQL statement to create a DATABASE even though I am already connected to my database?

I've been wondering if it's possible to create a new database using mysqli_query() even though I'm already connected to my database?
$create_new_db = mysqli_query($user_conn, "CREATE DATABASE sample_db");
if($create_new_db) {
echo 'new database has been created';
} else {
echo 'Error while creating new database.';
}
my variable $user_conn has a database connection named db_maindb. So is it still possible to create a new database when I'm connected to my db_maindb database?
Like you have in you code ..
assuming you can connect to an existing database and your connected user has grant for create database you can
<?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);
}
// Create database
$sql = "CREATE DATABASE sample_db";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>

Deletion of row in MySQL using php

I have been developing a CRUD application using PHP & MySQL database.
I was succeeded by creating, displaying, updation parts. But I stuck at the deletion part of a row from a database table.
I tried my best solving all the PHP shown errors but now in final it is now showing a message which I wrote to echo in case of failure.
I request someone to please help me with this problem.
Thankyou in advance.
Code I wrote for deletion:
//include database connection
include 'db_connect.php';
//$mysqli->real_escape_string() function helps us prevent attacks such as SQL injection
$query = "DELETE
FROM `grocery`
WHERE `GrocerID` ='".$mysqli->real_escape_string($_GET['id'])."'
limit 0,1";
//execute query
if( $mysqli->query($query) ){
//if successful deletion
echo "User was deleted.";
}else{
//if there's a database problem
echo "Database Error: Unable to delete record.";
}
$mysqli->close();
?>
Code I wrote for delete link in display table:
//just preparing the delete link to delete the record
echo "<a href='delete.php?id={$GrocerID}'>Delete</a>";
Code I wrote for db config:
<?php
//set connection variables
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
?>
I tried this and got working, can you update the code and see if this works?
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
// Delete row
if ($mysqli->query (sprintf( "DELETE FROM grocery WHERE email = '".$mysqli->real_escape_string($_GET['id'])."' LIMIT 1") )) {
printf ( "Affected Rows %d rows.\n", $mysqli->affected_rows );
}
I hope this helps.
Provide a connection :
if( $mysqli->query($con, $query) ){

php store session variable in mysql database

I have a website in PHP. I try to store the session variable $_SESSION['user_name'] to a mysql database when a logged in user visits a specific webpage on my site.
<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users
VALUES ('.$_SESSION['user_name'].')';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Error message:
Notice: Undefined variable: _SESSION in /opt/lampp/htdocs/succes.php on line 16
Tried a bunch of things but can't figure it out. What is wrong here?
You need to call session_start() at the beginning of your script (before using any $_SESSION variables). Also, you need quotes around the variable in you query:
$sql = 'INSERT INTO users
VALUES ("'.$_SESSION['user_name'].'")';
Please note that this is not safe; you are wide open to SQL injection. Instead, you should use prepared statements:
<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users
VALUES (?)';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $_SESSION['user_name']);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Before you use any $_SESSION variables you need to call session_start().
Of topic a bit though, something to look into PDO. It can be a bit a tad slower than mysqli() however supports many more Database types. Here is a good article on Tuts+ explaining some of the differences as well as explaining essential security steps.
If I could be a bit biased I have created a PHP Class for PDO Connections which can be found on GitHub

Categories