简体   繁体   中英

Error querying database when inserting into cpanel phpmyadmin

<?php
    $fname=$_POST['fname'];
    $mname=$_POST['mname'];
    $lname=$_POST['lname'];
    $college_name=$_POST['college_name'];
    $semester=$_POST['semester'];
    $contact=$_POST['contact'];
    $email=$_POST['email'];


    $dbc = mysql_connect('localhost','XXXX',"XXXX",'XXXXX')
            or die('error connecting to MYSQL server');
    echo kkk;
    $query = "INSERT INTO tab_m_registration(fname, mname, lname, college_name, semester, contact, email)".
            "VALUES(`$fname`, `$mname`, `$lname`, `$college_name`, `$semester`, `$contact`, `$email`)";
            echo $query;
            $result=mysql_query($query,$dbc) or die('error querying database');

            echo $result;

            echo 'Thanx for submitting the form. <br/>';
            mysql_close($dbc);

        ?>

Actually I don't understand where is the problem.

$result = mysql_query($query, $dbc)

is not working I think.

I first tried mysqli_query() and it got problem. Then I tried this

$result = mysql_query($dbc, $query)

and I get an error "argument 1 should be string" in mysql_query() .

I swapped the values and finally used this mysql_query($query, $dbc) .

It shows the value passing through echo.

But still there's a problem inserting the data in the database table. Please help me out.

You will need to investigate the error further (get some error messages). You could use a try/catch block to get more error messages (are the fields all set up, etc.). Consider the following code but bear in mind that it is still wide open to SQL injection (just to get an error message):

try {
    $db = mysqli_connect("host", "user", "password", "database");
    if ($db->connect_errno)
        throw new Exception("Connection to the database failed: " . $db->connect_error);

    $sql = "INSERT INTO tab_m_registration (`fname`, `mname`, `lname`, `college_name`, `semester`, `contact`, `email`) ";
    $sql .= "VALUES(`$fname`, `$mname`, `$lname`, `$college_name`, `$semester`, `$contact`, `$email`)";

    if (!$db->query($sql))
        throw new Exception("Error Inserting Data " . $db->error);

    mysqli_close($db);
} catch (Exception $e) {
    echo $e->getMessage();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM