Newish to php. I have been trying to query a database, and I keep getting the exception thrown that the query could not be completed. I checked to make sure I was connecting to the database, and everything looked fine, until I dug deeper. It appears that the my code tells me that I am connecting to the database regardless of what I put in for a password, username, or even if I do not have this data defined. I don't get it. Originally I had the following code in a function, but I put it no its own page to debug:
<?php
echo'this is working so far <br>';
/*$db = 'fake';
$host = 'localhost';
$password = 'wrong';
$user = 'root';
*/
$result = new mysqli($host, $user, $password, $db);
if(!$result){
echo 'did not connect to database';
throw new Exception('Could not connect to database');
}
else{
echo'connected to database';
return $result;
}
It always tells me I am connected to the database..
Because you are mixing Object oriented style with Procedural style To check database connection
Procedural style
<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($link) . "\n";
mysqli_close($link);
?>
Object oriented style
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
?>
Read http://php.net/manual/en/mysqli.construct.php
Note:
OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error() function or the mysqli->connect_error property as in the preceding examples.
Source
That means if($result) check is always true no matter what. So no, you don't have that database connection but you are verifying it incorrectly leading you to believe you do.
Your check should be
if($result->connect_error)
// no luck
else
// game on
You should check connect_errno property which stores the error code from last connect call.
$mysqli = new mysqli($host, $user, $password, $db);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Related
<?php
/* die/exit operation*/
mysqli_connect('localhost','root','') or die ('The connection is lost');
echo 'connected';
?>
mysqli_connect or die functions working together fine in case of the both correct and incorrect host names.But no matter what username I am using,it is always showing 'connected'.Can anyone please tell me why it is happening?
I don't think your die statement will ever be reached.
mysql_connect is the alias for mysqli::connect and the object will be made.
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
To get a connection failure:
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
Here's my code.
<?php
$server = "localhost";
$uname = "replace it with anything";
$pswd = "";
$conn = mysqli_connect($server, $uname, $pswd);
if(!$conn){
die('Caught');
}
else{
die('Connected');
}
?>
No matter what I passed in the mysqli_connect() as username. It always returns true. In the case of the wrong password, it shows an error that accesses denied, but I don't know why, no matter what I enter in the username, it always returning true.
It does not return a boolean but an object which represents the connection. You can then check the object for connectivity. From the manual:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
Try
<?php
$mysqli = new mysqli("host", "username", "password", "database") or die($mysqli->error());
if ($mysqli->connect_errno) {
echo "error";
exit();
}
?>
$dc=fopen("numeu.txt","rb");
$row1=fgets($dc,120);
$row2=fgets($dc,120);
$row3=fgets($dc,120);
fclose($dc);
$servername="localhost";
$username="root";
$password='';
$database="Stildev";
$conn = new mysqli($servername, $username, $password, $database);
$sql="SELECT poza1,poza2,poza3,poza4,poza5,poza6 FROM postari WHERE utilizator='".$row2."' AND subiect='".$row1."' AND id2='".$row3."'";
$resultat=$conn->query($sql);
echo $resultat->num_rows;
This piece of code returns 0 rows
There is no error and sql query works just fine in MySQL console.
Also i discovered that withought WHERE clause the code works.How you explain that?
Is the password empty on purpose?
Try adding
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
Also, according to https://php.net/manual/ro/mysqli.query.php, this may help:
if ($result = $mysqli->query($sql)) {
echo $result->num_rows;
/* close result set */
$result->close();
}
If you are using several result-returning queries, close previous results with ->close();
<?php``
if(mysql_connect("localhost","root",""))
echo"connect";
else
echo "not connect";
?>
this is my code but it's not connected . give the error as warning
Warning: mysql_connect(): MySQL server has gone away in C:..\pro1.php on line 2
Warning: mysql_connect(): Error while reading greeting packet. PID=2296 in C:..\pro1.php on line 2
Warning: mysql_connect(): MySQL server has gone away in C:..\pro1.php on line 2
not connect
You can try using either MySQLi or PDO and their prepared statement to be more secure.
If you intend using just MySQL then use the below code to initialize your Database connection.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
For reference see http://php.net/manual/en/function.mysql-connect.php
Alternatively kindly use MySQLi
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
For reference see http://php.net/manual/en/mysqli.construct.php
If you consider using PDO then try
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
For reference see http://php.net/manual/en/pdo.connections.php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
http://php.net/manual/en/mysqli.construct.php
remove '' after php open tag and
try like this
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('dbname'); //your database name
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>
I'm trying to learn this stuff. Please be gentle.
Something is wrong here:
$dbhost = "localhost";
$dbname = "something_dbname";
$dbuser = "something_user";
$dbpass = "pwpwpwpw";
$dberror1 = "Could not connect to the database!";
$dbconnected = "you are connected!";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1);
$select_db = mysql_select_db($dbname . $dbconnected) or die ($dberror1);
where is my mistake? I want $dbconnected to show...
I can just as easily use
echo "hello";
it shows that I connect but I'm trying to get familiar with using multiple variables.
would this be better?
$dbhost = "localhost";
$dbname = "something_dbname";
$dbuser = "something_user";
$dbpass = "pwpwpwpw";
$dberror1 = "Could not connect to the database!";
$dbconnected = "you are connected!";
if ($mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname))
echo $dbconnected;
else die($dberror1);
Right now you are trying to connect to a database called something_dbnameyou are connected. The . concatenates variables into one string.
To fix your immediate problem, try this:
First, define $dbhost - I don't see it in your code.
Then change the last line to this:
$select_db = mysql_select_db($dbname) or die ($dberror1);
Then, just echo $dbconnected;
If you are not connected, the page will have called die, and will never reach the line that echos $dbconnected. If you are connected, the program will proceed to this next line and echo your success message.
Or you can do it more explicitly like this:
if ($select_db = mysql_select_db($dbname))
echo $dbconnected;
else die($dberror1);
To fix the bigger problem, DON'T use mysql_*. Read this for more information.
mysqli or pdo are far better options, and you can accomplish the same task easier, for instance, connecting to a db with mysqli is just:
$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
Or you can do it procedural style, which is closer to your current code. The following snippet is from the php manual, on the page I linked in the comment below.
$link = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($link) . "\n";
mysqli_close($link);
I'd strongly recommend using PDO. The connection string is similar and can be done using:
// I do not see $dbhost defined in your code. Make sure you have it defined first
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo $dbconnected; // will print out the connection success message
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
To answer your question about not using mysql_* functions, you can check out this