The mysqli_connect not working - php

I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.
$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?
My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?

Looks like MySQLi extension is not installed. What does var_dump(function_exists('mysqli_connect')); output?

Do you have error_reporting(E_ALL); And ini_set('display_errors',1); ?
The problem could be somewhere else.
Also how do you know it's failing if it is not priting the message in Die()?

for the host, if you are using "localhost:8889",
try using "localhost", and in the mysqli_connect() put in '8889' (or whatever port you are using) as an argument after the other arguements.
worked for me.
eg:
mysqli_connect('localhost','root','root','dbname','8889');

If you pass no values, I think MySQL is using defaults from the settings ini. So maybe this happens too if you pass empty values. In that case the connection could actually be established, and the result won't 'die'. Best thing is to use var_dump to check what $dbc contains after the call and continue from there.
But anyway, there is no way, PHP is going to tell you which settings to use if you don't remember them. :)

If you just installed mysql, then there exists only the root user, without a password (or blank one if you prefer). You are strongly encouraged to change that password AND create a new user and password for your application, who has only access to just one database, the one your application uses.
To change the root password, you may do this:
$ mysql -u root -p
Enter password: [press enter]
mysql> use mysql;
mysql> UPDATE user SET `password`=PASSWORD('your_desired_password') WHERE username='root';
# this next bit is to create a database and a username for your web application
mysql> CREATE DATABASE your_application_name;
mysql> GRANT ALL ON your_application_name.* TO 'your_username'#'localhost' IDENTIFIED BY 'yourpassword';
Obviously change all your_* values with correct ones.
For the reason why the die() gets not executed, do what #yes123 and #binaryLV had said (I think both are right, the mysqli is not installed, so it throws a E_FATAL_ERROR upon calling mysqli_connect(...) and as error_reporting is disabled (or maybe display_errors, or maybe both), you don't see that error.

//1 create a data base connection
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if (!$con) {
die('mysqli connection failed: ' . mysql_error() );
}
//2 connect with a data base
$db_select = mysqli_select_db($con , DB_NAME);
if (!$db_select) {
die('data base selection failed: ' . mysql_error() );
}
//3 create query
$result = mysqli_query($con, "select * from subjects");
if (!$result) {
die('query not successed: ' . mysql_error() );
}
//4 use the returned data
while ($row = mysqli_fetch_array($result)) {
echo $row['menu_name'] . " " . $row['position'] . "<br>" ;
}
//5 close connection...
if (isset($con)) {
mysqli_close($con);
}
Run this code if you have any query then feel free to ask me.

First check your php version
echo 'Current PHP version: ' . phpversion();exit;
if it is above 5.5 and even not working
then write script in your php file phpinfo(INFO_MODULES);exit;
it show all about php and check Mysqli listed or not. if not then inform to our server admministrator or if you have access then go to phpini file and enable mysqli (remove semicolon from it)

Try this:
$dbc = # mysql_connect('localhost', 'root', '') or exit('Not connecting.');

Related

Table does not exist, but it EXISTS

