Message not getting printed on the browser in php? - php

Here is my code in php:
<?php echo "hello world";
$con = mysql_connect("localhost","root","root123");
echo "Connected";
mysql_close($con);
echo "hell"; ?>
Its printing hello world ,connected ,hell in terminal but it only prints hello world when i run it in the browser. Can anyone tell me why is this happening?
Thanks.

May be there has occurred an error in server side and server is not showing informatin about error. You look at error.log.

Please dont use mysql_*, use mysqli_* instead.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "collectively-codeigniter";
echo "hello world";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "Not Connected";
} else {
echo "Connected";
}
// Close connection
$conn->close();
echo "hell";
?>

I do not see syntax errors and since you said that echo() functions before the connection line work, I guess the problem could be the connection:
Replace mysql_connect with mysqli_connect and mysql_close with mysqli_close because mysql_* is now deprecated.
Add the following code after the connection line:
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
This will check if the connection succeeded and if it failed it will print the error description.
Other things that could cause the problem are:
You do not have MySQL modules installed
MySQL service is not running (to check windows services: run -> services.msc)
Let me know if this helped you :)

You are obviously running into an error server side before the output has a chance to take place. Possibly it's when you try and connect to the mysql server that everything goes south. That results in an error that you have configured PHP not to show (very good for production, not so good when developing), thus you see "nothing".
Start by enabling error reporting in PHP via the php config file or setting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
at the top of your script. That should give you a clearer picture of what you issue actually is. A guess would be that you are unable to connect to the mysql server due to privileges on the mysql server, the port used, credentials or something of that nature.
Also, as stated, depending on the version of PHP you are running mysql_* command are deprecated and you should instead use the mysqli_* functions, PDO or something like that.

Related

PHP Oracle connection

I am attempting to write some connection code with PHP to a Oracle database my school is hosting.
I'm using oci_connect() at the moment to make this connection, but it is failing.
$conn = oci_connect('username', 'password', 'hostname/SID');
I can access the oracle database through sqlDeveloper, as well as phpmyadmin, so I know the login information is correct.
I checked the oracle version with select * from v$version;, it shows as 12c Enterprise.
What is wrong with my php code for connecting? Is there a better way to make an oracle connection through PHP?
This is the test code I'm running, from http://php.net/manual/en/function.oci-error.php
<?php
echo "running";
$conn = oci_connect("username", "paswwrod", "address/SID");
if (!$conn) {
$e = oci_error(); // For oci_connect errors do not pass a handle
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
echo "ending";
?>
The string "running" gets echoed, but "ending" does not, the script just stops working when it attempts oci_connect()
have you also tried including the port number to the oracle db server like so?
$conn = oci_connect("user", "pass", "localhost:1234/xe");

Cant get php to connect to sql. Get error Connection failed: php_network_getaddresses: getaddrinfo failed: No such host is known.

I have scoured google, and stackover flow, and just cant get to the bottom of this issue. I cannot get the following php code to connect to SQL. Its a simple php web document, that i am using to test out some things. SQL is sqlexpress 2016, and its running on IIS with php 7.x installed. PHP code executes fine, so its something with the code or the database is my guess. Things I've tried:
I've ran an echo in php to resolve the name, and it resolves it fine.
I've connected from a separate server to the sql server using tcp, and it connects fine.
I've tried both PDO connection, and mysqli and both come back with same error.
The PDO code ive used is:
<?php
$servername = 'RemoteServerName\SqlInstance';
$username = 'iislogon';
$password = 'password';
try {
$conn = new PDO("mysql:host=$servername;dbname=netdata", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
The mysqli code is:
<?php
$servername = 'RemoteServerName\SqlInstance';
$username = 'iislogin';
$password = 'password';
$dbname = 'netdata';
?>
<?php $conn = new mysqli($servername, $username, $password, $dbname); ?>
<?php
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";?>
Both return the same error of host not found. What other issues could be causing this? Im new to coding php so any help would be appreciated.
mysqli and PDO starting with mysql: are supposed to connect to MySQL, not SQLExpress.
If you want to use SQLExpress you should use something like sqlsrv_connect or adjust your pdo string to a SQLExpress compatible one.
Take a look at this thread too.
Look at this description http://php.net/manual/en/pdo.construct.php and specifically:
In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.
Are you sure your dsn is correct and you have the PHP module enabled? See http://php.net/manual/en/ref.pdo-mysql.php
I think you didn't escape your backslash with another backslash. Try this:
<?php
$servername = 'RemoteServerName\\SqlInstance';
?>

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.

Remote connection to MySQL works via command line, but fails when using php's mysql_connect from a web browser

I am trying to connect to a MySQL server using PHP's 'mysql_connect()' function, but the connection fails. This is my code:
$con = mysql_connect("example.net", "myusername","") or die("Could not connect: ".mysql_error());
I placed this code inside a PHP script, which I try to open using a web browser (the script is stored on a remote host which has PHP enabled) but it doesn't work. It doesn't return the die error either. Echoing something before the $con successfully outputs in the browser, whereas nothing outputs after that line. If I type:
mysql -h example.net -u myusername
from a remote machine, I could connect to the DB without any problem and do queries and other modifications.
Update :
I also tried this after some suggestion, but no improvement:
<?php
$usern = "myusername";
$dbh = new PDO('mysql:host=servername.net;dbname=test', $usern, "");
echo $usern;
?>
What operating system is the remote host running PHP using? Perhaps MySQL isn't enabled in php.ini. Also, please don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process (see the red box). Instead, you should learn about prepared statements and use either PDO or MySQLi. If you can't decide which, this article will help you. If you care to learn, this is a good PDO tutorial.
Have you tried using PDO or the MySQLi interface? If you're trying to learn PHP, you should not be using the mysql_* functions regardless. See if you can access the database by using a line similar to this:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
If you need more detailed documentation, this code comes directly from the documentation itself.
EDIT: Also, try using PDO's error checking functionality. This example creates a database connection using PDO and tries to perform a simple query. It doesn't use prepared statements or any of those features, so it's not production-ready code (i.e. *don't just throw this into your code without understanding how to improve it) and you'll need to edit it to include a SELECT query that's relevant to your database, but it should at least tell PDO to provide more information about the errors it encounters.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM booksa";
$q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorInfo()));
$r = $q->fetch(PDO::FETCH_ASSOC);
print_r($r);
?>
Is the php file located on the same server as the mysql database, if so you might have to use 'localhost' as the first argument for mysql_connect() instead the external address.

