This question already has an answer here:
Can't connect to GoDaddy mysqli database via PHP script
(1 answer)
Closed 2 years ago.
I am trying to connect a database to a website. I am using GoDaddy and I am finding it difficult to input the following things in php.
$host = "Where do I find this? Is this a number? Do I put the IP Address: Port Number?";
$dbusername = "Does it contain quotes?" Or is it just the username?;
$dbpassword = "Does it contain quotes?" Or is it just the password;
$dbname = "Does it contain quotes?" Or is it just the database name;
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
I am assuming the port number is right next to the localhost.
$host => Specifies a hostname or an IP address(For example: localhost).
$username => Specifies the MySQL username(For example: my_user).
$password => Specifies the MySQL password(For example: my_password ).
$dbname : => Specifies the default database to be used(For example: my_db).
All these contain a name with quotes on them.
For example:
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
Related
I'm trying to build a blog website.
It is deployed on Heroku and it is supposed to connect to a MySQL database. The info required to login to my database is stored in an environment variable on Heroku, and looks like this (These are fake credentials of course):
mysql://g46w916ds134b8:639f463e#us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true
It contains the DB name, the user, the password and the host.
Is there a way to use this one string directly in my PHP code to connect to the database? I checked MySQLi and PDO documentation, and it seems like they only accept DSN/user/password or Host/user/password/DBname format.
This is a url after all, so you can use parse_url function to extract data.
// Connection string from environmental variable in heroku
$connectionStringHerokuEnv = 'mysql://g46w916ds134b8:639f463e#us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true';
$parsed = parse_url($connectionStringHerokuEnv);
$dbname = ltrim($parsed['path']. '/'); // PATH has prepended / at the beginning, it needs to be removed
// Connecting to the database
$conn = new PDO("{$parsed['scheme']}:host={$parsed};$dbname={$dbname};charset=utf8mb4", $parsed['user'], $parsed['pass'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
For database connection you should always use PDO and not mysqli driver. PDO allows you to connect to almost any database, without rewriting code in 85% of cases.
dont forget options [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION], this will allow you to catch any errors and handle them accordingly to application needs.
PDO accept this connection string driver: host=DATABASE_HOST;dbname=DATABASE_NAME; charset=DEFAULT_CHARSET(use utf8 whenever you can)
Learn more on parse_url: https://www.php.net/manual/en/function.parse-url
Learn more on PDO:
https://www.php.net/manual/en/class.pdo.php
<?php
$str = "mysql://g46w916ds134b8:639f463e#us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true";
// If I correctly understanded 'mysql://login:passwd#host/dbname?some_params'
// data parsing from input string
$sp = explode('/', $str);
$sp1 = explode('#', $sp[2]);
$first_part_sp = explode(':', $sp1[0]);
$login = $first_part_sp[0];
$passwd = $first_part_sp[1];
$host = $sp1[1];
$dbname = explode('?', $sp[3])[0];
$connect_str = "mysql:host=$host;dbname=$dbname";
echo $connect_str." ".$login." ".$passwd;
// database access
$pdo = new PDO($connect_str, $user, $passwd);
?>
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I would be grateful for any insight relating to my issue described below. Please excuse my ignorance as I am working to lessen it.
I am using PHPMyAdmin to create the database and php to connect a website to the database.
I have confirmed that the database does connect and I can create a form on the website to populate fields in the database.
What I cannot do is create a Query that returns results and publishes them on the website. I have used YouTube videos, Code Igniter tutorials and W3 tutorials and continually end up with the same problem. Deduction leads me to believe that there are issues with my database.
This is the relevant code:
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "news";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, title, slug FROM ci_nws";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<br> id: ".$row["id"]. " - Name: ".$row["title"]. " " .$row["slug"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
The error message refers to line 18
if (mysqli_num_rows($result) > 0) {
the "0 results" does display below the error message.
I am using
Database server
Server: Localhost via UNIX socket
Server type: MySQL
Server connection: SSL is not being used Documentation
Server version: 5.6.46-cll-lve - MySQL Community Server (GPL)
Protocol version: 10
Server charset: UTF-8 Unicode (utf8)
Web server
cpsrvd 11.78.0.38
Database client version: libmysql - 5.1.73
PHP extension: mysqliDocumentation curlDocumentation mbstringDocumentation
PHP version: 7.2.7
phpMyAdmin
Version information: 4.8.3
If relevant I am using Godaddy economy hosting package.
Any thoughts?
Thanks in advance.
You missed the database name from the connection
<?php
$servername = "localhost";
$username = ""; //<-- needs a valid username
$password = ""; //<-- needs a valid passsword for this username
$dbname = "news";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// -----------------missing part here ^^^^^^^
Remember, A MySQL instance can have multiple databases within it. So you must select the database you want to use either as part of the connection call or as a seperate mysqli_select_db() call
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 4 years ago.
Working with a Wordpress website that is being hosted by Godaddy. I am familiar with creating custom templates and scripting pages (php) and running them on this specific Wordpress webpage.
I am at the point where I need to access my mysql database and interact with custom templates+data via programmatically. Just in the past few days I've searched hundreds threads+tutorials and copied examples with no luck. I have a created a php file called display_data.php
Code:
<?php /* Template Name: display_data */ ?>
<?php
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = ''; // Password
$db_name = 'tutorial'; // Database Name
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = 'SELECT *
FROM sales';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
I get this error:
"Failed to connect to MySQL: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)"
I have had no luck figuring out what this error specifically means in my case and I've searched for many hours.
I am at the point where I believe I am missing something stupid simple that I am looking past.
Either I am filling the parameters wrong - $db_user, $db_pass, $db_name, or missing something entirely.
I used the same parameters (User name, password) from the ones I got from Godaddy to access phpmyadmin, and for $db_name I used the one I see in my database (picture).Taken from my database, I used what is said to the right of "Database:"
Taken from Gogdaddy (Database PHPMyadmin - View)
Please any help is greatly appreciated, and be nice. I've never used mysql before but I am also not a total noob to programming.
Thank you.
Why dont you just try using wpdb? This is what you should use to work with secondary databases in WP.
$mydb = new wpdb('username','password','database','localhost');
$rows = $mydb->get_results("select Name from my_table");
echo "<ul>";
foreach ($rows as $obj) :
echo "<li>".$obj->Name."</li>";
endforeach;
echo "</ul>";
I'm hosting a domain at 1&1 and I want to connect with my database using pdo. Without using a port, it doesn't work and I don't know how to add the port to my code....
$mysql_host = "xxxxxxxxx";
$mysql_username = "xxxxxxxxxxxxxx";
$mysql_database = "xxxxxxxxxxxxxxx";
$mysql_password = "xxxxxxxxxxxxxxx";
$pdo = new PDO("mysql:host=" . $mysql_host . ";dbname=" . $mysql_database , $mysql_username , $mysql_password);
Im not sure but maybe the Problem doesn't go together with the connection, but with the mysql-commands...
$schematic_statement = $pdo->prepare('SELECT title FROM schematics-download WHERE id = 1');
$schematic_statement->bindParam('title', $Title);
$schematic_statement->execute();
$TITLE = $schematic_statement->fetch();
echo ($TITLE);
Thank you for your help!
"Without using a port, it doesn't work and I don't know how to add the port to my code...."
This (probably) has nothing to do with porting.
Your code however, contains a few (syntax) errors.
1) You can't bind a column (or a table)
Your SELECT title and bindParam('title' suggest it.
2) FROM schematics-download - mysql is interpreting that as FROM schematics MINUS download, therefore you need to escape the table name.
I.e.:
FROM `schematics-download`
If this is a porting issue, then this user contributed note shows you how to do it.
$conn = new PDO('mysql: host=123.4.5.6;dbname=test_db;port=3306','username','password');
^^^^^^^^^^
and from http://php.net/manual/en/ref.pdo-mysql.connection.php
More complete examples:
mysql:host=localhost;port=3307;dbname=testdb
mysql:unix_socket=/tmp/mysql.sock;dbname=testdb
As for error handling, PDO has that:
http://php.net/manual/en/pdo.error-handling.php
which would have thrown you a few.
Taken from Chris' comment:
"Later you fetch which returns an array so $TITLE can't be echoed."
Take a look at the documentation on fetching data in PDO:
http://php.net/manual/en/pdostatement.fetch.php
There are ample examples in there to show you on to do this.
I've recently made a new database that I had local. Everything worked fine and the scripts I've used (mysql and php codes) have been working properly. Since I've changed the database from local to online it has only caused problems with my script. Of course I've changed the details of connecting to MySQL database (having a password and such). Also, the content after the script won't work either.
Note: I haven't changed my script AT ALL. I've only changed the connection part.
$dbhost = "localhost";
$dbuser = "dbuser";
$dbpass = "dbpass";
$dbname = "compunll_itnj01";
$con = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$so = $con->prepare("SELECT * FROM besteloverzicht");
$so->execute();
--- rest of code
My apologies if I've forgotten to put anything further here. You can ask me and I'll respond asap!
Try to set the ip address of your db online
$dbhost = 'xx.xxx.xxx.xxx';