Failed to query daabaseNo database selected - php

i am getting error no database is selected can anybody correct the code.
I am trying to learn php and mysql. So i tried making a database using
phpmyadmin and connect it with my php. Here is a simple example where I try to see if the database is working.
<?php
//Get values passe from form in donateform.html.
$link;
$Name = $_POST['Name'];
$Mobile = $_POST['Mobile'];
$Email = $_POST['Email'];
$Donating =isset($_POST['Donating']);
$Address = isset($_POST['Address']);
//To prevent mysql injection
$Name = stripcslashes($Name);
$Mobile = stripcslashes($Mobile);
$Email = stripcslashes($Email);
$Donating = stripcslashes($Donating);
$Address = stripcslashes($Address);
//connect to the server and select database.
$link=mysqli_connect("localhost", "gooddeeds", "");
mysqli_select_db($link,"donaters");
$Name = mysqli_real_escape_string($link,$Name);
$Mobile = mysqli_real_escape_string($link,$Mobile);
$Email = mysqli_real_escape_string($link,$Email);
$Donating = mysqli_real_escape_string($link,$Donating);
$Address = mysqli_real_escape_string($link,$Address);
//Query the database for user
$result =mysqli_query($link,"INSERT INTO donaters (Name, Mobile, Email, Donating, Address) VALUES ('$Name', '$Mobile', '$Email', '$Donating', '$Address')")
or die("Failed to query daabase".mysqli_error($link));
if(mysqli_query($result)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. ".mysqli_error($link);
}
?>
and i get
Database query failed::: No database selected
which means this part of code
//connect to the server and select database.
$link=mysqli_connect("localhost", "gooddeeds", "");
mysqli_select_db($link,"donaters");
is not working (i put a different number of these ":" in each if. Any help would be appreciated! Thank you!

You can try with following as databasename.tablename (gooddeeds.donaters)
INSERT INTO gooddeeds.donaters (Name, Mobile, Email, Donating, Address) VALUES ('$Name', '$Mobile', '$Email', '$Donating', '$Address')

This is by the first example in the php documentation. Try the the conditional to check connection.
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}

Related

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)

Is my hosting company messing me up here: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)?

