Problems connecting to mysql database in xampp - php

I have this code that is supposed to connect my website to a database that i created in xampp.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'anyons');
define('DB_USER','root');
define('DB_PASSWORD','');
$field1_name=$_POST['email'];
$field2_name=$_POST['pass'];
$field3_name=$_POST['name'];
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD)or die("Failed to connect to
MySQL: " . mysql_error());
#mysqli_select_db(DB_NAME,$con) or die( "Unable to select database");
$query = "INSERT INTO login VALUES('$field1_name','$field2_name',
'$field3_name')";mysql_query($query);mysql_close();
?>
I get an error Unable to select database, meaning there's a broken connection somewhere. i have been trying to figure it out but i really can't. Help will be highly appreciated.

You have combined the connection used by mysqli and mysql
replace your codes by following codes
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'anyons');
define('DB_USER','root');
define('DB_PASSWORD','');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
// connection checking
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// filtering values
extract($_POST); // collected all post values
$email = mysqli_real_escape_string($con, $email);
$pass = mysqli_real_escape_string($con, $pass);
$name = mysqli_real_escape_string($con, $name);
$query = "INSERT INTO login (email, pass, name) VALUES ('{$email}','{$pass}','{$name}')";
if(!mysqli_query($con, $query)){
die('Error: ' . mysqli_error($con));
}else{
echo 'records added!';
}
mysqli_close($con);
?>

Related

Fatal error: Uncaught mysqli_sql_exception: Unknown database 'test_db'. I keep getting this error even though I programatically created the database

Here is the code
<?php
$servername = "localhost";
$usrname = "root";
$pwd = "";
$db = "test_db";
// connect to the database
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
if (!$conn){
die('connection failed' . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS test_db";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
?>
I am not sure what is going on as I am sure i made no errors while typing. As it keeps showing me that there is an unknown database despite the fact i made a CREATE DATABASE statement.
I do not know if there is something else i need to do but by all measures the code should work.
It is supposed to echo the "Database created successfully" or the error message.
`<?php
$servername = "localhost";
$usrname = "root";
$pwd = "";
//$db = "test_db";
// connect to the database
$conn= mysqli_connect($servername, $usrname, $pwd);
if (!$conn){
die('connection failed' . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS test_db";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
?>`
Your code is fine, You just have to remove $db from mysqli_connect().
Because you are requesting to connect "test_db" to this database which already not exists.
<?php
// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Make my_db the current database
$db_selected = mysql_select_db('my_db', $link);
if (!$db_selected) {
// If we couldn't, then it either doesn't exist, or we can't see it.
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
mysql_close($link);
?>
Reference
How do I create a database if it doesn't exist, using PHP?
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
You are trying to connect to a database that did not initially exist, so you get a fatal error.
Try creating new database using try catch blocks
try{
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
}cath(Exception $e){
//your code
}

Unable to post form data to RDS MySQL Database

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)

linking mit inventor2 to sql database error 1109

I have been trying to connect my hosted sql database with mitinventor2 in a registeration form and I am getting an error that says something about
URL. error 1109
This is my php code :
<?php
DEFINE ('DBUSER', '******');
DEFINE ('DBPW', '*****');
DEFINE ('DBHOST', 's******');
DEFINE ('DBNAME', '*******');
$dbc = mysqli_connect(DBHOST,DBUSER,DBPW);
if (!$dbc) {
die("Database connection failed: " . mysqli_error($dbc));
exit();
}
$dbs = mysqli_select_db($dbc, DBNAME);
if (!$dbs) {
die("Database selection failed: " . mysqli_error($dbc));
exit();
}
$clientusername = mysqli_real_escape_string($dbc, $_GET['clientusername']);
$clientemail = mysqli_real_escape_string($dbc,$_GET['clientemail']);
$clientpno = mysqli_real_escape_string($dbc,$_GET['clientpno']);
$clientpass = mysqli_real_escape_string($dbc,$_GET['clientpass']);
$query = "INSERT INTO ssudb(clientusername, clientemail, clientpno, clientpass) VALUES ('$clientusername', '$clientemail', '$clientpno', '$clientpass')";
$result = mysqli_query($dbc, $query) or trigger_error("Query MySQL Error: " . mysqli_error($dbc));
mysqli_close($dbc);
?>
I am sure about the database info yet I hide them for security reasons. My database is well structured with phpmyadmin.
The link to the php file is right with no errors, and here is my mit inventor block:
I hope I didn't validate any rule.
Thanks in advance!
note:
when open phpmyadmin somtimes i see the table is having new attributes with no values in it but the increment ID.
$clientlocation is missing in the VALUES

Can't access the Database (MAMP)

When I press my submit button, I get an error saying :
ErrorTable 'form2.demo' doesn't exist
form2 is my database name which is created in phpmyadmin.
I am a new MAC user.
Below is my php code.
define('DB_NAME','form2');
define('DB_USER','root');
define('DB_PASSWORD','root');
define('DB_HOST','localhost:8888');
My ports are :
Apache : 8888
Msql : 8889
Full code is as below:
<?php
define('DB_NAME','form2');
define('DB_USER','root');
define('DB_PASSWORD','root');
define('DB_HOST','localhost:8889');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link){
die('Could not connect :' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can\'t use' . DB_NAME . ':' . mysql_error());
}
$value = $_POST['input1'];
$sql = "INSERT INTO demo (input1) VALUES ('$value')";
if(!mysql_query($sql)){
die('Error' . mysql_error());
}
mysql_close();
?>
Your problem have nothing to do with Mac. You have to show us more code. How the code in your form looks like? How you are sending stuff to database?
Let's assume that everything in code is set up properly. The main thing you have to check is if you actually have demo table in your database. Go to phpmyadmin and check it, if there is no table create it. You can use phpmyadmin to do that or do it via SQL query like that one
CREATE TABLE IF NOT EXISTS `form2`.`demo` ( `id` INT NOT NULL AUTO_INCREMENT , PRIMARY KEY (`id`));
Of course code above will create table with only ID column so you have to adjust it to your needs
DEFINE('DB_USERNAME', 'root');
DEFINE('DB_PASSWORD', '');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_DATABASE', 'customer');
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_error()) {
die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
}
echo 'Connected successfully.';
$mysqli->close();
Try the msqli library instead

