I am a student.
I'm trying to deliberately induce an error in
$db_connect->select_db($db_name);
to check the error handling, but it won't give out an error?
The actual database name is 'cart', but i am using 'cartxx' to try and induce an error, but nothing happens, it runs as if there is no error. I don't have a database named 'cartxx'.
<?php
session_start();
$host = 'localhost'; // connects to the host server
$db_name = 'cartxx'; // name of the database we are connecting to
$db_username = 'root'; // username for database
$db_password = ''; // password for database
$db_connect = new mysqli($host, $db_username, $db_password); // connect to mysql
// If error
if (mysqli_connect_errno()) {
echo('Connection to database failed: ' . mysqli_connect_error());
exit();
}
// Select database
$db_connect->select_db($db_name);
// If error
if (mysqli_connect_errno()) {
echo 'Connection to database {$db_name} has failed: ' . mysqli_connect_error();
exit();
}
Thanks.
you need to pass default db name in connection string directly. if you need connect to one more database you can use select statment
$db_connect = new mysqli($host, $db_username, $db_password, $db_name);
for more :- http://php.net/manual/en/function.mysqli-connect.php
mysqli::selectdb will NOT return false if you give him an incorrect database name.
This function suits better a "i want to switch from database X to database Y" scenario, and will stay connected to database X if database Y is not found.
You can check the manual for this function.
A better way to select the database at connection is to use the mysqli constructor.
Related
I am creating a form that will take a person's name and email and see if the email exists in the database already but I can't get the database to be selected. The mysql_error() won't display the error either. Is there something wrong with my code for selecting the database? All it shows is the hardcoded text "Could not select database because" then nothing. I replaced all the variables associated with the database with random fillers so as not to give away my info but everything I have is correct regarding that.
$host = "host";
$user = "user";
$password = "pass";
$database = "db";
$port = xxxx;
$table = "table";
// Create connection
$conn = mysqli_connect($host, $user, $password, $database, $port);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection Successful";
mysqli_select_db($database)
or die("Could not select database because".mysqli_error());
// check if the username is taken
$check = "select email from $table where email = '".$_POST['email']."';";
$qry = mysqli_query($check)
or die ("Could not match data because ".mysqli_error());
$num_rows = mysqli_num_rows($qry);
if ($num_rows != 0) {
echo "Sorry, there the username $username is already taken.";
}
Don't call mysqli_select_db. You've already selected your database with the fourth parameter to mysqli_connect.
You only need to call mysqli_select_db if you want to access a different database after the connection has been established.
Also, Raptor is correct that if you call procedural mysqli_error() you must pass it a connection handle.
For Procedural style mysqli_error(), you must supply the MySQLi DB link as parameter:
mysqli_select_db($database)
or die("Could not select database because" . mysqli_error($conn));
But it's useless to call mysqli_select_db() as you already specified the DB schema in mysqli_connect().
Additionally, your SQL is vulnerable to SQL Injection attack. Always escape the parameter before putting into SQL statement, or use prepared statements.
try this code
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>
I am new in PHP and would need some explanation. Here is a code where we connect to MySQL with PHP. Can you please explain me where is the statement that makes the connection? I can see only that we define what the value of $conn is, but does it mean execution as well? The other thing is: where do we create the database? I can see that we give the string "CREATE DATABASE myDB" as a value to $sql and we have an if statement, but does the expression ($conn->query($sql) === TRUE) also evaluated? It is strange for me, can somebody please explain it to me?! :) Thanks!
<?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();
?>
Here is a simple explanation of which lines do what. If you would like to know specifically what the individual parts of these mean, then please say which ones so they can be further explained to you. Or the correct links pointed to.
I notice that you are using the W3Schools example, as an almost exact copy and paste. Have you installed MySQL on your machine and created a username and password?
<?php
$servername = "localhost"; // This is the location of your server running MySQL
$username = "username"; // This is the username for MySQL
$password = "password"; // This is the password for MySQL
// Create connection
$conn = new mysqli($servername, $username, $password); // This is where you create a connection
// Check connection
if ($conn->connect_error) { // This checks if the connection happened
die("Connection failed: " . $conn->connect_error); // and produces an error message if not
} // otherwise we move on
// Create database
$sql = "CREATE DATABASE myDB"; // This is the SQL query which is sent to the MySQL server
if ($conn->query($sql) === TRUE) { // When the if statement begins here, it executes the query and test if it returns true
echo "Database created successfully"; // If it returns true then here is the message is returns
}
else {
echo "Error creating database: " . $conn->error; // Or if there was error with the query this is returned
}
$conn->close(); // Close the connection when it is no longer in use
?>
Although, your question does not belong here (This place is to help with your coding issues), but I will give you a bit explanation.
PHP reads each line and EXECUTES It. the create connection part opens a new connection using the "new" object and save it a variable ($conn),
($conn->connect_error) checks if the connection was successful with connect_error property. if it was connected, continue, or else through and error and stop.
If connection was successful, then create the database based on connection opened in variable ($conn).
Here's a MySQL pattern in PHP:
$username="username";
$password="password";
$database="username-databaseName";
// Opens a connection to a mySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$query = some query
$result = mysql_query($query);
I tried to replace most of it with a mysqli pattern and then stick the query part at the bottom like so:
//Database Information
$db_host = "localhost"; //Host address (most likely localhost)
$db_name = "username-databaseName"; //Name of Database
$db_user = "username"; //Name of database user
$db_pass = "password"; //Password for database user
/* Create a new mysqli object with database connection parameters */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
GLOBAL $mysqli;
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
// Search the rows in the markers table
$query = some query
$result = mysql_query($query);
However, I get this error message:
Invalid query: No database selected
What am I doing wrong?
First of all, you're calling mysql_query and not mysqli_query, like you intended to.
Second, since you're using the object oriented form, you need to call mysqli_query as a method:
$result = $mysqli->query($query);
In my script I link to a page that connects to my database :
include "connect.php";
connect.php
<?php
error_reporting(E_ERROR);
/* Allows PHP to connect to your database */
// Database Variables
$Host = "myhost";
$User = "username";
$Password = "password";
$DBName = "database";
// Connect to Database
$connect = mysql_connect($Host, $User, $Password)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($DBName)
or die ("Could not connect to database ... \n" . mysql_error ());
?
Then in another script I have an insert query:
include "connect.php";
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO mytable VALUES ('0','".mysql_escape_string($forename)."','".mysql_escape_string($surname)."', '".mysql_escape_string($username)."', '".mysql_escape_string($password)."', '".mysql_escape_string($email)."')";
if(mysql_db_query ($DBName, $Query, $Link)) {
$message = "You have successfully registered";
header("Location: register.php?message=".urlencode($message));
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
}
}
Why is this necessary :
$Link = mysql_connect($Host, $User, $Password);
Hasn't the connection already been established?
There is no point in doing this, especially as mysql_* functions will assume the last opened connection if none is given.
However, even with two calls to mysql_connect, only one connection is made. From the docs:
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters.
So by default, the existing connection will be returned.
<?php
// MySQL database connection file
$SERVER = "127.0.0.1"; // MySQL SERVER
$USER = "root"; // MySQL USER
$PASSWORD = "admin"; // MySQL PASSWORD
$link = #mysql_connect($SERVER,$USER,$PASSWORD);
$db = mysql_select_db("website");
?>
This is a database connecting code for chat program but it not connecting,Can any one pls help me to correct this code?
Drop the # infront of mysql_connect, it's used to suppress error which you don't want.
Also you need to check the return value of mysql_connect which is there in $link and make sure that it is not false before you proceed and to a DB select. Calling the function mysql_error when an error occurs gives you the reason for the error.
$link = mysql_connect($SERVER,$USER,$PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}