I use the hosting company aPlus.net, and I can't seem to get past a connection error I'm getting when trying to process some php to write database content to a webpage, and I am curious as to if this is because my database appears to not be on the same server as the entire rest of my hosting account, and if there is a way to resolve this in my code? This is my first attempt at writing PHP, and it would be good to know if my code is wrong, or if my hosting company is messing me up. (and either way, how to fix it)
Here's the code that's failing to pull from the database:
{
$con = mysql_connect("localhost","2p5dq9vxmy240651","MY_PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("felineasthma_2p5dq9vxmy240651", $con);
$users_name = $_POST['name'];
$users_comment = $_POST['requests'];
$users_name = mysql_real_escape_string($users_name);
$users_comment = mysql_real_escape_string($users_comment);
$inputid = $_GET['id'];
$query = "
INSERT INTO `felineasthma_2p5dq9vxmy240651`.`submissions` (`id`,
`name`, `requests`, `inputid`) VALUES (NULL,
'$users_name', '$users_comment', '$inputid');";
mysql_query($query);
echo "<h2>Your request has been processed, reload page.</h2>";
mysql_close($con);
}
and here's some screen captures from inside my hosting account (links because I don't have enough posts here yet to upload images, sorry):
felineasthma_2p5dq9vxmy240651 doesn't appear in my hosting account
yet it clearly exists in MySQL Manager, but on a different server
I was even more confused while making the user for this database, as the control panel didn't allow me to make a username, it just randomly assigned one. Help? Advice?
I found a more modern tutorial to learn PHP with, and now everything works, I just need to add security measures now. Here's the working code snippets, if anyone ever comes here asking the same questions.
here's the form action that places the entries into the database:
<?php
$servername = "sql5c40n.carrierzone.com";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
$users_name = $_POST['name'];
$users_request = $_POST['requests'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO submissions (name, requests)
VALUES ('$users_name', '$users_request')";
if (mysqli_query($conn, $sql)) {
header("Location: clv.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
here's the include that puts the database entries onto the page:
<?php
$servername = "sql5c40n.carrierzone.com";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, requests, name FROM submissions";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "" . $row["requests"]. " - by " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

error connecting to mysql database through crazy domains

newbie here! I have made a simple form on my site
warning message
I can't seem to figure out what i've done wrong.
This is the php code:
<?php
$servername = "localhost";
$dbusername = "charityh_root";
$dbpassword = "";
$dbname = "charitydb";
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$state = $_POST['state'];
$email = $_POST['email'];
//$password = $_POST['password'];
//$sha1password = sha1($password);
//Create connection
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
//Check connection
If ($conn -> connect_error) {
die("Connection failed:" . $conn -> connect_error);
}
Line 17 is $conn = newmysqli($...
any idea guys?
Mysql database wizard
Connecting to database now although when i enter in the details (first name, last name, state and email) i get the message first name can not be left blank...
if (empty($fname)) {
Echo "First name can not be blank. Please press back and correct the
issue";
die();
}
if (empty($lname)) {
Echo "Last name can not be blank. Please press back and correct the issue!";
die();
}
if (empty($state)) {
Echo "State can not be blank. Please press back and correct the issue!";
die();
}
if (empty($email)) {
Echo "Email can not be blank. Please press back and correct the issue!";
die();
}
$sql = "INSERT INTO charityh_database (First_Name, Last_Name, State, Email)
VALUES ('$fname', '$lname', '$state', '$email')";
if ($conn->query($sql) === TRUE) {
echo "Thank You";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close ();
?>
$dbusername = "charityh_root";
$dbpassword = "";
Seems like you are using the same username and password as you were using in your local server. You need to replace them with the username and password crazy domain's.
Since as far as I know Crazy Domain deosn't allows a blank password.
EDIT
Besides that I can see the database name you have mentioned in the codes is "charitydb"; which should be something like charityh_database.(By looking at your recent edit this is a wild guess)
The error indicates your username and password do not have access to the database.
Have you checked the database will allow you to connect, using the username and password?

PHP not inserting data into MySQLi database

My php has connected to my database however when I try to insert the data, I get the query is not okay response.
if(isset($_POST['Register'])) {
session_start();
$FName = $_POST['First_Name'];
$LName = $_POST['Last_Name'];
$Email = $_POST['Email'];
$PW = $_POST['Password'];
$query = "INSERT INTO user (Fname, Lname, Email, Password) VALUES('{$FName}', '{$LName}', '{$Email}', '{$PW}')";
$result=mysqli_query($con, $query);
if($result){
echo "Query is successfully executed";
}else{
echo "Query is not ok";
}
}
?>
This is my connection code but it tells me that I am successfully connected.
$con = mysqli_connect("localhost", "*******","*******");
mysqli_select_db('batman',$con);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
?>
The database matches all of the inputs and the table name is user so I cannot figure out why it will not insert into the database.
Use error_reporting(E_ALL); at startup
&
use simple $Fname instead {$Fname}
Also check input type="submit" and name=" is name Register"
Maybe you could try to make a class with the script, because I think the problem is the connection that you use , because you are not calling for the connection function when you execute the query.
Regards!

PHP posting <a href> causes error on insert

I am writing a php file that takes values from a form and posts them to a mysql database. One of the table fields is a button link to a video that will play when clicked. It works great if I go into the database and manually add the link. However my PHP insert causes an error. Please have a look at this code:
$fileName = "video_".$id.".html";
$link = "<button class=\"count\">Watch Video</button>";
$con=mysqli_connect("localhost","videomanager","password","my_database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO video_list (date, title, description, link) VALUES('$_POST[date]','".mysqli_real_escape_string($_POST['sermon'])."','".mysqli_real_escape_string($_POST['description'])."','$link' )";
if (!mysqli_query($sql,$con))
{
die('Error: ' . mysqli_error());
}
echo "This video has been successfully added to the video database.";
mysqli_close($con);
If I look at $link by doing something like: echo $link; die(); it produces a page with the button and the code in the button looks good. Is it how I am trying to insert it? Thanks for your help!
you have a lot of errors
<?php
$fileName = "video_".$id.".html";
$link = "<button class=\"count\">Watch Video</button>";
$con = mysqli_connect("localhost","videomanager","password","my_database");
// Check connection
if ( mysqli_connect_errno() )
die('Failed to connect to MySQL: ' . mysqli_connect_error() );
// Check param is set
if( !isset($_POST['date'], $_POST['sermon'], $_POST['description']) )
die('Param Error');
// SQL Request
$sql = sprintf("INSERT INTO video_list (date, title, description, link) VALUES('%s','%s','%s','%s')",
mysqli_real_escape_string($con, $_POST['date']),
mysqli_real_escape_string($con, $_POST['sermon']),
mysqli_real_escape_string($con, $_POST['description']),
mysqli_real_escape_string($con, $link)
);
// SQL execute
$result = mysqli_query($con, $sql) or die('Error: ' . mysqli_error($con));
// Free result
mysqli_free_result($result);
// Close connection
mysqli_close($con);
echo "This video has been successfully added to the Kim Watt videos.";

Categories