Connecting to a specific database using php (xampp / mysql) - php

I want to run a script that successfully connects to a database. I have xampp, both programs running, I have created a database within phpMyAdmin named "testing" with a user login "root" and password "root" (just for this).
The PHP code:
mysql_connect("localhost", "root", "root") or die("<p>failed: " . mysql_error() . "</p>");
I have no idea what is supposed to go into where "localhost" is and can't find an answer. I've tried several different options. Including pointing directly to the damn thing "localhost/xampp/mysql/data/testing".

The first parameter to mysql_connect is the host for your MySQL server. Since you are developing locally, localhost or 127.0.0.1 is probably what you want, unless you want to connect to a remove MySQL server. Both of these addresses will loopback to your own computer, where you should be running your MySQL service.
Also, you may want to consider using MySQLi or PDO. mysql_connect and the related functions are deprecated in PHP 5.5.

localhost is your own machine. If you're using Xampp you most likely won't need to change it.
Besides from opening a connection to the db host, you still need to select a database name (the one you created with phpmyadmin)
mysql_select_db('testing');
Since you're just starting I don't want to annoy you with the rant about the old mysql_ functions to be deprecated. But once you get the basics, try to switch to PDO mysql, the learning curve is the same and you'll avoid wasting your time.

Note that the MySQL extension has been deprecated since PHP 5.5 in favor of PDO MySQL or MySQL Improved.
Using for example MySQLi, in your case the connection statetement should read:
$mysqli = new mysqli("localhost", "root", "root", "testing");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
More information here.

Related

What is my host name for MySQL?

