Why does mysql_connect() return NULL? - php

I'm running my program on PHP 5.5.24,when I simply use :
$dblink = mysql_connect($dbhost, $dbuser, $dbpass);
But the function return NULL, I try to use mysql_error() to find out what's wrong, but it also returns an empty string. I know mysql_* is deprecated after 5.5.0, but I'm dealing with a very old repository. It will cost a lot of time to change into mysqli. The function suppose to refurn false if the connection failed, no NULL. Why does it happen?
-----Update-----
Now I find that $dblink can not shown by var_dump(), var_dump($dblink) would get NULL but it's actually not null.

seems it can return null, search the source for cases when it can happen

I got the answer.
To show the result of mysql_connect(), pls use var_dump() instead of var_export(). I use var_export() and get NULL as return, but var_dump() shows the result is not null. That's strange.

mysql_connect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, bool $new_link = FALSE [, int $client_flags = 0 ]]]]] )
Returns a MySQL link identifier on success or FALSE on failure.
I think U have to try:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
To see what happened.
I hope it is usefull.

Related

mysql_connect CHANGE TO mysqli [duplicate]

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 3 months ago.
I have some existing PHP code that is now throwing a fatal error since we migrated to PHP 7.0. Using this Stackoverflow Question I've altered this line:
$link = mysql_connect($host.':'.$port, $user, $pass) or die("Can not connect." . mysql_error());
to this:
$link = new mysqli($host.':'.$port, $user, $pass);
I am now throwing this error which I guess is some progress. The syntax seems fine? What am I missing?
Warning: mysqli::__construct(): (HY000/2002): Connection timed out
The constructor class looks like this:
__construct (
[ string $host = ini_get("mysqli.default_host")
[, string $username = ini_get("mysqli.default_user")
[, string $passwd = ini_get("mysqli.default_pw")
[, string $dbname = ""
[, int $port = ini_get("mysqli.default_port")
[, string $socket = ini_get("mysqli.default_socket") ]]]]]] )
So the order is host, username, password, database, port, socket. You'll need to pass in the port in a separate variable:
$link = new mysqli($host, $user, $pass, null, $port);
Edited because I copied the wrong bit of code..
Try just using the function.
$link = mysqli_connect($host,$user,$pass,$db).
The order is host, user, pass, db
http://php.net/manual/en/function.mysqli-connect.php

mysqli_affected_rows creates new connection (read details)

