简体   繁体   中英

Don't insert to MySQL with php

I'm creating simple registration form. But I have problems with inserting data to MySQL table.

        if (isset($_POST['name']) && isset($_POST['email'])){
            $userName = $_POST['name'];
            $email = $_POST['email'];
            $company = $_POST['company'];

            include '../template/sql-connect.php';

            $db_server = mysql_connect($db_hostname, $db_username, $db_password);

            if(!db_server) { die("Query error"); }

            $query = "INSERT INTO users VALUES" .
                 "('$userName', '$email', '$company')";

           if (!mysql_query($query, $db_server))
                 echo "INSERT failed: $query<br>" .
                 mysql_error() . "<br><br>";

            mysql_close($db_server);
        }

Help me to resolve this problem, please. Thank you!

I usually make a special file for database connection like this:

      <?php 
        $db_name='name'; 
        $server='server';
        $username='name'; 
        $password='pass'; 


$link=mysqli_connect($server,$username,$password,$db_name); 

if(!link){
die('Something went wrong'.mysqli_error($link)); 
} ?>

And then include it in the page I want to make database inserts or selections from. So if I need to make a insertion on lets say login_do.php I will just include the database file in like this

<?php 
include_once 'databaseConn.php'; 
.
.
. and so on ...

And try making your SQL statement like this.

$query = "INSERT INTO users (username,email,company) VALUES" .
                 "('".$userName."','".$email."','".$company."')"; 

You need to specify to which index in the database you are sending some value and then write them in the same order.

I hope this works for you and I answered your question. Good luck and keep coding ;)

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