0

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.

Bryan
  • 9
  • 2
  • 1
    @Thomas this is a matter of opinion and up to OP what they want to use. Although mysql_ is deprecated. – Nigel Ren Apr 22 '18 at 14:44
  • 1
    Possible duplicate of [Can I mix MySQL APIs in PHP?](https://stackoverflow.com/questions/17498216/can-i-mix-mysql-apis-in-php) – Nigel Ren Apr 22 '18 at 14:48
  • @NigelRen you missed the point. PDO is not only connected with OOP, but also is more flexible, and enables connecting with many other DBs. Abstraction provided by PDO is more convinient to use – Tomasz Durda Apr 22 '18 at 14:50
  • What's more mysql_* is removed, not deprecated – Tomasz Durda Apr 22 '18 at 14:50
  • you can't connected to database as there is `@` in your `mysqli_select_db(DB_NAME,$con)` and use mysqli_* function instead of mysql_* funtion – Akshay Parate Apr 22 '18 at 14:58

1 Answers1

0

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);
?>
Anfath Hifans
  • 1,588
  • 1
  • 11
  • 20