Why is my data not being submitted into my database?

I need to connect an html form to my sql database and I'm starting out with a simple form so I can understand how it works. I can't figure out what I am doing wrong. I have the form created, the php script, and the database created. Whenever I submit the form it takes me to a blank page and nothing has been added to my database. I've written error messages if the connections fail but I'm not seeing those either. I'm not as advanced in programming can someone please help me?
index1.html
<html>
<body>
<form action="info.php" method="post">
<p>Username:<input type="text" name="username" /></p>
<p>Email:<input type="text" name="email" /></p>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
info.php
<?php
define('DB_NAME' , 'users' );
define('DB_USER' , 'root');
define('DB_PASSWORD' , '');
define('DB_HOST' , 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
//connection to host
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//error if not connected to host
$db_selected = mysql_select_db(DB_NAME, $link);
//select the database
if(!$db_selected){
die('Can\'t use ' . DB_NAME . ':' . mysql_error());
}
echo 'Connected successfully';
$value = $_POST['username'];
$value2 = $_POST['email'];
$sql = "INSERT INTO guests (username, email) VALUES ('$value', '$value2')";
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
//error check to see if connected to tables
mysql_close();
//close connection
?>
As I stated in comments; your mysql_ code checks out, so chances are you need to use either mysqli_ or PDO, since mysql_ functions may very well not be available for you to use.
If the following mysqli_ rewrite does not work for you, then the problem goes deeper and would be out of scope of the question.
Using error reporting will/should confirm that. Consult "Footnotes" on how to use it in your PHP file(s).
<?php
define('DB_NAME' , 'users' );
define('DB_USER' , 'root');
define('DB_PASSWORD' , '');
define('DB_HOST' , 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//connection to host
if (!$link) {
die('Could not connect: ' . mysqli_error($link));
}
echo 'Connected successfully';
$value = mysqli_real_escape_string($link,$_POST['username']);
$value2 = mysqli_real_escape_string($link,$_POST['email']);
$sql = "INSERT INTO guests (username, email) VALUES ('$value', '$value2')";
if(!mysqli_query($link, $sql)){
die('Error: ' . mysqli_error($link));
}
//error check to see if connected to tables
else{
echo "Data entered";
}
mysqli_close($link);
//close connection
?>
References:
MySQLi: http://php.net/manual/en/book.mysqli.php
PDO: http://php.net/manual/en/ref.pdo-mysql.php
Error reporting: http://php.net/manual/en/function.error-reporting.php
Footnotes:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Make sure your server is running and properly configured for PHP/MySQL/Apache.
Make sure your columns are indeed VARCHAR and long enough to accommodate the data.
Try this query:
INSERT INTO guest set username=$value1,email=$value2
hope it will solve .
Try this, it should work for you.
$sql = "INSERT INTO guests (username, email) VALUES (".$value.", ".$value2.")";

Categories