So I'm starting to learn how to use PHP to access MYSQL databases and after successfully connecting to the database. I want to select data from it. However I get the issue that the table doesn't exist. Yet, it exists when I check it in my phpmyadmin. I've checked spelling, capitalization, etc.. and nothing works. I've tried it with multiple databases and I get the same error. So I'm really confused as to whats going on because from the looks of it, there is NOTHING wrong with the code. I've tried running the SQL query in phpmyadmin just to verify that the query works.. and it does. I just get the error "Table 'test.blog_table' doesn't exist" with the code below
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_in_use = "test";
$conn = new mysqli($host, $user, $password, $database_in_use);
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
echo $conn->host_info . "<br>";
$sql = "SELECT * FROM blog_table";
$result = $conn->query($sql);
$result = $conn->query($sql) or die($conn->error);
$conn->close();
?>
So I'm just completely lost and have no idea whats going on with it.
Solved! I connected to the wrong database, which is why the tables were there, but weren't showing up. Since I was connecting to a different database and the one I created tables in didn't have the default port.
Probably you are missing the mysqli and the mysqlnd PHP extensions.
Also, I recommend you to use \PDO object to fetch queries to your DB instead of the mysqli driver, if you do it, you will be free to change in the future to a PostgreSQL DB for example anytime just changing the DSN in the constructor (you need for that the PDO and the pdo_whatever_db_driver (e-g.: pdo_mysql) extensions.

PHP: could not find database

i am having difficulty with connecting my database to mysql, i have tried many different ways of trying to get it to connect to my database, but none these methods seem to work. I am only new to php and i could be missing something, but i dont know what it is.
This is for a search engine, i have the form created.
I would think that my problem is coming from this line of code, mysql_connect("localhost", "root", "") or die("could not connect");?!
I was wondering if i could be told what is the problem and how to fix it, thank you so much.
here is my code below.
<?php
//connect
mysql_connect("localhost", "root", "") or die("could not connect");
mysql_select_db("search") or die("could not find database");
$output = '';
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","", $searchq);
$query = mysql_query("SELECT * FROM gp management system WHERE Title LIKE '%$searchq%' OR Description LIKE '%$searchq%' OR Keyword LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
}
else{
while($row = mysql_fetch_array($query)) {
$Title = $row['Title'];
$Description = $row['Description'];
$Keyword = $row['Keyword'];
$output .= '<div> ' .$Keyword. ' </div> ';
}
}
}
?>
SQL errors:
SELECT * FROM gp management system WHERE Title...
^^-- table name
^^^^^^^^^^ aliasing 'gp' as 'management'
^^^^^^-- extra unknown garbage
Table names shouldn't have spaces to begin with, but if you insist on having them, then you need proper quoting:
SELECT * FROM `gp management system` etc...
^--------------------^
Never output a fixed/useless "could not search" error. Have the DB tell you what went wrong:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^^
As your only new, you really should stop using mysql_ and change to mysqli_ or (my preference) PDO(). Your message in your title seems to be coming from your selectdb line, so you're actually connecting to the database fine, it's just not able to locate the schema that you are trying to use (i.e. "search" does not exist as a schema name in your DB environment). Unless that's not the error that you are getting, in which case it's a flaw in your actual SQL query. Without an accurate statement of what you are getting back on the screen when you try to run the script then not much can be done to help.
I would rather do somehow like I did ages ago, see below:
function db_connect($host, $username, $passwd, $db_name) {
$db = mysql_connect($host, $username, $passwd);
if (!$db) {
echo "Login to database failed: ";
echo mysql_error();
return false;
}
$result=mysql_select_db($db_name); //Select the database
if (!$result) {
echo "Cannot find the database: ".$db_name;
echo mysql_error();
return false;
}
return $db; //Database descriptor
}
However you shouldnt rely on the old MYSQL extension, but use MYSQLi.
EDIT: as #tadman pointed out there were a # sign infront the mysql_connect call, however there is an if statement for checking and a call to error output.
As others have said, your code is something of a mess - you seem to be new to programming, not just in PHP. But everyone has to start somewhere, so....
You might want to start by learning a bit about how to ask questions - specifically you have included a lot of code which is not relevant to the problem you are asking about - which is about connecting to MySQL. OTOH you have omitted lots of important information like the operating system this is running on and what diagnostics you have attempted. See here for a better (though far from exemplary example).
Do read your question carefully - the title implies an issue with mysql_select_db() while in the body of the content you say you think the problerm is with mysql_connect(). If you had provided the actual output of the script we would have been able to tell for ourselves.
You should be checking that MySQL is actually running - how you do that depends on your OS. You should try connecting using a different client (the mysql command line client, sqldeveloper, Tora, PHPMyAdmin....there are lots to choose from).
You should also check (again this is operating system specific) that your MySQL instance is running on the same port as is configured in your php.ini (or overridden in your mysql_connect() call).
MySQL treats 'localhost' as something different from 127.0.0.1 on Unix/Linux systems. If this applies to you try 127.0.0.1 in place of localhost.
or die("could not connect");
Does not help in diagnosing the problem. If instead you...
or die(mysql_error());
You will get a more meaningful response.
BTW: while writing code using the mysql extension rather than mysqli or PDO is forgivable, I am somewhat alarmed to see what appears to be medical information managed with no real security.

Accessing SQL Server 2012 from php under Linux

I'm in troubles...
I have a web server apache/php under linux, also i have another server with SQL Server database under windows. I need to get access to SQL Server database from my apache/php.
What do i need, please help. I have no idea how to start.
**sorry for my english.
Could do with a bit more clarification but I'll try my best..
If you mean through the code, you would do it like this:
Create a new php file called "connect.php" and insert all of this code, replacing the tags like USERNAME with the correct details.
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
// Create connection
$con = mysqli_connect("HOST","USERNAME","PASSWORD","DATABASE");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$select_db = mysqli_select_db($con, 'DATABASE');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($con));
}
?>
Next, EVERY file that requires a connection to the database, simply add
include("connect.php"):
To it at the start of the page and it should be fine :)
I seriously recommend you read up a bit more though as you seem like a bit of a newb (we all started somewhere)!
Hope this is what you were after!
Look for dblib, you will need to add that driver.

