PHP MySQL - Error: No Database selected - php

I am trying to read and write to a database. Here is the code I have so far:
$mysql = mysqli_connect("example.com", "johndoe", "abc123"); // replace with actual credidentials
$sql = "CREATE DATABASE IF NOT EXISTS dbname";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating database: " . mysqli_error($mysql);
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($mysql);
$mysql = mysqli_connect("example.com", "johndoe", "abc123", "dbname"); // replace with actual credidentials
$sql = "CREATE TABLE IF NOT EXISTS Users(ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(ID), username CHAR(15), password CHAR(15), email CHAR(50))";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating table: " . mysqli_error($mysql);
}
$sql = "INSERT INTO Customers(username, password, email) VALUES(" . $username . ", " . $password . ", " . $email . ")";
if (!mysqli_query($mysql, $sql)) {
echo "Error: " . mysqli_error($mysql);
}
mysqli_close($mysql);
However, when I try to run it, it has an error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , )' at line 1
Could anybody tell me how to fix this?

Please check syntax of mysqli, it takes 4 parameters.You also have to provide database name.
$link = mysqli_connect("myhost","myuser","mypassw","my_db");

You're missing database in mysqli_connect() call
$link = mysqli_connect("hostname","username","password","database") or die("Error " . mysqli_error($link));

Obviously the answer is in your error. You didn't select any database. When using this function mysqli_connect specify the database you want to connect to.
Here is the syntax of the function: http://www.w3schools.com/Php/func_mysqli_connect.asp .
1) Create your database outside of your application
2) Specify mysqli_connect with the database you want to select.
You can also use another function called mysqli_select_db . You can find the sytanx here : http://www.w3schools.com/php/func_mysqli_select_db.asp .
As already stated in the comment, you will also have to replace : "example.com" with your ip address, if you are running locally replace it with 127.0.0.1:3306 , if you didn't change the port when you installed your mysql database / "johndoe" with your database account, you can change that to "root" / "abc123" with your root account password DEFAULT : "" .
Good luck !

First check mysqli_select_db if it returns false then create database.
try like this:
$mysql = mysqli_connect("example.com", "johndoe", "abc123") or die(mysqli_connect_error()); // replace with actual credidentials
if (!mysqli_select_db($mysql,'hardestgame_accounts')) {
$sql = "CREATE DATABASE IF NOT EXISTS hardestgame_accounts";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating database: " . mysqli_error($mysql);
}
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "CREATE TABLE IF NOT EXISTS Users(ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(ID), username CHAR(15), password CHAR(15), email CHAR(50))";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating table: " . mysqli_error($mysql);
}
mysqli_close($mysql);
here is a good answer: Php mysql create database if not exists

Try using mysql_select_db in between the database connection and the table creation.
Also, mysql_ is deprecated, please use mysqli_ instead

Use ` backticks for MYSQL reserved words...
your table name is reserved word for MYSQL...
Change your table name.

Related

I have a domain 'itcircle.net' which is hosted in 'freehosting.com'. Now i want to create a table in mysql

My database name is "itcircle_s" user is "itcircle_ss"
Now I want to create a table name "simple_tb".
But I failed. My code is like below:
$con=mysql_connect("localhost","root","")or die(mysql_error());
$db=mysql_select_db("s",$con)or die(mysql_error());
if(mysql_query("CREATE TABLE IF NOT EXISTS simple_tb(id int(255) NOT NULL AUTO_INCREMENT,n varchar(40) ,PRIMARY KEY ( id ));",$con)){
echo"TABLE created";
} else {
echo"Error creating database: ".mysql_error();
}
mysql_close($con);
You have a problem on your script because you are using user 'root' to connect to it .
Check below : replace my_password with your password.
<?php
$con = mysqli_connect("localhost","itcircle_ss","my_password","itcircle_s");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql=mysqli_query($con," your query goes here ");

How to specify a database in a query in MySQL?

I am writing a PHP script to log in to a website. Right now, I am making a "My Profile" page, where all you info, like Username and Email are displayed. I have MySQL set up. In MySQL, a database named registeredusers holds all the info like username, password, and email. I can use PHPMyAdmin to view it, but I must first select the database registeredusers to run a query on it. This is the command I am trying to run.
SELECT username FROM users WHERE id = 1
My table inside registeredusers database is called users. The username value is username. Id is just an incrementing number I use to identify each different account.
I want to be able to run this in the global query box. What would I have to change in the code to select registeredusers as the database I want to run it on?
If using mysqli:
$mysqli = new mysqli("localhost", "root", "root", "registeredusers");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Here is some more information on that http://php.net/manual/en/mysqli.quickstart.connections.php
If you are using PDO (PHP5), you can use the following code which was taken from here (http://php.net/manual/en/class.pdostatement.php):
$host = "yourHost";
$user = "yourUser";
$pass = "yourPass";
$db = "yourDB";
$cursor = "cr_123456";
try
{
$dbh = new PDO("pgsql:host=$host;port=5432;dbname=$db;user=$user;password=$pass");
echo "Connected<p>";
}
catch (Exception $e)
{
echo "Unable to connect: " . $e->getMessage() ."<p>";
}

get variable in php leading to database not accepted

so i have this php code :
session_start();
$servername = "localhost";
$username = "root";
$dbname = "3890ask3_db";
$con = mysql_connect($servername, $username, "", $dbname)
or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($dbname,$con)
or die("Failed to connect to MySQL: " . mysql_error());
$query = mysql_query("SELECT * FROM register where Username = '$_SESSION[Username]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(isset($_GET['selecttoy']))
{
$clname=$row['Name'];
$clsurname=$row['Surname'];
$clemail=$row['Email'];
$stoy=$_GET['selecttoy'];
$query2 = "INSERT INTO order (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('$clname', '$clsurname', '$clemail' , '$stoy', ' ' )" ;
if (mysql_query($query2)) {
echo "Order created successfully!";
} else {
echo "Error: " . "<br>" . mysql_error($con);
}
}
?>
The php page can actually read the get variable,but as soon as i try to insert something in the database, i get this error message:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('mar', 'kyr', 'dgg' at line 1"
i tried everything but no result...can someone please help me?
thanks in advance....
You can not use order directly because it's reserved word. try to enclose it in (``). Like below:-
$query2 = "INSERT INTO `order` (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('$clname', '$clsurname', '$clemail' , '$stoy', ' ' )" ;
Note:- Try to add sql error reporting code always.
stop using mysql_*, use mysqli_* or PDO.
your above code is open for SQL Injection. thanks.

How to connect to a new database using PHP MySQL

So I've been trying to learn how to use MySQL with PHP, and I've managed to create a connection and create a database along with a table. What I don't know how to do is create the database along with the tables all in one go.
What I mean by this is easier shown in my code (Which will show unable to connect error message because the connect method is trying to connect to a database that does not exist.
<?php
$servername = isset($_POST["servername"]) ? $_POST["servername"] : '';
$username = $_POST["username"];
$password = $_POST["password"];
$dbname = $_POST["dbname"];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
So, all I am trying to achieve is Connect to MySQL, create the database, create a table for said database and close the connection all within one .php file.
On a side note, due to the user being able to define a database name ($dbname), how would I add this value into the MySQL code above? I heard somewhere that you're supposed to add the variable into quotes? So '$dbname'. Any help with that would be good too! Thanks in advance!
Okay, the reason for this question is because I am creating a setup-type page where the user will be able to connect to their own database, allowing them to give it a name and connect using their credentials. Obviously I am not very experienced within this field, I hope I have explained it better.
All the code you have looks fine to me. The only thing I think your missing is after you create a database you have to call
$conn->select_db("myDB");
Also if you want to have the database name be $dbname then
$sql = "CREATE DATABASE myDB";
should be
$sql = "CREATE DATABASE " . $dbname;
If I didn't cover your problem please give me more detail on your problem.
where you passing all of this variable ?
$servername = isset($_POST["servername"]) ? $_POST["servername"] : '';
$username = $_POST["username"];
$password = $_POST["password"];
$dbname = $_POST["dbname"];
just simply hardcode the servername, username, password and your dbname.

Failed to insert into MYSQL table

Right, im just doing a little bit of testing before building my project and i keep getting errors. I'm using WAMP and phpmyadmin for the database.
I have managed to connect to the database successfully, but cannot seem to insert data into the table.
Ultimately i want to insert data the user uploads from a form but I'm using static figures for now to get the INSERT working correctly.
So when the user clicks submit, i want this to run;
PHP/MYSQL:
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "#########");//I have hashed out the password here
define("DB_NAME", "uploads");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
$query = "INSERT INTO ";
$query .= "customers ";
$query .= "(`reference`, `doc1`, `doc2`, `doc3`) ";
$query .= "VALUES ('123456', 'newimage1.jpg', 'newimage2.jpg', 'newimage3.jpg')";
$result = mysqli_query($connection, $query);
if ($result) {
echo "created insert";
} else {
// Failure
echo "failed to insert";
}
Okay so the database connection works as it throws no errors, however i just get "failed to insert".
Any ideas guys? if you need more info just post a comment
EDIT:
echo the $query i get:
INSERT INTO customers(reference, doc1, doc2, doc3) VALUES ('123456', 'newimage1.jpg', 'newimage2.jpg', 'newimage3.jpg')failed to insert
and its the same if i remove the space on customers
WORKING:
The fields where varchar 11, and the text was too long to be inserted. Very stupid mistake haha, relatively new to using MYSQL with php. But thanks for the help!
As per your question there is a mistake in you table structure change the varchar size (increase more than 11 )to insert data int table for column doc1 doc2 doc3

Categories