Connecting .php file to mySQL database - php

What I am trying to do is get mysql database to load up my .php file. I am using hostgator to run mysql database server. So far what i have for sql is a table with three columns.
int: id (primary key / A.I.)
varchar: name
text: message
I save the table and name it "test" and the database is called "testdb"
My php file (tutorialTest.php) looks like this:
<?php
$username = "nfoggia_nick";
$password = "imnick";
$database = "nfoggia_testdb";
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die("Unable to find database");
$name =$_GET["name"];
$message = $_GET["message"];
$query = "INSERT INTO test VALUES (' ', '$name', '$message')";
mysql_querry($query) or die(mysql_error("error"));
mysql_close();
?>
I added the .php file in my file directory on hostgator and now my problem is this:
I know that this code will do nothing, but when i type in
http://localhost/tutorialTest.php
the web browser says "browser cannot connect to local host" when it should just show a blank screen. Any help? What did i do wrong?
EDIT:
I moved my php file to the document root for my website and now when i run the
http://myWebsiteName/tutorialTest.php this shows up:
Fatal error: Call to undefined function mysql_querry() in /home2/nfoggia/public_html/tutorialTest.php on line 15

Before mentioning all the PHP errors, your URL is wrong.
localhost means your local computer, instead of your hosting environment, which you mentioned is hostgator.
Do you upload your PHP to hostgator server?
Is the MySQL database schema exist in hostgator environment?
Your URL should look like : http://www.hostgator.com/whatever/tutorialTest.php (or under your domain name). Anything but not http://localhost
First of all, remove the # to reveal the error.
For MySQL connection, the first parameter is a string, so you have to enclose it with single quotes, that is:
mysql_connect('localhost', $username, $password);
Last, you have multiple PHP errors :
mysql_querry($query)
You misspelled the function. Also, mysql_error() accepts link identifier as optional parameter instead of a string.
As a side note, stop using deprecated mysql_* functions. use MySQLi or PDO instead. Also, your code is subjected to SQL Injection attack, as you directly allow GET values to be inserted in your query.

Related

mssql_connect will not connect different DB on same SQL Server

$conn_161 = "192.168.0.161"; //local serwer adress
$user_161 = "ME";
$pass_161 = "what_is_the_password?";
$connect_161 = mssql_connect($conn_161,$user_161,$pass_161);
mssql_select_db ( 'DUKENUKEN3D' , $connect_161 );
//as requested - 1st DB connection and 1st query
$q_duke = "select * from DUKE /*DB1*/";
$r_duke = mssql_query($q_wartownik,$connect_161); //result
$connect_different_db = mssql_connect($conn_161,$user_161,$pass_161);
mssql_select_db ( 'BIGMAN' , $connect_different_db );
//second db and query
$q_bigman = "select * from BIGPEOPLE /*DB2*/";
$r_bigman = mssql_query($q_bigman,$connect_different_db ); //result
Error:
Warning: mssql_query() [function.mssql-query]: message: Invalid object name 'DUKE'.
Yes I know mssql_select_db is old, but I need to use it in this project. As you see I try to connect to same server but select 2 different DB at the same time, and run queries in the same php page (to connect data from 2 different DB). It seems it is not valiable? I even tried to run mssql_select_db just before doing the query to second DB, and then changing it back to first DB.
I understand this is limitation of the library (I will run all queries from LAST selected DB).
Is there a workaroud? Because all I got is to create page inside invisible iframe and there run php page with different db connection - far from good solution.
I would expect that this will work the same as it would if you were running this in a SQL environment directly (e.g. you can try it in SSMS or from the command line).
You can specify the database name when you reference the table in the query: e.g.
select * from db1.dbo.DUKE
This is standard SQL Server behaviour whenever you want to refer to an object which is outside the context of the current database.

What is servername

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.

mysql_connect with --local-infile parameter

