Pretty simple stuff, I know, but am getting an error
<?php
session_start();
$dbhost = "###"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "###"; // the name of the database that you are going to use for this project
$dbuser = "###"; // the username that you created, or were given, to access your database
$dbpass = "###"; // the password that you created, or were given, to access your database
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
mysql_select_db("###", $con);
$safe_email = mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO register (email) VALUES ('{$safe_email}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
$con is not defined anywhere in your code, before you use it in the query call. You should have:
$con = mysql_connect(...) or die(mysql_error());
Beyond that, your code is WIDE open to SQL injection attacks. You should have:
$safe_email = mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO register (email) VALUES ('{$safe_email}')";
Assuming the following:
You don't have a lot of experience with PHP
The information that has been provided to you is correct
This is an example script and you know the values that need to be substituted for $dbname, $dbhost, $dbuser and $dbpass
Please try the following and report back if you get any output at all to screen:
<?php
session_start();
print "Connecting and inserting email: ".$_POST['email']."...";
$dbhost = "###"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "###"; // the name of the database that you are going to use for this project
$dbuser = "###"; // the username that you created, or were given, to access your database
$dbpass = "###"; // the password that you created, or were given, to access your database
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
$safe_email = mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO register (email) VALUES ('{$safe_email}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
print "success! Inserted email with row id: ".mysql_insert_id();
mysql_close($con)
?>
this may just be me but you should but strings on a single line or use the concatenation (.) for the strings
$sql="INSERT INTO register (email) VALUES ('$_POST[email]')";
Other than that you should clean the information before adding it into the database otherwise your asking for sql injection attacks.
now to the actual problem. your using a variable that is undefined called conn. i am assuming your referencing the connection made, but you never set that variable to the connection like so
$conn = mysql_connect($dblocal,$dbuser,$dbpass) or die(xxx);
Related
Hello anyone who can help (or having the same issue).
I have a form on my website I need to store the data in a database.
I have no problems when using any other database service but when using an Amazon RDS Database I have no luck.
This php file is used to send the data to the database.
<?php
$dbhost = "xxxx.xxxx.ap-southeast-2.rds.amazonaws.com";
$dbuser = "username";
$dbpass = "pasword";
$userid = $_GET['UniqueID'];
$username = $_GET['name'];
$useremail = $_GET['email'];
$userphone = $_GET['phone'];
$userref = $_GET['refid'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "INSERT INTO landing_post (`useid`, `name`, `email`, `phone`, `refid`) VALUES ('$userid', '$username', '$useremail', '$userphone', '$userref')";
mysql_select_db('bunker');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
After the form is submitted to the original post action, it opens the below url.
https://example.com.au/test/post.php?&UniqueID=10020&name=burger&email=test%40mvmedia.com&phone=1800+000+000&refid=28383
The $_GET functions fill out the data using the variables in the url.
When running the php from a cpanel based server I get this error.
Could not connect: Can't connect to MySQL server on 'xxxxx.xxxxxxx.ap-southeast-2.rds.amazonaws.com' (111)
When running the php from a AWS EC2 instance I don't even get a error readout.
Any assistance or insight would be greatly appreciated.
Cheers,
Andy
Shout out to JeanPaul98 who put me on the right path. After trial and many errors, i found the below code solved the issue.
<?php
$userid = $_GET['UniqueID'];
$username = $_GET['name'];
$useremail = $_GET['email'];
$userphone = $_GET['phone'];
$userref = $_GET['refid'];
$link = mysqli_connect('xxxxx.xxxxxx.ap-southeast-2.rds.amazonaws.com', 'User', 'password','database');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Check if server is alive
if (mysqli_ping($link))
{
echo "Connection is ok!";
}
else
{
echo "Error: ". mysqli_error($link);
}
mysqli_query($link,"INSERT INTO table (`useid`, `name`, `email`, `phone`, `refid`) VALUES ('$userid', '$username', '$useremail', '$userphone', '$userref')")
or die(mysqli_error($link));
echo "Entered data successfully\n";
mysqli_close($link);
?>
The main change was I stopped using mysql and rather used mysqli. There are also some structural changes to make the code to work with mysqli. For others having a similar issues here are a few things to check.
You have opened a inbound port for the IP in the security group of the RDS Database.
The Database is publicly accessible.
That your php version has PDO_MYSQL installed, or compatible driver (more details here
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_PHP.rds.html)
I am creating a form that will take a person's name and email and see if the email exists in the database already but I can't get the database to be selected. The mysql_error() won't display the error either. Is there something wrong with my code for selecting the database? All it shows is the hardcoded text "Could not select database because" then nothing. I replaced all the variables associated with the database with random fillers so as not to give away my info but everything I have is correct regarding that.
$host = "host";
$user = "user";
$password = "pass";
$database = "db";
$port = xxxx;
$table = "table";
// Create connection
$conn = mysqli_connect($host, $user, $password, $database, $port);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection Successful";
mysqli_select_db($database)
or die("Could not select database because".mysqli_error());
// check if the username is taken
$check = "select email from $table where email = '".$_POST['email']."';";
$qry = mysqli_query($check)
or die ("Could not match data because ".mysqli_error());
$num_rows = mysqli_num_rows($qry);
if ($num_rows != 0) {
echo "Sorry, there the username $username is already taken.";
}
Don't call mysqli_select_db. You've already selected your database with the fourth parameter to mysqli_connect.
You only need to call mysqli_select_db if you want to access a different database after the connection has been established.
Also, Raptor is correct that if you call procedural mysqli_error() you must pass it a connection handle.
For Procedural style mysqli_error(), you must supply the MySQLi DB link as parameter:
mysqli_select_db($database)
or die("Could not select database because" . mysqli_error($conn));
But it's useless to call mysqli_select_db() as you already specified the DB schema in mysqli_connect().
Additionally, your SQL is vulnerable to SQL Injection attack. Always escape the parameter before putting into SQL statement, or use prepared statements.
try this code
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>
I have a problem with my code. I'm trying to add new post to the table events. I'm confused because I have used this code in other place on the same website (but it was using mysqli_query to register new user). mysqql_error returns "No database selected"
This is the code:
<?php
$add_title = $_POST['add_title'];
$add_happen = $_POST['add_happen'];
$add_created = date('Y-m-d');
$add_content = $_POST['add_content'];
$add_author = $_POST['add_author'];
//connect to
//localhost
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_dbname = "zhp2";
$db_con = mysql_connect($db_host, $db_username, $db_password, $db_dbname);
$query = "
INSERT INTO events ( title, happen, created, content, author )
VALUES ( '$add_title', '$add_happen', '$add_created', '$add_content', '$add_author') )
";
$retval = mysql_query($query, $db_con);
if(! $retval ){
die('Could not enter data: ' . mysql_error());
}
else{
echo "Entered data successfully\n";
}
mysql_close($db_con);
//header('Location: ../../index.php?link=events');?>
I've tried to fix it using trial and error method playing with different combinations both mysql_query and mysqli_query
You are confusing mysql_connect and mysqli_connect functions in the way you pass those parameters. In your example:
$db_con = mysql_connect($db_host, $db_username, $db_password, $db_dbname);
you are passing a fourth parameter which is the database name but that wont work as you should only pass the three first (host,username,password) and then call mysql_select_db():
$db_con = mysql_connect($db_host, $db_username, $db_password);
mysql_select_db( $db_dbname, $db_con );
In mysqli which is the BETTER way of doing it since mysql_ functions are very vulnerable and being deprecated from php you could pass four elements like here:
$db_con = mysqli_connect($db_host,$db_username, $db_password, $db_dbname) or die("Error " . mysqli_error($link));
which is close to what you are trying to do, but in a correct mysqli_ way.
Well then, you need to select the database! ;) The fourth parameter of mysql_connect() is not the database name. You need to do this separate of connecting to the MySQL server.
Using mysql_select_db() function:
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_dbname = "zhp2";
$db_con = mysql_connect($db_host, $db_username, $db_password );
mysql_select_db( $db_dbname, $db_con );
And of course all the obligatory warnings about SQL injection, sanitizing your data, deprecation of mysql_* functions.
You need to select which database to connect to using the mysql_select_db function:
// make $db_dbname the current db
$db_selected = mysql_select_db($db_dbname, $db_con);
if (!$db_selected) {
die ("Can't use $db_dbname : " . mysql_error());
}
See the PHP manual for more info: http://php.net/manual/en/function.mysql-select-db.php
Based on suggestions and a better understanding of what I need I have changed my question:
My site is protected with .htaccess. Im trying to get the current user and a few other variables and save them to a MySQL database. Everything works except the current user part.
Heres my code:
<?php
$_SERVER["PHP_AUTH_USER"] = "rep";
$hostname = "hostname";
$username = "username";
$dbname = "dbname";
$password = "password";
$usertable = "usageStats";
$yourfield = "your_field";
$con = mysql_connect($hostname, $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
$sql="INSERT INTO usageStats (Bid, PRid, User)
VALUES
('$_POST[BID]','$_POST[branding]','$_POST[rep]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
I know that the below are both wrong. How should the current user be passed instead of $_POST[rep]?
Wong:
$_SERVER["PHP_AUTH_USER"] = "rep";
and
'$_POST[rep]'
If you are using Basic Authentication you do not need to send the username explicitly. The browser will send it and you can access it using the PHP_AUTH_USER server variable:
$_SERVER['PHP_AUTH_USER']
Also checkout the HTTP Authentication article in the documentation.
I am a PHP newbie and have been trying for sometime now to connect to MySQL database using PHP so I can insert data into a table I have created but I am unable to do this.
I suspect the problem is coming from my PHP .ini file,but that's just me.
Would be grateful if anyone can help me configure my PHP .ini file so I can connect to MySQL and insert data into my table. Here is my PHP script in case you are wondering.
Any help will be gratefully appreciated.
<?php
$host ="localhost";
$username = "username";
$password = "password";
$database = "database1";
$table ="users";
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect:'.mysql_error());
}
mysql_select_db("database1",$con);
$mysql = "INSERT INTO $table(name,email,password)
VALUES('$_POST[name]','$_POST[email]','$_POST[password]";
if(mysql_query($mysql)) die(mysql_error());
echo"Data inserted";
mysql_close();
?>
I revised some of your code this should work. You had a bunch of little errors. I suggest you read a couple tutorials on just connecting and the syntax of php.
Here is some really basic examples of connecting to a database:
http://www.w3schools.com/php/php_mysql_connect.asp
Also once you get the hang of it here is a really good tutorial to teach you the OOP way of creating a class for a database:
http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/
As far as I see this is not an ini issue. I hope this helps.
<?php
//Set your variables
$host = "127.0.0.1";
$username = "username";
$password = "password";
$database = "database1";
$table = "users";
//Make your connection to database
$con = mysql_connect($host,$username,$password);
//Check your connection
if (!$con) {
die("Could not connect: " . mysql_error());
}
//Select your database
$db_selected = mysql_select_db($database, $con);
//Check to make sure the database is there
if (!$db_selected) {
die ('Can\'t use the db : ' . mysql_error());
}
//Run query
$result = mysql_query("INSERT INTO $table(name,email,password) VALUES('$_POST[name]','$_POST[email]','$_POST[password]'");
//Check Query
if (!$result) {
die("lid query: " . mysql_error());
}
echo "Data inserted";
mysql_close($con);
?>
First, why do you have <br/> in your PHP statements? Remove all those.
Also, you have to use PDO or mysqli_ instead of the mysql_ library, mysql_ is deprecated.