Can't connect to database "Fatal error: Call to undefind function mysqli_connect()"

I've been scouring this site for 5 hours now trying to get this sorted, I rarely ask for help but this is one of the weirdest and most annoying things I've encountered.
First of all I'd like to say that this DID work fine, I have limited examples of what the cause is but I'll list them anyway.
Here's the full error message:
Fatal error: Call to undefind function mysqli_connect() in C:\wamp\www\game\connect.php on line 3
And here's the code
<?php
// Create connection
$con=mysqli_connect("localhost","root","","game");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$select_db = mysqli_select_db($con, 'game');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
?>
Weird thing is, it was working completely fine and just suddenly stopped, this has happened more than once.
Here's what I've tried:
Checking the extensions are enabled -
Rebooting various times -
Setting the correct php path -
Using many example codes that "work" -
I also had some code that inputted data straight from phpdesigner into the database, which successfully worked, but that no longer works and I've made literally 0 changes.
The last time it stopped working, I filled out a registration form on my site as a test (that doesn't work either) and it suddenly went off. When filling in the form I click register and nothing happens besides a refresh.
Bit extra: In my httpd file the pfp and pfpinidir are as follows
php5_module"c:/wamp/bin/php/php5.5.12/php5apache2_4.dll"
PHPIniDir "C:\wamp\bin\apache\apache2.4.9\bin\php.ini"
Your mysqli extension might not be enabled. so u need to enable that.
You have two PHP binaries on your machine. One is connected to the Apache, and is the one u use when you surf to a web page.
The phpinfo() shows you which php.ini file is used by the web php binary. u need to edit this file and in it activate the mysqli extension
You're trying to connect to DB twice, plus you're mixing MySQL APIs with mysql_error(), they do not mix together.
The 4th parameter is the DB name which is what you've done in the first example.
Use either:
<?php
// Create connection
$con=mysqli_connect("localhost","root","","game");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
or omit ,"game" from mysqli_connect() - while mysqli_error() requires DB connection parameter.
<?php
// Create connection
$con=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$select_db = mysqli_select_db($con, 'game');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($con));
}
?>

Mysql fails in php but works in phpmyadmin

I've made this a lot of times but now I can't :(
The insert allways return false but if I execute the same SQL script (taked from the output) it inserts in the database without any problem. I'm connected to the database because some values are fetched from another table.
This is my code:
$query = "INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx,equipo_compania,paciente,sexo,edad,id_compania,otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('$fecha','$macropera','$pozo','$equipo_pmx','$equipo_compania','$paciente','$sexo',$edad,$id_compania,'$otra_compania','$puesto','$ta','$tum','$ove','$coordinador')";
if (mysql_query($query,$connection)){
//OK
} else {
$errno = mysql_errno();
$error = mysql_error();
mysql_close($connection);
die("<br />$errno - $error<br /><br />$query");
exit;
}
The output is:
0 -
INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx, equipo_compania,paciente,sexo,edad,id_compania, otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('20111001','P. ALEMAN 1739','P. ALEMAN 1715','726', 'WDI 838','SERGIO AYALA','M',33,21, '','','110/70','ROBERTO ELIEL CAMARILLO','VICTOR HUGO RAMIREZ','LIC. PABLO GARCES')
Looks like there are no error, but allways execute the code in the else part of the if instruction. Any idea? Thanks in advance.
I think the issue might be you are missing the mysql_select_db line after the connection.
After the connection with the database is established you need to select a DB. Please make sure you have selected the Database that your desired table resides in.
And you can even use the following snippets to get some useful informated through mysql_errors.
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection) {
die('<br>Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name')) {
die('Could not select database: ' . mysql_error());
}
And try you insert query after these lines of code. All the best.
I agree with the others concerning the column types. INT is one of the only data types that do not require single quotes.
There are two blank strings. There is a possibility that the variables are not defined, and therefore giving you a PHP exception (not even in the MySql yet) but that requires stricter-than-normal exception settings. I would personally look into the $connection variable. Before the SQL query statement, put this and send us the cleaned results:
echo '<pre>'.var_dump($connection, true).'</pre>';
Additionally, on your mysql_connect function call, put
OR die('No connection')
afterwords. Do the same thing with the mysql_select_db function, changing it to 'No DB Select' obviously.
Ultimately, we will need more information. But changing to mysqli is very desirable.
Oh! And make sure the permissions for the user you are connecting as are not changed. Sometimes I find people who connect to PhpMyAdmin using one user account but a different account in their PHP code. This is problematic, and will lead to problems eventually, as you forget the different accounts, at times.

Categories