i just wanted to insert data into database from a form, with php. i ran the code below in my Localhost using XAMPP and everything was fine but where i upload it to my host it didn't work.
Question is What shold i put for $servername and when should i look for it ?
There is my codes:
Register.php (in localhost)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$Name = $_POST['Name'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Email = $_POST['Email'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header("Location:#");
}
//Inserting Data
try{
$sql = "INSERT INTO User (uName , uUsername , uPassword , uEmail) VALUES ('$Name' , '$Username' , '$Password' , '$Email')";
mysqli_query($conn, $sql);
}catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$conn->close();
header("Location:#");
}
?>
If your MySQL database is on the SAME SERVER as your PHP script, then the usual logical approach is that your host is localhost. The same as you used on your local computer -- because they're on the same machine.
However, if your MySQL database is on ANOTHER SERVER seperate from your PHP scripts the you will need to access that server using a web address for your PHP to connect to yout MySQL.
We can't tell you what that is, and your server hosts (of your MySQL server) will be able to tell you and provide you with the correct login credentials.
I believe it would be more usual for MySQL and PHP to be on the same disk, especially for non-professional systems as your appears to be, so then the issue would be:
Are your login details set up correcty on your server? (same username/password)
Are there any MySQL errors or PDO errors (if you connect with PDO). Don't redirect on error, but instead output the error to a log file so you can read WHY the MySQL in your code didn't connect.
It is still possible for you to set your PHP to communicate with your localhost MySQL via a remote address (such as servername=$_SERVER['SERVER_NAME'];). (see note below)
Many online accounts (in things such as CPanel) will block you from accessing the MySQL as a root or at least will not give you the root MySQL password. Using root to access MySQL via PHP is NOT a good idea and you should instead set up a specific MySQL user for your PHP with only enough privileges that you need to read/write to the DB, and nothing more.
If your MySQL is remote (not localhost) then you may also need to supply a Port Number with the connection details. Usual port numbers are 3306 but this is something you'd need to know from your server hosts.
Immediately after a header(Location:); redirection instruction you should always set die(); or exit to stop PHP processing the rest of the script.
Your SQL insert data is highly suseptible to SQL injection and other SQL attacks and compromise. You should really, REALLY look into using MySQL Prepared Statements, you're already coding in OO style so you're almost there already.
Example remote connection from the manual
<?php
/***
* Remember 3306 is only the default port number, and it could be
* anything. Check with your server hosts.
***/
$conn = new mysqli('remote.addr.org.uk', 'username', 'my_password', 'my_databasa', '3306');
/***
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
***/
if ($conn->connect_error) {
error_log('MySQL Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
/***
* Upon failure, the above will output a connection error notice such as
* user not found or password incorrect. It won't explicity say these
* things but you should be able to deduce which from the notice
***/
echo "Success... \n" . $conn->host_info ;
$mysqli->close();
# : I seem to think that MySQL detects when the remote address given is the same as the server address and auto converts it to localhost, but I'm not sure on this.
The long and the short of it is that if your MySQL is on the same
server as your PHP it makes no sense to open up a network loop to send
data out just to get it back again. Use localhost instead.
I asked my host service providers about the "$servername" and they answered me that the "$serverneme" is localhost.
Related
I'm a total beginner when it comes to PHP, I have a fair grasp of the syntax but I'm not sure about the safest way to utilise it to connect to my server. I apologise that this is a sort of generic question rather than a code problem, since my code technically works.
I have a .php site doc with a basic comment submission form. The only way I can think of to connect to the server is to allow a "dummy" user with select only privelege to call a stored function to accept the comment.
If my dummy account is called siteuser then am I going round this the right way? This is the section of the PHP that I'm using to connect. I believe this code is only visible server side so nobody can ever see it and use the password or username to connect some other way? Or is there a sort of default string I can use in my php without creating the dummy user, seeing as the php and server is all hosted via the same provider?
$sqlserv = "localhost";
$sqlname = "siteuser";
$sqlpass = "mypassword";
$sqldbdb = "comments_table";
$conn = new mysqli($sqlserv, $sqlname, $sqlpass, $sqldbdb);
What i do is this to connect to my DB
db.php:
<?php
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('/somepath/config.ini');
//Mysqli Connection
$conn = new mysqli($config['host'], $config['user'], $config['pass'], $config['dbname']);
if($conn->connect_errno > 0){
die('Unable to connect to database [' . $conn->connect_error . ']');
//Set encoding
mysqli_set_charset($conn, "utf8") or die;
}
?>
and in config.ini:
[database]
user = johndoe
pass = someweirdpassword
dbname = the_name
host = localhost
both files have 700 permissions, so only user (and no one else can access it)
also the config.ini file is placed somewhere outside the public_html directory, i'm not totally sure if that helps or not but i do it that way.
I just installed MAMP and have created a MYSQL database. I can access it via PHPMYADMIN.
In my php page I have this, pasted directly from the MAMP webstart page--
$user = 'root';
$password = 'root';
$db = 'local_db';
$host = 'localhost';
$port = 3306;
$link = mysql_connect(
"$host:$port",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
The resulting page stops at this point, won't print anything below these instructions.
I've tried changing the port in the MAMP preferences. I also included or die("Could not connect"); after the first line, but still don't get any text after the link data in the page.
I checked online, and others with the problem at least see the die text. I don't get that.
I haven't changed any passwords or data other than mess with the port number.
Any help would be appreciated!
Please give the following a try, I have developed and tested it locally, functionality within has been documented to help you understand what is going on in every step.
/**
*
* Modern method of connecting to a MySQL database and keeping it simple.
*
* If you would like to learn more about PDO,
* please visit http://php.net/manual/en/book.pdo.php
*
*/
//Set up database connection constants, so they cannot be changed.
define('DBHOST','127.0.0.1'); //Change this to the ip address of your database
define('DBNAME','test'); // Change this to the database name you are trying to connect to.
define('DBUSER','databaseuser'); // Insure this user is not the root user!!!!
define('DBPASS','databasepassword'); // Insure this is not the root password!!!!
//Let's try to connect to the database first.
try {
//Initiate a new PDO object called $MYDB and pass it the proper information to make
//the connection
$MYDB = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME."", DBUSER, DBPASS);
//If we are successful show it :D for the test page, if this is for production you should not show this.
echo "Database connection was successful.";
//If this does not worth catch the exception thrown by PDO so we can use it.
} catch(PDOException $e) {
//Show that there was an issue connecting to the database. Do not be specific because,
//user's do not need to know the specific error that is causing a problem for security
//reasons.
echo "Oh, sorry there was an issue with your request please try again.";
//Since we had an issue connecting to the database we should log it, so we can review it.
error_log("Database Error" . $e->getMessage());
}
//Since this is 100% php code we do not need to add a closing php tag
//Visit http://php.net/manual/en/language.basic-syntax.phptags.php for more information.
If you have any issues with this please attempt to break it up into smaller pieces while reviewing the PDO documentation.
I have one file on one web serve and my phpmyadmin SQL databases on a seperate server and am currently trying to connect to my external serve but it doesnt seem to work.
I keep getting the error message:
'Access denied for user ''#'localhost' (using password: NO)'
and am not sure what this means.
Any help would be greatly appreciated or even an article to get started on figuring this out since I cant seem to find anything myself.
Thank you
EDIT --- PDO SCRIPT ---
My PDO Script is the generic one from w3, I have place holders for security reasons.
<?php
$servername = "externalIP";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=Reservations", $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 to find your phpmyadmin page where you login using also a password.
Try this one :if you have not assign password into database for specific user then you just have to apply 'root' as user and leave blank password field and also set your hostname as 'localhost' or 127.0.0.1
also remember that you have to start first apache and mysql services before access.
If you are using remote server as database then not required.in that case you have to apply your remote Ip address and also remember that in that remote server if you have not specific user then leave password as blank. one another way to debug mysql connection into your remote server creating mysql connection file with its required paramter to check that your remote server ok or not.
This error will come most probably because of user permission issue. Make sure you have privilege to that user for that database.
I want to send form data to a server online.
At the moment i'm using xampp so the username and password are 'root' and ''
If I was to put this online I would have to put my hosting login details. Is that correct?
Clearly that would be a very serious security issue as anybody could see it written in my process file.
I have found a lot of info about prepared statements to prevent SQL injection but nothing about how to hide username/password, which I would have thought would be a bigger thing.
Am I missing something essential about usernames/passwords?
(I am not trying to create user login accounts, just basic newsletter signup)
<?
// database details
$servername = 'localhost';
$username = 'username';
$password = 'password';
$database = 'database';
// form submission
$email=$_POST['email'];
// connect to database
mysql_connect($servername, $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
mysql_query("INSERT INTO newsletter VALUES ('$email')");
Print "Your information has been successfully added to the database.";
mysql_close();
?>
Update:
Ok, so I have since included prepared statements into my code, and it now looks like this:
<?php
// database details
$servername = 'localhost';
$username = 'username';
$password = 'password';
$database = 'database';
// form submission
$email=$_POST['email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO scenariosubmission (Email) VALUES (?)");
$stmt->bind_param("s", $email);
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
My code should prevent SQL injection
So what I want to know is if I was to enter my username password database and upload this to the server, would those details be safe if I uploaded them like any other web page to public_html?
So when you move this to your hosting, the code will be something like this:
<?
// database details
$servername = 'localhost';
$username = 'your userid with your hosting company';
$password = 'hosting company provided mysql password';
$database = '';
Will that be a big security issue of everyone being able to see your MySQL password?
Not really, because only you and the people working for the hosting company should be able to see the PHP code. And the people working at the hosting company will have the root password to the database anyway, so they could look at what you have in the database without your particular mysql credentials.
But using <? rather than <?php may cause your code to be transmitted instead of run on some server setups. So if you upload it that way, initially some users may end up seeing the passwords you have in the code before you figure it out and fix it.
Another more serious issue than this is if the hosting company has you using phpmyadmin over http rather than https, because every time you login to it your credentials will be transmitted in plain text.
Well there a couple of things in play here.
Since you mentioned SQLi and considering you're using PHP + MySQL, you should look into doing prepared statements, by using the prepare(), bind() and execute() functions.
Second, even before thinking about putting something online or using SQL properly is to change the default username/password.
Now if you want to put your server online, I'm assuming you have a server or the credentials to someplace where you can ran either XAMP or configure its services by hand. Anyway, those credentials are the Database's, which are different from your host server login credentials.
As long as that .php file is properly secured on the server, it's common practice to have the username/password there in the file.
I have to build an android app which connects to a remote MYSQL webserver and retrieve information for display purpose.
So I did research coz I had no idea where to start. I read an article it mentions the better approach for that is to use php script. And didn’t know anything about how server, database and php works, so I studied php from here “http://www.homeandlearn.co.uk/php/php12p1.html” to understand and downloaded WhampServer to do some testing. On local machine everything worked fine.
But main thing I don’t understand is “HOW TO CONNECT TO REMOTE SERVER/DATABASE”.
It’s obvious that I’m doing something really stupid, I just need help to find out what am I doing wrong.
When we test php script on local machine in webrowse we use "localhost/some.php." But when I want to test same php script on remoter server from my local machine then what and how should I do? Do I need to make some changes in configuration file on server side?
I have done more research before asking this question here to understand remote server connection in php but I still don’t understand. I have gone through almost all the pages within the link below:
https://www.google.co.uk/search?q=connect+to+remote+mysql+webserver+php&rlz=1C1AVSX_enGB447GB448&oq=connect+to+remote+mysql+webserver+php&aqs=chrome.0.69i57j69i62l3.19724j0&sourceid=chrome&ie=UTF-8#fp=5a2359cf96dc5f79&q=how+to+connect+to+remote+mysql+web+server+php
And help would be much appreciated.
If my question is not clear please let me know I'll try to explain more. or think of it as if you have to connect to a remote MySQL server how would you do , means what is the process and steps involved in that.
Thanks everyone.
Edit
I have created a database "dealt3_raj_test" on remote server. and when I type "examplewebserver.CO.UK/myphpscriptname" in my web browser.
It gives me error "An error occurred , You have reached the error page"
<?PHP
$user_name = "dealt3_raj";
$password = "5dN5nh&eMd(vCR$dzk";
$database = "dealt3_raj_test";
$server = "examplewebserver.CO.UK";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if($db_handle)
{
print "Connected";
}
else
{
print "Can not connect to server";
}
if ($db_found)
{
print "DataBase found";
}
else
{
print "DataBase not found";
}
?>
Adding onto #user4035's comment, after opening the connection, use JDBC in your Android/Java code to interact with the database.
That said, it is not good practice. Rather create a web service
Your application may experience latency/connectivity issues. This will impact performance.
Your MySQL server will have to be open to remote connections which is strongly advised against
If your Android App is intended for public usage, it means the database username and password of your MySQL server reside on everyone's phone using your app. Encrypted or not this makes your database server a "step less" secure
Well answered here on SO (JDBC vs Web Service for Android)
use this code to connect with data base
$username = "database user name";
$password = "DB password";
$hostname = "hostname";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("data base name",$dbhandle) or die("Could not select examples");