Access denied for user 'www-data'#'localhost - how to deal with that?

I face with a strange problem yesterday. I have server running Debian with installed PHP 4.4.4-8 and mysql 5.5.9. That server serves a several websites.
For some reason randomly I get that error "Access denied for user 'www-data'#'localhost' (using password: NO)" when I try to load the webpage.
If I hit refresh the page loads normally, but afer several clicks that message appears again. Username which that page use to connect to mysql server is not www-data.
Does anyone has faced similar problem ?
www-data is the Debian user that runs apache and php. If you attempt a query when you don't have a valid connection, php/mysql will attempt to create a connection using <unix-user>#localhost with no password. This is where www-data#localhost (using password:NO) is coming from.
The most likely reason that this has started happening now (though it has been running fine for 2-years prior) is that your db load has increased to the point where some connections are unable to succeed (probably due to max_connections, or max_user_connections; though this can also result from other limits like memory, threads, etc). When this happens, your call to mysql_connect will emit an error message, and return FALSE. If you fail to detect this failure, then your next mysql call (probably mysql_query, or mysql_select_db) will attempt the connection to www-data#localhost -- thus causing the problem you're seeing.
I suggest enabling error reporting, and error display (as suggested by #DarkMantis) :
ini_set('error_reporting', E_ALL|E_STRICT);
ini_set('display_errors', 1);
Also, be sure that your call to mysql_connect is not preceded by a # sign; and make sure to check the return value. It should look something like this:
$cxn = mysql_connect('localhost','yourusername','yourpassword');
if( $cxn === FALSE ) { die('mysql connection error: '.mysql_error()); }
It sounds like the query that is causing the error happens when something specific is called. This could mean that when the query is called, you aren't connected to the database with the correct username/password.
Try to ensure that you are definatly connected, use or die(mysql_error()); at the end of all your query variables to debug them.
Also, use the following two lines at the top of your php file:
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
That will show you any little php errors that may occur within your class/file which you may not have picked up before.
If your still having a problem after this, please post your PHP code and I will take a look at it directly.
Thanks!
i faced the same problem.
The problem was in my config.php!
I simply changed the $dbserver from
"127.0.0.1" -> "localhost".
Now the connection works again!
For absent-minded people, this error may happen when mysql_query() is called after mysqli_connect(), when it should be mysqli_query().
Use password 'NO'
(MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Deactivating safe mode fixed it for me:
Notice: mysql_connect(): SQL safe mode in effect - ignoring host/user/password information in /var/www/html/test.php on line 4
For solve this problem. I had to change the connection script Using
(MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Categories