I have a problem trying to connect to a my_sql database. I'm very new to PHP, so this is probably a very simple problem. At the top of my index.php I have the following code:
try
{
echo 'here 1';
$db=mysql_connect('localhost', 'root', 'password') or die(mysql_error());
echo 'here 2';
if(!$db)
{
echo 'here 3';
}
$db_selected=mysql_select_db("alphaes", $db);
echo 'here 4';
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
echo 'here 5';
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
The problem is that the only output from the page is 'here 1'. If I comment out all the database code the page loads ok. There's something wrong with the connect code, however I don't see the mysql_error or exception written to the browser. Do these get logged to a file somewhere? Can anyone see a problem with the code?
The username and password are correct.
Any help is much appreciated,
Mark
here's a very simple example that uses the newer mysqli extension in conjunction with exception handling:
<?php
ob_start();
try
{
$db = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);
if ($db->connect_errno)
throw new exception(sprintf("Could not connect: %s", $db->connect_error));
$sqlCmd = "select * from users order by username";
$result = $db->query($sqlCmd);
if(!$result) throw new exception(sprintf("Invalid query : %s", $sqlCmd));
if($db->affected_rows <= 0){
echo "no users found !";
}
else{
$users = $result->fetch_all(MYSQLI_ASSOC);
foreach($users as $u) echo $u["username"], "<br/>";
}
$result->close();
}
catch(exception $ex)
{
ob_clean();
echo sprintf("zomg borked - %s", $ex->getMessage());
}
if(!$db->connect_errno) $db->close();
ob_end_flush();
?>
Thanks to everyone who replied - turns out that it was very 'beginners' error - mysql was not enabled in the php configuration file.
If it only outputs "here 1" that means the code stops at:
$db=mysql_connect('localhost', 'root', 'password') or die(mysql_error());
I think it is because mysql_error needs to get the last connection from mysql_connect, and the connection fails.
From the docs:
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
(emphasis mine)
http://php.net/manual/en/function.mysql-error.php
Try changing mysql_error with some string output and see if it works. If it works, then the error is in the database connection.
Try without a password: $db=mysql_connect('localhost', 'root', '') or die(mysql_error());
Related
Even if I have used LAMPP many times, this time something goes wrong. When I visit the browser(chrome) nothing echos. Here is my code:
index.php
<?php
error_reporting(E_ALL); /*after edit*/
$link = mysqli_connect('localhost', 'root', 'root', 'db');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($link);
?>
Do I miss something? The output is nothing. By the way i write my files in
var/www/html/my_pages
and i call it this way: localhost/my_pages. Simple echos are working and php in general is fine. Something goes wrong with my db connection.
Use this code
<?php
$link = mysqli_connect('localhost', 'root', 'root', 'db');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
else
{
echo 'Connected successfully';
}
?>
Yes probably, because mysqli_connect() method return the object, not Boolean value.
You can verify the connection with the following code:
if($link->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
return false;
}
else{
echo "Connection Successful";
return $link;
}
Why not using PDO.
$dsn = "mysql:host=localhost;dbname=db";
try {
$pdo = new PDO($dsn, "root", "");
} catch (PDOException $ex) {
$ex->getMessage();
}
with PDO you can change anytime you need the Db vendor:
http://php.net/manual/en/book.pdo.php
<?php
echo phpinfo();
?>
Run this file and get all PHP and apache details. Search for mysqli support in it. If it is supported, you should have something like below.
Also check for your root directory
Thanks everyone for the response! I found the problem. Something went wrong and mysqli wasn't enabled in php. That's why i had this error Fatal Error:Call to undefined function mysqli_connect() in /var/www/html/diamond/index.php on line 8 I reinstalled php and problem solved :)
I am working on converting some PHP code from mysql to mysqli. I have created an error and am unable to understand how to fix it. Any suggestions would be greatly appreciated.
The code looks like this:
<?php
include ("admin/includes/connect.php");
$query = "select * from posts order by 1 DESC LIMIT 0,5";
$run = mysqli_query($conn["___mysqli_ston"], $query);
while ($row=mysqli_fetch_array($run)){
$post_id = $row['post_id'];
$title = $row['post_title'];
$image = $row['post_image'];
?>
The error produced is: Fatal error: Cannot use object of type mysqli as array
The error is being called out on this line:
$run = mysqli_query($conn["___mysqli_ston"], $query);
In the line above $conn is a variable from the database connect file which has this code:
<?php
// Stored the db login credentials in separate file.
require("db_info.php");
// Supressing automated warnings which could give out clues to database user name, etc.
mysqli_report(MYSQLI_REPORT_STRICT);
// Try to open a connection to a MySQL server and catch any failure with a controlled error message.
try {
$conn=mysqli_connect ('localhost', $username, $password) or die ("$dberror1");
} catch (Exception $e ) {
echo "$dberror1";
//echo "message: " . $e->message; // Not used for live production site.
exit;
}
// Try to Set the active MySQL databaseand catch any failure with a controlled error message.
try {
$db_selected = mysqli_select_db($conn, $database) or die ("$dberror2");
} catch (Exception $e ) {
echo "$dberror2";
//echo "message: " . $e->message; // Not used for live production site.
exit;
// We want to stop supressing automated warnings after the database connection is completed.
mysqli_report(MYSQLI_REPORT_OFF);
}
?>
This line
$run = mysqli_query($conn["___mysqli_ston"], $query);
should be
$run = mysqli_query($conn, $query);
If you're migrating to mysqli, you should really read these docs at least.
The proper way to use a mysqli connection:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}
?>
you should also consider utilizing mysqli's prepared statements
I have connected to a database for the first time with oop and stright away come up with an issue, below is my code which i'm struggling with:
$q = 'SELECT * FROM test';
$sqli->query($q);
if($sqli->query($q)){
echo "worked";
}
if($sqli->error){
echo $sqli->error;
}
I have checked for errors when connecting to the db and that works fine, but when I run this query I get no output, why? I expected an error or "worked", but have got neither.
Whats happening?
I have put some comments in the source code to help:
$q = 'SELECT * FROM test';
//$sqli is the result of a
//new mysqli("localhost", "user", "password", "database");
$resource = $sqli->query($q); // this returns a resource or false
if(!$resource) {
echo $sqli->error;
die; // do not process further
}
// process the results
$rows = $resource->fetch_all();
if ($rows) { // check if there are rows
echo "worked";
}
else {
echo "query is ok, but there are no rows";
}
You could also use $resource->fetch_object() which returns an object for output. Therefore if you wanted to print specific data from the result set, you would do something like
//table test.Name and test.Country
while ($rowobj = $resource->fetch_object()){
printf ("%s (%s)\n", $rowobj->Name, $rowobj->Country);
}
Good luck,
You could use this method, I hope it's what you are looking for. You will need to define the DB first. Then you can connect in OOP and test the connection is true or exit();
Let me know if this works for you. You can also define the DB in an external file and just do an include(); towards the top of your script for any pages needing connection to the DB.
define("SERVER","IP Address");
define("USER","DB USERNAME");
define("PASSWORD","DB PASSWORD");
define("DATABASE","DB NAME");
// This is for connection
$mysqli = new mysqli(SERVER, USER, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit();
}
I am starting to use PDO and I successfully connected to MySQL using PDO. However, when I try to SELECT stuff from my DB, nothing happens. Nothing is echoed. (even though I have records in that table, and the column username exists) No error in my PHP log.
I am using MAMP and all PDO components seem to be working in phpinfo() (since I was able to connect to db in the first place)
Please let me know what could have gone wrong. Thanks a lot
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
$stmt=$connection->prepare("SELECT * FROM users");
$stmt->execute();
while ($row=$stmt->fetch(PDO::FETCH_OBJ)){
echo $row->username;
}
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
You need to tell PDO that you want it to throw exceptions:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Following your comment below, it is apparent that your DSN is incorrect. It should be:
$connection = new PDO('mysql:host=localhost;dbname=my_db','my_username','xxxxxxx');
Note that the syntax is dbname= rather than dbname: (which you had originally).
First, get your query out of your PDO connection segment...
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
Then, do it.
<?php
$SQL = 'SELECT * FROM users';
foreach($connection->query($SQL) as $row){
print $row['username'] . "\n".'<br />';
}
?>
Why not ask PHP?
catch(Exception $e)
{
die($e);
}
Looks like your either don't have data in that table or have an error:
Try to add this code after $stmt->execute();:
$arr = $sth->errorInfo();
print_r($arr);
I have this code:
$link = mysql_connect("localhost", "ctmanager", "pswsafgcsadfgG");
if ( ! $link )
die("I cannot connect to MySQL.<br>\n");
else
print "Connection is established.<br>\n";
print "a";
if ( mysql_create_db("ct", $link) )
print "AAA";
else
print "BBB";
print "2";
die();
And this is the output:
Connection is established.
a
So, I cannot understand how it's possible that neither "AAA" no "BBB" is outputted. Is it because program dies at mysql_create_db?
You probably guessed right. Try adding:
error_reporting(-1);
ini_set('display_errors', 'On');
at the very top of your script. You will get more details I'm sure. Post your findings and I'll update my answer if needed to.
Also, if you use PHP 5, you can try:
try
{
if (mysql_create_db("ct", $link))
echo 'AAA';
else
echo 'BBB';
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
maybe this will catch something...
Also, as František Žiačik pointed out with his link:
The function mysql_create_db() is
deprecated. It is preferable to use
mysql_query() to issue an sql CREATE
DATABASE statement instead.
mysql_create_db is deprecated in PHP5, maybe there even does not exist anymore.
See http://php.net/manual/en/function.mysql-create-db.php for an example how to do it.
I think you're right it is failing at mysql_create_db but i would guess it's the SQL that you're passing into it. are you trying to create a DB called "ct"? If so i'd try "CREATE DATABASE ct"
What PHP version are you running? According to the documentation, mysql_create_db is depracated, and a CREATE DATABASE query should be issued instead.
if (mysql_query("CREATE DATABASE ct", $link))
print "AAA";
else
print "BBB";
I think this would be the alternate way hopefully.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$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";
}
?>