Connecting to a database in SQL and PHP [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm making a website that uses SQL and PHP functionalities. How do I connect to a database?

I would advise you begin by looking here.
You need to ensure that you have created user credentials with the correct permissions to query the database before you try this. You can do this through the cPanel of your web server (I'm going to assume you are using a web hosted server for this question).
Once you have a working and tested connection to the database, you can then start looking at the mySQLi documentation here. Which will show you how to execute and retrieve results from a database query and how to handle the returned data with PHP.

I see you are seriously downvoted.
I learned it the hard way and I am still learning to post here.
Stack sites are supposed to be searched first. If your question is already answered then people downvote you.
The solution to your question:
In your mysql or phpmyadmin you can set whether you use a password or not. The best way to learn is to set mysql with a password in my opinion. If you will launch a website online finally, you have to take security measures anyway.
If you make contact to your mysql database with you have to set:
username, password, database and servername ( for instance localhost).
The most secure way is using the OOP / prepared method:
$servername ='localhost';
$username='yourname';
$password='12345';
$dbname='name_database';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($stmt = $conn->prepare("SELECT idnum, col2, col FROM `your_table` WHERE idnum ='5' ")) {
$stmt->execute();
$res = $stmt->get_result();
$qrow = mysqli_num_rows($res);
while ($row = mysqli_fetch_assoc($res)) {
var_dump($qrows); // number of rows you have
$total = implode(" / " , $row);
var_dump($total);
$idnum = $row['idnum'];
var_dump($idnum);
}

The easiest way that I do with my site is make a file called db.php containing:
<?php
$host = 'localhost';
$user = 'root';
$pass = 'password';
$db = 'databasename';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
..then in the index.php file, at the top:
<?php
require_once('db.php')
?>

Related

How to Auto run PHP file on windows server? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am a newbie of PHP
and I would like to create a php file that can autorun on the windows server at a specific time.
any idea to achieve??
My PHP File
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Anyidea, Thank you very much.
You may execute a php on windows machine thru the command line:
“php c:\[directory]\[folder]\[phpscript].php”.
So if you want the machine to execute it every day at a specified time, please put the command into the windows scheduler and set the time.
First create .bat file and show the file location as per below.
php D:\wamp\www\test\test.php
You can do by window scheduler from your window machine. Then your file will auto run at your specific mentioned time.

Which username and password should be give in order to connect to database? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have these usernames and passwords:
User name: AmirAman
Pin: ****
Password: ***************1
Parallels Plesk: qatarreal
password: *************2
DataBase:
username: amir
password: ***3
When I type this code in index.php file, it doesn't work and Internal Server Error appears:
<?php
$username = "AmirAman";
$password = "**********1";
$hostname = "www.qatarreal-estate.";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
thank you for this answers , i tried all possible suggestion , but there are no thing changed , same result appear in this website qatarreal-estate.com.
DataBase:
username: amir
password: ***3
You will need to use these, like the following:
$username = "amir";
$password = "***3";
$hostname = "localhost";
I'm assuming the hostname of the mysql database is local, due to it not being defined in the information and webhosting providers sometimes leave that information out if it's on localhost.
Also note that you are using mysql_* functions which are considered bad practice and will be removed from PHP in the near future. Better is to use the PDO class or at least mysqli_* functions.
As other people pointed out in the comments, your hostname is wrong. Try this:
enter code here
<?php
$username = "AmirAman";
$password = "**********1";
$hostname = "qatarreal-estate.com";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
Assuming qatarreal-estate.comis the domain you are looking for.
Edit: If you run the MySQL server locally, use localhost or 127.0.0.1 for the hostname.

How to use a backup db connection using PHP/Mysql [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have a function that handles my db connection. In casse my main DB isn't available I want to use a backup one.
I tried to do so using below code but it's not working...
$host = 'xxx';
$database = 'xxx';
$login = 'xxx';
$pass = 'xxx';
if (! mysql_connect( $host, $login, $pass ) )
{
// try to connect to backup db
$host = 'yyy';
$database = 'yyy';
$login = 'yyy';
$pass = 'yyy';
mysql_connect ( $host, $login, $pass ) or die ( "Failed to connect to the database: " . mysql_error());
}
mysql_select_db ( $database ) or die ( "Failed to find the database" . mysql_error());
mysql_query("SET NAMES 'utf8'");
I'm sure about my connection parameters, so the problem isn't there
Edit:
I'm using an old version of php so I'm limited to Mysql_*
My 1st server is currently down, and I'm getting a 'Warning: mysql_connect() [function.mysql-connect]: Too many connections in ...' error
In fact my problem is that I need NOT to print this warning message if the 1st connection failed...
Please note Mysql_* is deprecated, use mysqli_ or PDO which is far more secure.
Have you tried outputting the error? I don't see it in your code.
I haven't used mysql_ for a long time, but try outputting the error using:* mysql_error()
As mentioned, it could be a variety of problems:
Mysql isn't started
Firewall is blocking the connection
Not using default port
...
Edit:
Also you may want to look into setting up replecation for such events as DB failure.
Don't do this in your code, just use something like MySQL Proxy to do it for you.
When php fails to connect, it generates a warning, which stops the php execution.
You may use #mysql_connect (function name prefixed with an "#") to avoid the warning. And your code will continue to execute, even if first sql server does not respond. crappy, but working.

PHP: Displaying table contents on html page [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
New to PHP. Trying to simply output the contents of a mySQL table onto my HTML page. Here is my html code:
<body>
<div>
<?php
$hostname = "XXXXX";
$username = "XXXXX";
$password = "XXXXX";
$db_name = "XXXXX";
//connect to database
mysql_connect($hostname, $username, $password) or die("cannot connect to server");
mysql_select_db("$db_name") or die("cannot select database");
$sql="SELECT * FROM myTable";
$result=mysql_query($sql);
if (!$result) {die("SQL error retrieving data.");}
while ($row = mysql_fetch_array($result)) {
echo $row['field1'] . $row['field2'] . "</br>";
}
mysql_close();
?>
</div>
</body>
My output is simply this:
"; } mysql_close(); ?>
I know that there is data in the table. I can't see what I am doing wrong. Can anyone help? Thanks!
Try change your file extension to .php instead of .html
Please change your connection to PDO or mysqli because mysql is soon deprecated
The code is not interpreted as PHP code. Thus, the Browser interprets <?php as the start of a HTML element that is closed by /br>. This HTML element is unknown to the browser and therefore ignored. The following lines
";
}
mysql_close();
?>
are then visible in the browser, because they are not part of a HTML element.
You might need to uncomment an appropriate extension for mysql from php.ini, if you have php installed of course.
Also I would suggest you to use sqlite. It is easy to start and manage you DB, check it out: http://php.net/manual/en/book.sqlite.php

Not able to connect to MySQL server using PDO [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a PHP script which I use to connect to a MySQL database. Connection through mysql_connect works perfectly, but when trying with PDO I get the following error:
SQLSTATE[HY000] [2005] Unknown MySQL server host 'hostname' (3)
the code I use to connect is below:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$hostname_localhost ="hostname";
$database_localhost ="dbname";
$username_localhost ="user";
$password_localhost ="pass";
$user = $_GET['user'];
$pass = $_GET['pass'];
try{
$dbh = new PDO("mysql:host=$hostname_localhost;dbname=$database_localhost",$username_localhost,$password_localhost);
echo 'Connected to DB';
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT check_user_company(:user,:pass)");
$stmt = $dbh->bindParam(':user',$user,PDO::PARAM_STR, 16);
$stmt = $dbh->bindParam(':pass',$pass,PDO::PARAM_STR, 32);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row)
{
echo $row['company_id'].'<br />';
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Thanks in advance
Got the same problem. Mine solution was another database port. I wrote localhost:1234 and got this error.
Fixed with:
mysql:host=$hostname_localhost;port=1234;dbname=$database_localhost",$username_localhost,$password_localhost);
echo 'Connected to DB';
It does seem pretty straightforward, here is what I use to build my PDO connectors(noticed your dbname and host are done differently than mine, dunno if that's relevant, but worth a check):
PDO Creation function
require_once('config.inc.php');
function buildDBConnector(){
$dsn = 'mysql:dbname='.C_BASE.';host='.C_HOST;
$dbh = new PDO($dsn, C_USER, C_PASS);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
config.inc.php
define('C_HOST','localhost');// MySQL host name (usually:localhost)
define('C_USER','sweetUsername');// MySQL username
define('C_PASS','sweetPassword');// MySQL password
define('C_BASE','superGreatDatabase');// MySQL database
And while it makes no sense, when I tried to declare $dsn inline including variables during the newPDO call, I kept getting failures too. I broke it apart and used the $dsn variable to do so. And haven't had an issue since.
Wondering if you're in shared hosting by chance?
NOTE:
If you don't have a dedicated IP, and instead are going through a NAT, your IP won't properly translate to your actual server.
That help at all?
UPDATE:
Just thought of another thing. Are you trying to connect to a mysql database that is on a different IP than you are running your scripts from? If so, you will likely need to enable remoteSQL access for the ip you are calling the database from. Fairly easy to do, but CRITICAL if you are not accessing localhost.
You dont seem to specify the database host dns details or IP address. Adding that will solve the problem

Categories