I wrote a code in PHP to connect with Mysql database and add data into it.. code is given below:
$dbhostname = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "rms_invoice";
function showDBMessage(){
if($_POST["name"] != NULL){
//came from register page
if(register()){
print("<br/>Registered successfully!!!");
} else {
print("<br/>Registration failed!!!");
}
}
}
function register(){
global $dbhostname,$dbusername,$dbpassword,$dbname;
// Create connection
$con=mysqli_connect($dbhostname,$dbusername,$dbpassword);
// Check connection
if (!mysqli_connect_errno()) {
print("MYSQL Connection established...<br/>");
echo "<br/>Successful: ".mysqli_get_host_info($con);
$selected = mysqli_select_db($con, $dbname);
if(false!==$selected){
$name = mysqli_real_escape_string($con, $_POST["name"]);
$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$address = mysqli_real_escape_string($con, $_POST["address"]);
$insertUserQuery="INSERT INTO USER(name,username,password,address) VALUES ('$name','$username','$password','$address')";
echo $insertUserQuery;
$result = mysqli_query($con, $insertUserQuery);
if ( false===$result ) {
printf("<br/>mysqli_connect_error: %s\n", mysqli_connect_error());
printf("<br/>mysqli_error: %s\n", mysqli_error($con));
} else {
echo "<h4>New User Added!!!</h4><br/>";
return true;
}
}else{
printf("<br/>Error while selecting database, error:%s\n",mysqli_errno($con));
}
} else {
print("<br/>Failed to connect to MySQL: "+mysqli_connect_error());
}
mysqli_close($con);
return false;
}
and the output is:
MYSQL Connection established...
Successful: localhost via TCP/IP
INSERT INTO USER(name,username,password,address) VALUES ('nitin','ndthokare','p','beed')
mysqli_connect_error:
mysqli_error: No database selected
Registration failed!!!
It is getting connected but database selection seems to be problem. (same query executes successfully through mysql cli).
I tried many possible corrections in code discussed on SO, but could not succeed.
Can anybody help me to find out the mistake?