Can not load data from uploaded (local) file since upgrade of mysql (current version: Server version: 5.5.44-0+deb8u1 (Debian)), files implied are:
dbconnection.php
<?php
$server = "localhost";
$user = "TheUser";
$pass = "ThePass";
$db_name = "DbName";
$link = mysql_connect($server, $user, $pass);
mysql_select_db($db_name);
mysql_set_charset('utf8', $link);
?>
send2db.php
<?php
include 'dbconnection.php';
mysql_select_db("DbName") or die(mysql_error());
$query = "LOAD DATA LOCAL INFILE '$file' INTO TABLE `T1` FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"' ";
mysql_query($query) or die(mysql_error());
?>
The error says:
ERROR 1148 (42000): The used command is not allowed with this MySQL version
Inside mysql:
SHOW GLOBAL VARIABLES LIKE 'local_infile';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile | ON |
+---------------+-------+
1 row in set (0.00 sec)
But if I access mysql this way, files can be loaded:
mysql --local-infile -p
So my question is, can I set this option in the dbconnection.php file, I've tried many ways already with no success, I've been reading posts about my.cnf configuration and some other stuffs but nothing works for me, any suggestion?
Thanks
UPDATE:
I've been away changing the code of the entire web to mysqli, ufff!!, well following the suggestions from the answers bellow I did the next code but no success, I still get the message: "The used command is not allowed with this MySQL version". Implied files are next:
acessdb.php
<?php
$link = new mysqli($server, $user, $pass, $dbname);
?>
send2db.php
<?php include 'acessdb.php';
$link->options(MYSQLI_OPT_LOCAL_INFILE, true);
mysqli_query($link, "LOAD DATA LOCAL INFILE 'upfiles/file.csv' INTO TABLE `T1` FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"'") or die(mysqli_error($link));
$link->options(MYSQLI_OPT_LOCAL_INFILE, false);
?>
Any suggestions?
Set the option in my.cnf (or mysql configuration file on your system):
local-infile=1
Restart MySQL service and this should fix the problem for you.
UPDATE
Another option to try with PHP
$conn = mysqli_init();
$conn->options(MYSQLI_OPT_LOCAL_INFILE, true);
Try that and see if that works. Options link mysqli options
Ok, finally I found the way, here is the working code:
file: connectdb.php
$link = mysqli_init();
mysqli_options($link, MYSQLI_OPT_LOCAL_INFILE, true);
mysqli_real_connect($link, $server, $user, $pass, $dbname);
file: send2db.php
mysqli_query($link, "LOAD DATA LOCAL INFILE 'upfiles/file.csv' INTO TABLE `T1` FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"'") or die(mysqli_error($link));
I hope it helps.
LOCAL INFILE is a mechanism by which the database server can request more or less any file from the database client (= the PHP server) If you can't fully trust your server and network this can be dangerous. Therefore LOCAL INFILE has to be allowed both on the server (as you did) as on the database client.
You are using the old outdated and not maintained mysql extension of PHP. That extension doesn't support setting the flag. You should switch to mysqli which has the MYSQLI_OPT_LOCAL_INFILE option to enable this mode.
<?php
$m = new mysqli(...);
$m->option(MYSQLI_OPT_LOCAL_INFILE, true);
$m->query("LOAD DATA LOCAL INFILE ....");
$m->option(MYSQLI_OPT_LOCAL_INFILE, false);
?>
Look through the comments above and create your checklist of sorts as follows:
Can I run "Load Data Local Infile" via mysql command line? If no, make sure this is enable by checking your global variable as discussed above.
Can I run a basic mysql script via my php code? If yes, then replace with the "Load Data Local Infile" script show about (same as what was used in step 1 via mysql).
Check database to determine if the load worked. If yes, "great job". If no, you need to turn on this Load feature via PHP. Look at the instructions above where you add $xxx->options(MYSQL_OPT_LOCAL_INFILE, true); this should be followed by a command to turn this off.
I struggled through this same issue for 5+hours. These are the summary steps that would have helped me troubleshoot and solve this issue faster. I would try these steps before messing with config files, which could lead to unintended consequences. Thanks for everyone's contributions.
As mysql_connect() is deprecated since PHP 5.5.0 (and will be deleted in the future), it's not impossible the issue comes from your web server (Apache ?) and not your SQL version.
Another thing that can cause this issue is the content of your file which eventually contains depreacted command (that's what the error message seems to tell you).

PHP mysql_query() No such file or directory found?

I have a MySQL database set up with Hostmysite.com. It connects just fine, and the idea of my php file is to take form values and input it into the SQL database. I am trying to create a feature that doesn't allow duplicate entries by comparing the email to see if it exists in the db...
The php code I think is right, but on die() it returns No such file or directory found??? That doesn't make sense.
<?php
//connection variables is excluded to get to the point of the problem
$con = mysqli_connect($host, $user, $pass, $db);
if (!$con){
die("Connection failed: " .my_sqli_connect_err());
}
$email = $_POST["email"];
$email = mysqli_real_escape_string($con, $email);
//see if email exists in database
$findEmail = "SELECT * FROM rsvpWedding WHERE email='" . $email."';";
$results = mysql_query($findEmail)or die(mysql_error());
?>
The:
$results
Returns a No such file or directory exists? I don't understand the SQL statement is correct and I believe my php code is also correct.
I don't know if this has anything to do with the problem, but this does mix:
mysqli_*();
with
mysql_*();
*****UPDATE ******
I believe I understand why I am getting that error of No such file or directory found. According to the web page : http://php.net/manual/en/function.mysql-query.php When sql_query() is executed it tries to connect to a link that was executed on
sql_connect()
not
sqli_connect()
If it can't find one it will try and attempt a connection with sql_connect() with no arguments, if that fails it will generate an error.. From researching online I see that No such file or directory is normally associated with sql_connect() errors.
So i suppose my question to this post sort of changes to how do I create a resource using the sqli_* syntax. I tried
$results = mysqli_query($con, $findEmail) or die(mysql_error());
but that still doesn't work, it just skips that entire code block... doesn't even produce an error.
This might be caused by mysql.sock file path is not configured properly for php.
So please make sure you installed the mysql db engine, and find where the mysql.sock file is located.
Then you need to configure in php.ini file:
Find these lines, configure like the following:
mysql.default_socket = /path/mysql.sock
mysqli.default_socket = /path/mysql.sock
pdo_mysql.default_socket = /path/mysql.sock
Restart apache server and mysql service
You can't mix mysqli_* with mysql_*. It's safer to do it the mysqli way anyways:
//see if email exists in database
$stmt = $con->prepare('SELECT * FROM rsvpWedding WHERE email=?'); // question mark is a placeholder
$stmt->bind_param('s', $email); // 's' means it's a string
$stmt->execute();
$stmt->bind_result($result); // assign the result to your $result var
$stmt->fetch();
See the docs here:
http://php.net/manual/en/mysqli.prepare.php
your not printing anything thats why!
try using mysqli_num_rows($result)
echo that one
if its greater than zero then it exist
if none then youre all good

php connect to mysql db in cloud 9?

I usually connect php to mysql with localhost in my PC..
now i'm trying to put my project in cloud https://c9.io ,but i can't connect to mysql. i already have mysql database in cloud and put my project in same place...
mysql_connect("/lib/mysql/socket/mysql.sock","myUser","") or die(mysql_error());
i use script above to connect but i get Unknown MySQL server host '/lib/mysql/socket/mysql.sock' (1)
what shoul i do ?
Okay, so none of the above answers had worked for me, but fortunately I was able to setup a database and get it up and running my own way and I can now make queries and run them successfully, so I will share my method with you in hopes that anyone else scouring the internet can stumble across this and not have to go through the same head scratching that I did.
If you want the quick rundown, just scroll to Step 3 and read on from there. If you're a complete beginner, keep reading as I'll walk you through it in detail.
Couple things to mention:
You will have to setup a database via a Terminal in Cloud 9. I had no experience prior doing it in a Terminal before, but it's very simple to learn.
You can not use mysql functions, you have to use mysqli, since mysql functions are deprecated and Cloud 9 will not run them.
Step 1: Setup MySQL on Cloud 9 (in Terminal)
In your project, open up a New Terminal (click the plus-sign tab above the text editor space, select "New Terminal"). In the terminal, type mysql-ctl start and hit Enter. MySQL will start up in the back, but you won't get any response back in the terminal.
Next, type mysql-ctl cli and hit Enter. You should see some text that starts off as Welcome to the MySQL monitor.... Congrats, you've setup MySQL on your Cloud 9 project.
Step 2: Create a test database (in Terminal)
You can actually go ahead and create your official database if you like, but for this sake I'll just make a database that holds a table that holds an ID and a username. So here's the steps to setting up a database and a table. If you've used MySQL and databases before, then this should be cake, but I'll explain it in detail for those who might not fully understand MySQL .
Type SHOW DATABASES; and hit Enter. This will show a list of current databases within your project. You can enter this any time you want to see a list of your databases on the current project.
Type in CREATE DATABASE sample_db; and hit Enter. You should get a Query OK, 1 Row affected. which means the query was successful. You can name the database whatever you like, but for this little walk-through, I named it sample_db.
Type in USE sample_db; and hit Enter. This selects sample_db from the list of databases.
Type in CREATE TABLE users (id INT(11), username VARCHAR(20));, and hit Enter. This creates a table named users with two columns: id and username. The number in parentheses represents the character limit the column will store in the database. In this case for example, username won't hold a string longer than 20 characters in length.
Type in INSERT INTO users (id, username) VALUES (1, "graham12");, and hit Enter. This will add the id of 1 and a username graham12 in the table. Since the id column is an INT, we do not put quotes around it.
Type in SELECT * FROM users;, and hit Enter. This will show everything that is in the users table. The only entry in there should be what we inserted from the last step we just did.
Step 3: Get the credentials you'll need to connect to the database from PHP. (in Terminal)
Now we have some data in our table that we can test our mysqli connection with. But first, we have to get the credentials we will need to connect to the database in PHP. In Cloud 9, we will need 5 credentials to connect:
Host name
Username
Password
Database name
Port #
Username, password, database name, and port #, are practically already known to you by now. I'll explain:
Host name - Type in SHOW VARIABLES WHERE Variable_name = 'hostname';, and hit Enter. You'll get a table that has 2 columns: Variable_name and Value. In the Value column you should see something like yourUsername-yourProjectName-XXXXXXX, where the X's are a 7 digit number. Write this number down or save it some where. This is your host name. (If you're getting the quick rundown on this walkthrough, just start a new terminal and start up your mysql and select the database you want to use, then type in SHOW VARIABLES WHERE Variable_name = 'hostname';. Re-read this step from the beginning if you're confused.)
Username - Your username that you use to log in to Cloud 9.
Password - There is NO password for your database in Cloud 9.
Database name - This would be sample_db or whatever you named your database;
Port # - is 3306. In Cloud 9, all of your projects are wired to 3306. This is a universal constant of Cloud 9. It will not be anything else. Write this as you would an integer, not as a string. mysqli_connect() will interpret the port # as a long data type.
Last Step: Connect to the database with PHP! (using PHP)
Open up a PHP file and name it whatever you like.
I'll pretend that my host name is graham12-sample_db-1234567 for this example and that this is what my data looks like:
Host name: "graham12-sample_db-1234567"
Username: "graham12"
Password: ""
Database name: "sample_db"
Port #: 3306
So in PHP, insert your credentials accordingly:
<?php
//Connect to the database
$host = "grahamsutt12-sample_db-1234567"; //See Step 3 about how to get host name
$user = "grahamsutt12"; //Your Cloud 9 username
$pass = ""; //Remember, there is NO password!
$db = "sample_db"; //Your database name you want to connect to
$port = 3306; //The port #. It is always 3306
$connection = mysqli_connect($host, $user, $pass, $db, $port)or die(mysql_error());
//And now to perform a simple query to make sure it's working
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
echo "The ID is: " . $row['id'] . " and the Username is: " . $row['username'];
}
?>
If you get a result and no error then you have successfully setup a database and formed a connection to it with PHP in Cloud 9. You should now be able to make all the queries you can normally make.
Note: I demonstrated the last part without using parameterized queries for the sake of being simple. You should always use parameterized queries when working with real web applications. You can get more info on that here: MySQLi Prepared Statements.
For starters, the mysql_* functions are deprecated so you shouldn't be using them. Look at PDO or mysqli instead. Next, you'll want to try this per the example docs:
$link = mysql_connect('localhost:/lib/mysql/socket/mysql.sock', 'myUser', '') or die(mysql_error());
To find the ip running you project, create a test file with the code below, run it and put the result as host.
<?php
$ip = getenv("REMOTE_ADDR") ;
Echo "Your IP is " . $ip;
?>
You are using Cloud9 so it's a little different to use. To connect to MySQL you have to first create the MySQL server in C9. Type this in C9's command line:
mysql-ctl start
C9 will create your mysql server.
MySQL 5.1 database added. Please make note of these credentials:
Root User: <username>
Database Name: c9
Next to find your IP address type:
echo $IP
Now use this code with your username, the ip address, no password and the 'c9' database to access MySQL:
mysql_connect("<$IP>","<username>","") or die(mysql_error());
mysql_select_db("c9")
Hope this helps
The documentation show how start, stop, and run the mysql environment.
Start the MySQL shell mysql-ctl start then in yor file.php:
$ip = getenv("REMOTE_ADDR");
$port = "3306";
$user = "YorUsername";
$DB = "c9";
$conn = mysql_connect('$ip', '$user', '', '$db', '$port')or die(mysql_error());
mysql_select_db('$db','$conn')or die(mysql_error());
mysql_query("select * from YourTableName",'$conn')or die(mysql_error());
The line getenv("REMOTE_ADDR") return the same local IP as the application you run on Cloud9.

Categories