I have a routine that I call to do a mssql and mysql server connect like so:
$mysql_aoi_conn = DoMySQLConnect( 'AOI' );
$mssql_aoi_conn = DoMsSQLConnect( 'itf' );
the functions are as follows:
function DoMySQLConnect( $pdb_name ){
$mysql_conn = mysql_connect('localhost', '####', '####') or die( 'could not connect to localhost server : ' . mysql_error() );
$mysqldb_conn = mysql_select_db( $pdb_name, $mysql_conn ) or die('could not use database ' . $pdb_name . ' : ' . mysql_error() );
return array("database" => $mysqldb_conn, "connection" => $mysql_conn );
};
function DoMsSQLConnect( $pdb_name ){
$mssql_conn = mssql_connect("128.251.xxx.xxx", '###', '###') or die("failed to connect to server USLONSAPP003");
$mssqldb_conn = mssql_select_db( $pdb_name, $mssql_conn) or die("failed to select database " . $pdb_name);
return array("database" => $mssqldb_conn, "connection" => $mssql_conn );
};
I'm trying to use the connection implementation within the mssql_query and mysql_query to tell my queries which connection to use but I'm getting an error. Here is one of my queries:
$login_res = mssql_query("SELECT *
FROM ITF_USER
WHERE ITF_LOGIN = '" . $lcUserName . "'", $mssql_aoi_conn['connection'] )
or die("failed to query ITF_USER: \n" . mssql_get_last_message() );
This dies with the mssql_get_last_message() of:
Changed database context to 'itf'. which is not really an error. Can someone tell me if I'm utilizing this query option wrong?
After some research it seems that mssql_query() doesn't support the link_identifier option and therefore breaks (albeit without a valid error for debugging). Removing the link identifier for the mssql_query and keeping it throughout my document for any mysql_query() lets me use both mssql_query() and mysql_query() commands throughout my script.
Even though you have solved your problem, I was facing a similar error "changed database context" when using the mssql_exec() function in PHP. It seems to be fixed by setting:
sqlsrv_configure ( "WarningsReturnAsErrors" , 0 ); //OFF
sqlsrv_configure ( "LogSeverity" , 1 ); //SQLSRV_LOG_SEVERITY_ERROR
Before that, I was using [DATABASE].[dbo].[TABLE] to prevent getting lots of reports about such error/warning.
Related
I'm running this code on GoDaddy webhosting and I'm getting 'The database could not be found' echoed.
Obviously the database in question can't be selected, even though I've privileged the user and checked the db name.
I don't get anything out of here mysqli_error()
$db= 'test2' ;
$con = mysqli_connect('whatever','whatever','whatever') or die ('The connection to the database could not be established.');
mysqli_select_db($db , $con) or die ('The database could not be found' . mysqli_error());
As per the mysqli_select_db documentation, it expects the parameters this way:
mysqli_select_db ( mysqli $link , string $dbname ) : bool
So your parameters are put in backwards, change it to this:
mysqli_select_db($con, $db) ...
Or, alternatively, just select the database inside mysqli_connect().
$con = mysqli_connect('whatever','whatever','whatever', $db) ...
Side note, your die() isn't really doing anything, you won't get an actual error code out of that. To use mysqli_error(), you need to pass your database handle:
die('There was an error: ' . mysqli_error($con));
For the die() that is attached to mysqli_connect(), you should do this:
die('There was an error: ' . mysqli_connect_error());
I already have my database named als and I still got the error.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con = #mysql_connect($mysql_host,$mysql_user,$mysql_password) or die(mysql_error());
#mysql_select_db($mysql_db) or die(mysql_error());
?>
Not exactly an answer to your question but too long for a comment:
After establishing the database connection you could just query the existing databases via SHOW DATABASES
<?php
$mysqli = new mysqli('localhost', 'root', '');
if ($mysqli->connect_errno) {
trigger_error('query failed: '.$mysqli->connect_error, E_USER_ERROR);
}
$result = $mysqli->query('SHOW databases')
or trigger_error('connect failed: '.join(',', $mysqli->error_list), E_USER_ERROR);
foreach( $result as $row ) {
echo join(', ', $row), "<br />\r\n";
}
Does your database als show up?
Since you're using the default root account (with an empty password; you might want to look into that as well) there shouldn't be any permission related problems. So, if the database doesn't show up, it's just not there...
(almost) same script using PDO (my weapon of choice) instead of mysqli:
<?php
$pdo = new PDO('mysql:host=localhost;charset=utf8', 'root', '', array(
PDO::MYSQL_ATTR_DIRECT_QUERY => false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
foreach( $pdo->query('SHOW DATABASES', PDO::FETCH_NUM) as $row ) {
echo $row[0], "<br />\r\n";
}
There you go. The mysql_ family has been deprecated for some time. Please change to the mysqli_ library. Another machine may work because it's using an older version of PHP in which it hasn't been deprecated OR where deprecated warnings have been globally supressed.
MySQLI Connect
In the wild
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con= mysqli_connect($mysql_host,$mysql_user,$mysql_password, $mysql_db) or die("Error " . mysqli_error($con));
There's no need to arbitrarily select the database anymore. Now you can use $con as an argument to the mysqli_ family of procedural functions.
Last, but not least, never debug with the # symbol. This suppresses the error warnings from the function it precedes.
Here is the code:
<?php
$con=mysql_connect('localhost', 'itorras', 'passwordhere');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db( "my_db" ) or die( 'Error'. mysql_error() );
$sql="INSERT INTO Brackets(have things here)
VALUES(and here)";
if (!mysqli_query($con,$sql))
{
die('Error with adding row: ' . mysqli_error($con));
}
echo "Thank you, your bracket has been submited.";
echo "<a href='index.html'>Click here to go back to home page</a>";
?>
I am using the username and password that is given the rights to mess with the database.
So when i try to submit something into the file none of the top errors run but then the bottom error prints error with adding row and nothing more. This file worked fine on my local server but has not worked on the web host. I am using godaddyweb hosting, so phpmyadmin and cpanelx.
If you need any more info let me know. Have been at this for a couple hours.
You are using mysql_connect but mysqli_query. You are mixing mysql and mysqli. Use only mysqli_*.
It appears you are using two different libraires at the same time
The original mysql API is deprecated for various reasons and you should not use it in new code
Instead, use PDO or mysqli
In your code, you are using the original mysql for the db connect, and then you use mysqli for the query. Instead you should only use mysqli
Replace the following code :
$con=mysql_connect('localhost', 'itorras', 'passwordhere');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
With :
$db = new mysqli('localhost', 'user', 'pass', 'demo');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
Then you can query the database with something similar :
$sql = <<<SQL
SELECT *
FROM `users`
WHERE `live` = 1
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
For a complete overview, you can take a look at the documentation
http://ca2.php.net/mysqli
Is there any way to turn on driver logging for PHP/MySQL 5? Is there a log that shows internally what's going on... like all database activity? Lower-level errors?
I'm trying to get a trivial PHP page to call a trivial stored proc on Windows 7. mysql_error isn't returning any error message when the mssql_init() fails.
Thinking it might be a permission problem I created a new user and I get the same results:
CREATE USER 'user1'#'localhost' IDENTIFIED BY 'pass1';
GRANT ALL ON *.* TO 'user1'#'localhost';
Here is the code:
create table trace (
trace varchar(50) not null,
datet datetime not null
);
drop procedure if exists mark;
delimiter !!
create procedure mark()
begin
insert into trace (trace,datet) values ('mark',now());
end; !!
delimiter ;
I can call the SP from MySQL Workbench just fine:
call mark();
Here is the PHP page:
<?php
$connection = mysql_connect('localhost', 'user1', 'pass1');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
$sel = mysql_select_db('tw');
if (!$sel) {
die('Could not select_db: ' . mysql_error());
}
//$stmt = mssql_init('mark', $connection);
//$stmt = mssql_init('mark', $sel);
$stmt = mssql_init('mark');
if (!$stmt) {
die('Could not init: ' . mysql_error());
}
$result = mssql_execute($stmt);
if (!$result) {
die('Could not execute: ' . mysql_error());
}
mysql_free_result($result);
mssql_free_statement($stmt);
mysql_close($connection);
printf("DONE<br />");
?>
Other proof of concept pages which demonstrate insert, *select,* etc, are working just fine. Just can't get a stupid stored procedure to run from a web page!
The page output is only this:
Could not init:
(The PHP mssql_init documentation page isn't very helpful and seems to have a typo as the $link variable isn't defined.)
You're using mssql_init (Note MS SQL) to execute a stored procedure on My SQL.
Obviously the mssql_init() function can't find your Microsoft SQL Server connection 'cause you don't have one. You should only be using mysql_ functions for a MySQL connection.
And MySQL doesn't have a special function for calling stored procedures. mysql_query('CALL mark()') will work just fine.
Why do I get a "mysql_query(): supplied argument is not a valid" for the first...
$r = mysql_query($q, $connection);
In the following code...
$bId = trim($_POST['bId']);
$title = trim($_POST['title']);
$story = trim($_POST['story']);
$q = "SELECT * ";
$q .= "FROM " . DB_NAME . ".`blog` ";
$q .= "WHERE `blog`.`id` = {$bId}";
$r = mysql_query($q, $connection);
//confirm_query($r);
if (mysql_num_rows($r) == 1) {
$q = "UPDATE " . DB_NAME . ".`blog` SET
`title` = '{$title}',
`story` = '{$story}'
WHERE `id` = {$bId}";
$r = mysql_query($q, $connection);
if (mysql_affected_rows() == 1) {
//Successful
$data['success'] = true;
$date['errors'] = false;
$date['message'] = "You are the Greatest!";
} else {
//Fail
$data['success'] = false;
$data['error'] = true;
$date['message'] = "You can't do it fool!";
}
}
I also get an "mysql_num_rows(): supplied argument is not a valid MySQL result resource" error too.
Side notes: I am using 1&1 Hosting (worst hosting ever), custom .htaccess file with one line text to enable PHP 5.2 (only way with 1&1 Hosting).
Extra stuff add after the questions was posted...
Here is how $connection is defined. It is on its own page called connection.php that is called up using the require_once function. It it is called up on every page that require a database connection including the one in question...
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database Connection Failed: </br>" . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database Selection Failed: </br>" . mysql_error());
}
... I know it is working because this the same connect that I use for the page I have and I have no problems with it. I havent testing on my home server yet, but I am going to later to see if it is related to a 1&1 Hosting issue.
UPDATE: I am in the process of moving from 1&1 Hosting to HostMoster. 1&1 runs a PHP as CGI and runs PHP4 instead of PHP5 (you can make a custom .htaccess file to make it run PHP5). I will update you later.
The first would be because it's not a connection, and the second would be because it's not a query result because it wasn't a connection. Use mysql_error() to figure out what went wrong in the connection.
My guess is that $connection has not been properly opened. You should have a line like:
$connection = mysql_error($server, $user, $pass);
Also check mysql_error() to see the reason why it's failing.
I think that cletus meant to suggest that you need to have a mysql_connect() instead of mysql_error() before you attempt to perform a mysql_query(). It will probably look like this (with the exception that 1and1 may have given you a specific hostname to connect to for your database which you should use in place of localhost below):
//Make sure this goes before any of your other mysql_* functions
$connection = mysql_connect('localhost', 'yourUserName', 'yourPassword');
Passing $connection around for each of your queries isn't really necessary unless you have multiple database connections open concurrently that you are using and need to make sure to differentiate between the two when making query calls. Otherwise, mysql_query assumes that you are using the last database that you connected to.
Also, for security purposes as mentioned by Frank you should use mysql_real_escape_string() like so:
$q = "SELECT * ";
$q .= "FROM " . DB_NAME . ".`blog` ";
$q .= "WHERE `blog`.`id` = ".mysql_real_escape_string($bId).";
Tested on my local system (via WAMP), I had no problems. At the time when I had problems, I was using 1&1 Hosting. 1&1 Hosting run PHP as CGI, which probably cause my problems. I couldnt handle allof the crap with 1&1 and switch to HostMonster. Now, I don't any issues. Plus, I rather use cPanel over 1&1's admin panel.