问题描述:

I've got this code

<?php

$db_host="localhost";

$db_username="root";

$db_password="";

$db_name="mydb";

$db_connect=mysqli_connect($db_host, $db_username,$db_password, $db_name);

//check connection

if (mysqli_connect_error()){

echo "Failed to connect to MySQL:" .mysqli_connect_error();

} else{

echo "Connection successful" ;

}

?>

When i run the code it shows "Connection successful" but when i input data into a table that is in the database it gives me an error "No database selected"

I tried the code below and it seems to work, other than the fact that the Auto increment value (ID) isn't passed into the database so it gives me an error which means that "the data passed in row 1 doesn't match the datatype. "(Shouldn't it not be required to be entered, and with each insert query gets updated automatically?) I am passing values to the table using and insert statement and not in array form, maybe?

<?php

error_reporting(1);

$connect_error = 'Sorry, we\'re experiencing connection problems.';

mysql_connect('localhost','root','') or die($connect_error);

mysql_select_db('mydb') or die($connect_error);

?>

I was asked to provide the code i'm using for inserting data into the table.

 <?php

require_once ('dbconnect.php');

$title= "my title";

if (isset($_POST['submit'])) {

$username = $_POST['username'];

$password = $_POST['password'];

$class = $_POST['class'];

$type = $_POST['type'];

$description = $_POST ['description'];

$date = date(d-m-y);

$sql= "INSERT into mytable values ('username, password, class, type, description')" ;

$qry= mysql_query($sql) ;

if (!$qry) {

echo "Something went wrong: " . mysql_error();}

else echo "Finished successfully";

}

?>

网友答案:

Are you mixing mysqli and mysql.

use below code to fire mysql query

mysqli_query($db_connect,$sql);

replace this line

$qry= mysql_query($sql) ;

to

$qry= mysqli_query($db_connect,$sql);
网友答案:

Latest Version of php uses mysqli object (mysql improved) insted of methods for accessing mysql database.

    <?php 

    $db_host="localhost";
    $db_username="root";
    $db_password="";
    $db_name="mydb";

    $db_connect=new mysqli($db_host, $db_username,$db_password, $db_name);


    //check connection
    if ($db_connect -> connect_error)
    { 
    echo "Failed to connect to MySQL:".$db_connect->connect_error;
    }
    else{
    echo "Connection successful" ; }

    ?>
网友答案:

I had two mistakes, one was mixing mysqli in the dbconnect.php while using mysql_query in the other page. And then I was confused about the second parameter to use with mysqli_query other than the insert statement, used the connection variable and it now works.

相关阅读:
Top