I would like to print the measured data of my weatherstation on a website. Therefore I would like to connect my MariaDB-database. Here ist my code.
<?php
$username = "root";
$password = "M1lVhPuio";
$database = "weatherbot";
try {
$pdo = new PDO("mysql:host=raspberrypi;port=3306;database=$database", $username, $password);
//Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
die("ERROR: Could not connect. ". $e->getMessage());
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Wetterstation </title>
</head>
<body>
<h1> Meine Wetterdaten </h1>
</body>
</html>
When I open the website, I see this: "ERROR: Could not connect. SQLSTATE[HY000] [2002] Connection refused"
There's already an entry in this forum about this case, but adding the port didn't work for me. (3306 is the right port.)
Like Sergio Rinaudo said, I had to use the default address instead of "raspberrypi":
$servername = "127.0.0.1";
try {
$pdo = new PDO("mysql:host=$servername;port=3306;database=database", root, M1lVhPuio);
Thank you for your help!
Related
This question already has answers here:
How to secure database passwords in PHP?
(17 answers)
Closed 2 years ago.
I have a main page on my site and I am trying to make a connection to the MySQL server and get some data from the database.
But the problem is that when I want to establish a connection I have to put the username and password in the page which doesn't seem wise to me.
I added a part of my code related to this problem.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
if ($connection->connect_error) {
die("Connection failed due to this error : " . $connection->connect_error . '<br>');
}
else{
echo "Connected successfully";
{
</body>
</html>
Put your connection code into another file, like connection.php and in every page you want to connect you should require_once "connection.php", also you could use variables from that file if you connect it, also instead of require_once you can use just require, but look at the internet differences between them
Normal practice is to put the mysql data in a separate php file. For example:
dbmain.php
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
?>
then you can include this file in all php files which require db connection.
<?php include_once("dbmain.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
/// php commands, such as
//if ($result = $mysqli -> query("SELECT * FROM dbtable1")) {
// echo "Returned rows are: " . $result -> num_rows;
// Free result set
// $result -> free_result();
//}
//$mysqli -> close();
?>
</body>
</html>
I have a problem with providing infromation from a mysql database through php. I am working with brackets and always when I try to connect with my database (opening my connection, giving information about my server, port and the name of the dtabase -> shown in the code below) nothing happens. I can not administrate my database with phpmyadmin I know that would be easy. I also have xamp and a apache server working, but then I would have to use phpmyadmin to connect.
But is there a way to connect the database (created with mysql workbench running on localhost 127.0.0.1 and port 3306) only like that with my php file. Or is the problem that I have a mistake in my code?
Code:
File one: db_connection.php
<!DOCTYPE html>
<html>
<header>
<center> <h1>My New Website </h1> </center>
</header>
<body>
<?php
//die echo Funktion, ist dafür da, dass etwas in den Browser ausgegeben wird (same as Syso)
//echo "Hello World!";
function OpenConnection()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "";
$dbname = "dml_final";
$connection = new mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname)
or die ("Connection failed: %s\n". $connection -> error);
return connection;
}
function CloseConnection()
{
$connection -> close();
}
?>
</body>
</html>
File two: index.php
<?php requires 'db_connection.php'; ?>
<!DOCTYPE html>
<html>
<header>
<center> <h1>My New Website </h1> </center>
</header>
<body>
<?php
$connection = openConnection();
echo "Connection successfully!";
CloseConnection($connection);
?>
</body>
</html>
If you want to use your current way, change function to public function so that it is globally available across your website, I recommend the following method instead:
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "";
$dbname = "dml_final";
$connection = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
if(!$connection) {
die("Connection failed:".mysqli_connect_error());
}
And you include this in all of your PHP files. To close the connection, simply run a mysqli_close($connection);. I don't know about you, but I find this way more simple.
I have the following code:
<?php
//Step1
$db = mysqli_connect('localhost','root','[mypassword]','users')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
</body>
</html>
I am just trying to connect to my MySQL database. It is administered using phpMyAdmin. I am very unfamiliar with MySQL and I have never used it before. [mypassword] is the password I use to successfully connect to mySQL from the Mac terminal. "users" is a name of a table I have created in phpMyAdmin. I am using cPanel. I keep on getting the error:
Error connecting to mySQL server.
In phpMyAdmin it says Server: localhost:3306. I have tried for a very long time to fix this problem but with no results. What am I doing wrong?
I have also tried the following:
<?php
$servername = "localhost";
$username = "root";
$password = "[myPassword]";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $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();
}
?>
After visiting the webpage it says
Connection failed: SQLSTATE[28000] [1045] Access denied for user
'root'#'localhost' (using password: YES)
Be sure that your mySql instance is up. You can download sequelpro and use that to connect to your mySQL. If that doesn't work then its a mysql setting/config that is wrong.
You can try this code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
How to Connect to mysql using php
Use a try catch to handle errors on the connection proccess, but i strongly advise you to use PDO by alternative from mysqli PDO Book
Use something like this:
<?php
try
{
if ($db = mysqli_connect($hostname_db, $username_db, $password_db))
{
//do something
}
else
{
throw new Exception('Unable to connect');
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
And check if the code print some connection error.
Reference: how to use throw exception in mysql database connect
I have hosted my website on Linux server and I want to connect MS SQL database. i have used PHP in programming. I have contacted to both server provider and they helped in their extent. But my issue is not solved Can you guide me what to do. My code is below.
While I run this it is showing " could not find driver1"
Please guide me. Thanks in advance
<?php
//echo phpinfo();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>testing</h1>
</body>
</html>
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = 'server:port';
$myDB = "DatabaseName";
// Connect to MSSQL
$link = mssql_connect($server, 'username', 'password');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else
{
echo "success";
}
?>
<?php
try {
$conn = new PDO("sqlsrv:Server='server_name';Database=database_name", 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
die(print_r($e->getMessage() ));
}
$tsql = "select * from table_name";
$getResults = $conn->prepare($tsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach ($results as $row) {
echo $row['0'].' '.$row['6'];
echo "<br>";
}
?>
I am trying to use php for the first time to connect to MySQL on the raspberry pi. Both the server and MySQL are running on the Pi and I want to tweak my index.html file to show some value that is in the data base. Normally for I would be able to do just that with pyton but I have no clue if I can do that with php. Here is my index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ziks</title>
<link href="CSS/style1.css" rel="stylesheet" type="text/css">
<style type="text/css">
body {
background-color: #FFFFFF;
background-image: url(Images/twe_background-1920x1080.jpg);
}
</style>
</head>
<body>
<div class="header">
<p><strong>Welcome to Ziks</strong></p>
</div>
<p> </p>
<div class="box">
<p> Wishing every one a happy life! </p>
<form method="GET" action="ftp://47.55.90.215:21">
<input type="submit" value="Click here to view Disk">
</form>
<body>
<html>
<body>
</body>
</html>
</body>
<div class="image"></div>
<iframe src="http://free.timeanddate.com/clock/i5nb4b3g/n1127/szw160/szh160/hoc9b8578/hbw10/hfc754c29/cf100/hnc432f30/hcw2/fav0/fiv0/mqcfff/mqs4/mql25/mqw12/mqd78/mhcfff/mhs2/mhl5/mhw2/mhd78/hhcfff/hhs2/hhl50/hhw8/hmcfff/hms2/hml70/hmw8/hmr4/hscfff/hss3/hsl70/hsw3" frameborder="0" width="160" height="160"></iframe>
<video width="400" controls>
<!--<source src="///smb://zikpc/f/test.mp4" type="video/mp4">-->
<!--<source src="///smb://zikpc/f/test.ogg" type="video/ogg">-->
<source src="1.mp4" type="video/mp4">
<source src="1.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
</div>
</body>
</html>
This index.html file works fine. All I want to do is write some php in it to connect to MySQL. The current method I'm using in python is:
# External module imports
import time
import os
import datetime
import MySQLdb
os.system('sudo modprobe w1-gpio')
os.system('sudo modprobe w1-therm')
# Connect to mysql
db=MySQLdb.connect("localhost","zikmir","gforce","temp_database")
cursor=db.cursor()
while True:
# Initialization
sensor= "/sys/bus/w1/devices/28-011620ee98ee/w1_slave"
# Open the file for sensor
file = open(sensor)
# Read all of the text in the file.
text = file.read()
# Close the file now that the text has been read.
file.close()
# Split the text with new lines (\n) and select the second line.
second_line = text.split("\n")[1]
# Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
temp_data = second_line.split(" ")[9]
# The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
temp = float(temp_data[2:])
# Put the decimal point in the right place and display it.
temp = temp / 1000
# Display time
t= datetime.datetime.now()
print t,temp
# Push data into mySQL
sql = "INSERT INTO time_temp VALUES(now(),%s)"
cursor.execute (sql,(temp,))
db.commit()
# Wait 5 seconds
time.sleep(5)
My question is how would I be able to do this in php within the index.html file? Any help would be appreciated!
This is my website
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";
?>
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $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();
}
?>
You have a number of choices. The simplest, IMHO, would be something like the following.
Rename your index.html file to index.php (make sure that your web server looks for index.php as well as index.html and index.htm).
Your index.php would then be modified to look something like this:
<?php
//Open MySQL connection
//Get the data you want into a string variable called $info
print <<< END
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ziks</title>
<link href="CSS/style1.css" rel="stylesheet" type="text/css">
<style type="text/css">
body {
background-color: #FFFFFF;
background-image: url(Images/twe_background-1920x1080.jpg);
}
</style>
</head>
<body>
... (rest of HTML excluded for brevity)
END;
?>
Simply put the $info variable where ever you want the data to appear in the HTML data.
The construct:
print <<< END
<<<what you want to print>>>
END;
is called a "heredoc" and is very handy.
I have not described how to actually get the data from the database since your question seemed more about the process of using PHP to output HTML with data from a database. Look at the PDO documentation (PDO documentation) to quickly get up to speed on DB access in PHP.