This sounds like a stupid question, but I'm beginning in PHP and MySQL and failing at the first step, trying to connect to the database:
<html>
<head>
</head>
<body>
<?php
$con = mysqli_connect("localhost", "root", "root", "ASOIAF.odb");
if (mysqli_connect_errno()) {
echo "Failed to connect to database";
} else {
echo "Connected to database";
}
mysqli_close($con);
?>
</body>
</html>
I don't understand the first host parameter. A yahoo help page said that the host should be "mysql", but when I used this it failed to connect as well. The database, ASOIAF, is in OpenDocument database format (odb), on LibreOffice Base. I'm using Uniserver to run PHP and MySQL; both are currently running. The web application is stored in Uniserver's www folder, and run on Google Chrome through localhost.
What should I be inserting in the host portion of the connect statement? Or have I made a more basic syntax error in the PHP code that is preventing a connection from being made?
What is my host name for MySQL?
We don't know what you have called the computer you are running MySQL on.
A yahoo help page said that the host should be "mysql"
That is specific to Yahoo Web Hosting. It doesn't sound like you are using their service, so that is inapplicable.
I'm using Uniserver to run PHP and MySQL
That suggests the computer running the webserver running PHP and the computer running the MySQL server are the same machine. That makes localhost appropriate.
localhost is the standard name given to a computer on the private network that only it connects to. For MySQL is has a special meaning and causes the connection to be made via a socket instead of TCP/IP (which is more efficient).
What should I be inserting in the host portion of the connect statement?
localhost if the above is correct.
Or have I made a more basic syntax error in the PHP code that is preventing a connection from being made?
I can't see any syntax errors. I suspect the problem may be down to your database configuration. Have you told the MySQL server about ASOIAF.odb? Is that what the database is actually called inside MySQL (as opposed to just being the file that stores the configuration for LibreOffice to connection to that database).
Your biggest mistake is not using mysqli_error to find out what problems PHP is reporting.
if (mysqli_connect_errno()) {
echo "Failed to connect to database";
echo mysqli_error();
use
mysqli_connect("localhost", "root");
Hope it will work

PHP, can't connect to the MySQL server

What might be the reason of the following problem.
PHP function mysql_connect() works fine if I execute it from
command line (php -r "mysql_connect('127.0.0.1', 'db_user', 'db_pass');").
The same call with the same parameters fails for PHP running as an Apache module.
MySQL server is running remotely, connection to it is forwarded using SSH: ssh -fN -L 3306:localhost:3306 remote_host
Any ideas what might be wrong?
You'll want to be looking at using MySQLi or PDO as the older MySQL functions are deprecated.
This should help get you started:
<?php
//establish conection
$link = mysqli_connect("host","user","pass","bd") or die("Error: " . mysqli_error($link));
$query = "SELECT name FROM mytable" or die("Error: " . mysqli_error($link));
//execute query
$result = $link->query($query);
//display information
while($row = mysqli_fecth_array($result)) {
echo $row["name"] . "<br>";
}
?>
Based on your question and details, I would say that the MySQL server is refusing to connect to your web server (where ever it is) because the connection is not secure (in one fashion or another). If you want to connect via the PHP module in Apache as easily as you do from the command line, set up your connection so that all encryption/ tunneling issues are resolved. That's what I would do.
However, make sure the following line is correct..
mysql_connect('127.0.0.1', 'db_user', 'db_pass');"
Are you pointing to the correct server? I thought you said that the MySQL server was remote. This line suggests that you are attempting to connect to a local, imaginary MySQL server that is running on the same machine as the web server. Try getting the IP or domain name of the MySQL server and use that instead (in your web code, that is).

Connection between MySQL and PHP

I have a Linux server with:
MySQL 5.1.57
PHP 5.1.6
When I try to connect MySQL- The output is a blank page.
The code is attached.
<?php
$link = mysql_connect("localhost", "usr", "pass");
if (!$link) {
die("Could not connect: " . mysql_error());
}
print "Connected successfully";
Btw do you enable mysql module for php? You can check with this command
php -i | grep mysql
or see in web
<?php phpinfo(); ?>
And check PHP error log.
Most likely you don't have the php_mysql extension installed, so it doesn't understand what you're trying to do. To be sure about that, check your web servers error log. It should tell you why it didn't parse the page.
But as Quentin already mentioned in the comments, the mysql extension has been deprecated for quite a while now. Try installing the MySQLi or PDO extension and use that instead. PDO is more flexible and offers prepared statements support, so I'd suggest that.
So, install the PDO extension on your server (see the documentation for more details). And then connect using something like this instead:
$dbh = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
This will connect you to the test database on your localhost. More information can be found in the PHP docs here.

Trouble Connection to phpMyAdmin MySQL database

I'm pretty new at php and I'm getting an error whenever I try to load a php page that requires access to the database I set up on phpMyAdmin
Here is the error:
Database connection failed: Can't connect to local MySQL server
through socket '/tmp/mysql.sock' (46) (2002)
The code I'm using for the connection is this:
<?php
define("DB_SERVER", "localhost");
define("DB_USER", "xxxx");
define("DB_PASS", "xxxx");
define("DB_NAME", "tester");
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection occurred.
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
I set up phpMyAdmin on my server by following the directions from the site that hosts my website, so I'm pretty sure I did that correctly.
I've been able to get databases to work before on my computer by using WAMP, but this is the first time I've actually tried getting everything working online, so I don't know if this is a stupid error on my part, or if it's something bigger.
I don't know what a socket is either so I'm not sure how to troubleshoot this.
Thanks for your help!!
You have to find a way to connect to your MySQL instance. There are two ways, TCP (networking, even if that network address is 127.0.0.1) and sockets (a file such as /var/run/mysqld/mysql.sock). Generally, MySQL is configured out of the box to listen on both, and again in general there's little difference between the two. You have to be careful when creating or editing permissions that they match the connection type, user bob#localhost is different from user bob#127.0.0.1. I tend to use sockets and that's also what your script is trying to do by default. You could tell it to connect via TCP, but it's just as easy to tell it the proper path to the socket.
Anyway, for me the quickest way to figure it out is to try the command line tool. If you can do mysql -u root -p at the command line and get a MYSQL> shell prompt, type in "STATUS" and look for the Connection line, which might read Localhost via UNIX socket; and a bit further down you might see a line like "UNIX socket: /var/run/mysqld/mysql.sock" in which case you just tell your PHP script or global PHP configuration about the socket path, because right now it's looking in /tmp/mysql.sock which doesn't exist.
You can also see this when you log in to phpMyAdmin, it should display on the right hand side of the page some "Database Server" information -- look here for the "Server" line which might read something like "phpMyAdmin demo - MySQL (192.168.30.23 via TCP/IP" (a clear indication you're connecting over TCP).
Anyway, whichever method you use to find the path to the socket or deciding to use TCP networking, see the PHP manual page for information about using that to connect. You can also just set the global path in php.ini for the socket (which is what I'd suggest you do), then you don't have to set it manually in each script as it just uses the php.ini setting as a default. You may need to set each of the values for pdo_mysql.default_socket, mysql.default_socket, and mysqli.default_socket (though in your code you're only using mysqli, so technically you only need to set the last value...but why risk confusing your future self with questions like "why would mysqli work but pdo fail?" -- just set them all now and don't worry about it).
Hope this helps.
That either means you don't have the privileges to access phpMyAdmin or that socket isn't there. Try reinstalling phpMyAdmin.

mysql_real_escape_string works in localhost but not on webserver

I have a PHP script that is inserting a record into a database after getting the data from a user-filled form. I developed on my local machine (WAMP server) and have the following code in my PHP script:
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
//connecting to db
mysql_connect("host", "user", "pass") or die('save_failed');
mysql_select_db("db") or die('save_failed');
//inserting into table
mysql_query("INSERT INTO table(name, email) VALUES('" . $name . "', '" . $email . "' ) ")
or die('save_failed');
The script worked just as expected and the records were being successfully inserted into the table.
As soon as I moved the script to my webserver, I realized the values being stored in the database were empty strings. Removing mysql_real_escape_string fixed this.
Why is it that mysql_real_escape_string won't work on my webserver?
The database I'm working on hasn't changed. Even when developing locally, I was hitting my webserver DB.
PHP ver on localhost is 5.3.8 while on the webserver it is 5.2.
Does PHP 5.2 not support mysql_real_escape_string, and if so what is the alternative?
Put mysql_connect("host", "user", "pass") or die('save_failed'); before mysql_real_escape_string.
You first need to connect to the database, then mysql_real_escape your strings. I suspect it works locally because PHP and your database are configured so they can automatically establish a connection when needed.
http://www.php.net/mysql_real_escape_string
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.
Apparently you should also activate error reporting and/or check your error logs.
From the manual page for mysql_real_escape_string():
Parameters
unescaped_string: The string that is to be escaped.
link_identifier: 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.
Your code uses mysql_real_escape_string() before calling mysql_connect(). That means that PHP is trying to open a connection to the MySQL server before than you think and you are not providing credentials or doing error checking. If it works in your development box, it's probably pure chance: your local server has default credentials at php.ini or a password-less MySQL account.
Move the connecting to db part to the top and you're done.

Categories