I am learning to use mysqli instead of mysql and facing some problems.
This is my code.
require("classes/dbo.class.php");
$db->dml('update table set name="abc" where a_id=5);
echo "Rows Affected : ".mysqli_affected_rows($db->link());
Here's dbo.class.php
class dbo
{
private $db = "dbname";
private $user = "root";
private $pass = "";
private $host = "localhost";
function link()
{
$link = mysqli_connect($this->host, $this->user, $this->pass) or die(mysqli_error($link));
return $link;
}
function dml($q)
{
$link = mysqli_connect($this->host, $this->user, $this->pass) or die(mysqli_error($link));
mysqli_select_db($link,$this->db) or die(mysqli_error($link));
mysqli_query($link, $q) or die(mysqli_error($link));
}
}
$db = new dbo();
Now the problem is I don't understand how to pass database link ($link) in mysqli_affected_rows() function. I tried above, but it seems to create a new database connection, so mysqli_affected_rows returns 0 instead of 1.
I thought of creating a new method dmlWithMysqliAffectedRow() in dbo.class.php that returns affected rows instead of true and false.
My solution looks stupid to me. Which is the better way to do this?
First you have an error in this code, you have not closed the string for your query. Its also better to use a double quoted string and single quotes around you SQL data parameters.
require("classes/dbo.class.php");
//$db->dml('update table set name="abc" where a_id=5);
$db->dml("update table set name='abc' where a_id=5");
echo "Rows Affected : ".mysqli_affected_rows($db->link());
Second mysqli_ has a perfectly good OO implementation, use that rather than trying to re-invent the wheel, and getting a square one.
Documentation: for this can be found here, in many languages

cannot get a connection to MySQL in php

I have this simple code:
<?php
//Open the mySQL connection
$conn_string = "'localhost', 'Vale', 'test'";
$dbh = mysql_connect($conn_string);
//Check that a connection with the DB has been established
if (!$dbh)
{
die("Error in MySQL connection: " . mysql_error());
}
...
And I get the error: Error in MySQL connection: php_network_getaddresses: getaddrinfo failed: The requested name is valid, but no data of the requested type was found.
I cannot figure out what the problem is, I have been google-ing but all the suggestions have failed (tried 127.0.0.1 instead of localhost, 127.0.0.1:3306, etc.)
I have code that works with postgre, but I need to use mysql, and I am trying to modify it, but I cannot pass the first line and get a connection. Any suggestion, please? Thank you!
mysql_connect doesn't take a comma seperated string. It takes 3 individual strings.
Change it to this:
$dbh = mysql_connect($server, $mysql_user, $password);
If you absolutely have a comma separated string, and can't get around this, you can split the string like this:
$config = str_replace("'", '', $conn_string); // replace the quotes.
$config = preg_split('/,/', $conn_string); // split string on ,
if($config != $conn_string) { // make sure this returned an array
count($config) === 3 OR die("Invalid database configuration string");
$dbh = mysql_connect($config[0], $config[1], $config[2]);
if(FALSE === $dbh) {
die("Coult not connect: " . mysql_error());
}
}
You might want to consider MySQLi, instead of MySQL.
<?php
$dbh=mysqli_connect("localhost","Vale","Password","test"); /* Vale is your username? And the name of your database if test, right? And your Username's Password is blank? */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
As other users have pointed out mysql_connect expects the database, username, and password as separate arguments rather than a single string.
I think another highly important issue to point out is that this particular extension is deprecated.
Please see: http://uk1.php.net/function.mysql-connect
A better solution would be to use mysqli_connect: http://uk1.php.net/manual/en/function.mysqli-connect.php
$db = mysqli_connect( 'localhost', 'Vale', 'test', 'yourDatabaseName' );
mysql_connect requires three argument not single string
$dbh = mysql_connect('localhost', 'Vale', 'test');

multiple mysql connections on one page php

I am getting errors (not really errors, just not working properly) and I'm trying to figure out if it's related to my sql connections. I have 2 separate connections to two entirely different databases.
$dshost = "kjbkb";
$dsdatabase = "kjhk";
$dsusername = "hjgfytdf";
$dspassword = "jhv";
mysql_connect($dshost,$dsusername,$dspassword);
mysql_select_db($dsdatabase) or die( "Unable to select database");
$sql = "SELECT * FROM users WHERE `username` = '".$_POST['paydl']."'";
$cheeseburger = mysql_query($sql);
$res = mysql_fetch_array($cheeseburger);
$autobus_user = $res['id'];
mysql_close(); //close first connection
$db_host = "khgv";
$db_user = "trdstx";
$db_password = "txz";
$db_database = "gfxx";
mysql_connect($db_host, $db_user, $db_password) or die("Unable to connect to host");
mysql_select_db($db_database) or die( "Unable to select database");
$ASDFASDF = "SELECT * FROM `autobus` WHERE `user_id` = '".$autobus_user."' LIMIT 3";
$BobDoleDontNeedThis = mysql_query($ASDFASDF);
$resnumbatwo = mysql_fetch_array($BobDoleDontNeedThis);
mysql_close(); //close 2nd connection
Am I doing this right? Why is $resnumbatwo returning false?
When using multiple MySQL connections in PHP, you have to supply a fourth argument telling PHP to actually create new connections like this (this is very important, if you are using two connections to the same host):
$db1 = mysql_connect($host1, $user1, $passwd1, true);
$db2 = mysql_connect($host2, $user2, $passwd2, true);
If the fourth argument is not used, and the parameters are the same, then PHP will return the same link and no new connection will be made.
After this you should use "mysql_query" with an extra parameter than defines which connection to use:
$res1 = mysql_query($sql1, $db1) or die(mysql_error($res1));
$res2 = mysql_query($sql2, $db2) or die(mysql_error($res2));
The description of the fourth parameter from php.net is:
"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. In SQL safe mode, this parameter is ignored."
See more at:
http://www.php.net/manual/en/function.mysql-connect.php
mysql_fetch_array will return false if there are no matching records returned from the query. Please see the following entry from the API reference docs:
Return Values:
Returns an array of strings that corresponds to the fetched row, or
FALSE if there are no more rows. The type of returned array
depends on how result_type is defined. By using MYSQL_BOTH
(default), you'll get an array with both associative and number
indices. Using MYSQL_ASSOC, you only get associative indices (as
mysql_fetch_assoc() works), using MYSQL_NUM, you only get number
indices (as mysql_fetch_row() works).
Better save each connection handler in a variable and transmit it to correspondent mysql_query().
Example:
$dbch1 = mysql_connect($dshost, $dsusername, $dspassword);
$dbch2 = mysql_connect($db_host, $db_user, $db_password);
$cheeseburger = mysql_query($sql, $dbch1);
$BobDoleDontNeedThis = mysql_query($ASDFASDF, $dbch2);
You can use
$dbch1 = mysql_connect($dshost, $dsusername, $dspassword,true);
$dbch2 = mysql_connect($db_host, $db_user, $db_password,true);
$cheeseburger = mysql_query($sql, $dbch1);
$BobDoleDontNeedThis = mysql_query($ASDFASDF, $dbch2);
Using php7
you can use the mysqli_change_user() function.
Like in the examples at the php.net page: http://php.net/manual/en/mysqli.change-user.php

mysql_real_escape_string() just makes an empty string?

I am using a jQuery AJAX request to a page called like.php that connects to my database and inserts a row. This is the like.php code:
<?php
// Some config stuff
define(DB_HOST, 'localhost');
define(DB_USER, 'root');
define(DB_PASS, '');
define(DB_NAME, 'quicklike');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('ERROR: ' . mysql_error());
$sel = mysql_select_db(DB_NAME, $link) or die('ERROR: ' . mysql_error());
$likeMsg = mysql_real_escape_string(trim($_POST['likeMsg']));
$timeStamp = time();
if(empty($likeMsg))
die('ERROR: Message is empty');
$sql = "INSERT INTO `likes` (like_message, timestamp)
VALUES ('$likeMsg', $timeStamp)";
$result = mysql_query($sql, $link) or die('ERROR: ' . mysql_error());
echo mysql_insert_id();
mysql_close($link);
?>
The problematic line is $likeMsg = mysql_real_escape_string(trim($_POST['likeMsg']));. It seems to just return an empty string, and in my database under the like_message column all I see is blank entries. If I remove mysql_real_escape_string() though, it works fine.
Here's my jQuery code if it helps.
$('#like').bind('keydown', function(e) {
if(e.keyCode == 13) {
var likeMessage = $('#changer p').html();
if(likeMessage) {
$.ajax({
cache: false,
url: 'like.php',
type: 'POST',
data: { likeMsg: likeMessage },
success: function(data) {
$('#like').unbind();
writeLikeButton(data);
}
});
} else {
$('#button_container').html('');
}
}
});
All this jQuery code works fine, I've tested it myself independently.
Any help is greatly appreciated, thanks.
Are you 1000% sure that $_POST["likeMsg"] actually contains something?
As for mysql_real_escape_string() returning an empty value, the manual says there is only one situation where that can happen:
Note: A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.
this doesn't seem to be the case here though, as you do have a connection open. Strange.
As the other answers don't make clear what exactly to do, here's my:
When you do
$db_connection = new mysqli($SERVER, $USERNAME, $PASSWORD, $DATABASE);
you need to escape like this:
$newEscapedString = $db_connection->real_escape_string($unescapedString);
NOTE: Because people are downvoting this (WTF!?), here's the official page of the official php manual that says EXACTLY what i have posted: real_escape_string # PHP Manual.
For people who might be finding this again now, I just ran into this problem as I'm migrating from PHP5 to PHP7. I'm changing from
string mysql_real_escape_string(string $unescaped, [resource $link = NULL])
to:
string mysqli_real_escape_string(mysqli $link, string $escapestr)
So, in other words, the database $link is no longer optional and moves to the first argument position. If left out, it returns an empty string, without an error, apparently.
Do a var_dump of $_POST['likeMsg'], and a var_dump of $likeMsg. That gives you information on what goes wrong.
mysql_real_escape_string() will return blank response if you have not made connection to database ...

Categories