Search code examples
phpmysqlsqldatabaseinsert-update

My PHP code will not let me insert into my mysql table


I tried everything I could think of, I look at it over and over. I added echo (); to see if the problem was something else. Everything is spelled like it is on the server. I don't know what else to do. Please help!!

<?php
include('../lock.php');

$username    =    $login_session;  
$characterName    =    mysql_real_escape_string($_POST['characterName']);  
$gender =    mysql_real_escape_string($_POST['gender']);   
$height = "58" + rand(2, 20);   
$weight = "120" * rand(2, 8);

echo ($id . "<br />");    
echo ($username . "<br />");  
echo ($characterName . "<br />");  
echo ($gender . "<br />");  
echo ($height . "<br />");   
echo ($weight . "<br />"); 

if(isset($_POST['nc1'])) 

{  
$query    =    "INSERT INTO character(id, username, characterName, gender, height,   weight) VALUES ('$id', '$username', '$characterName', '$gender', '$height', '$weight')";  
mysql_query($query) or die('Error: ' . mysql_error());  
//header('location:success.php');   
echo ("success");  
}  
?>

Jan 29, 2014 - I have made the updates you have suggested(but mysqli) and everything is echoing out correctly, the mysql_error() is returning blank but there is an error. POST is working. I still don't know how to fix it. The connection is also correct.

I take that back, the error is: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'character (id, username, characterName, gender, height' at line 1


Solution

  • First of all, you must specify the logical structure of the database in your question, and it seems that your id is a primary key and you have done $id = $id. This may cause the id to be duplicate or null so the first check for that variable is set or not and also check for other constraints like not null. If it is applied in the fields and is not fulfilled the rows can't be inserted too.

    Secondly check your database connection string, if you are reachable to database through the connection string like,

    boolean function connect($host, $uname , $pass){
    if(mysql_connect($host, $uname, $pass))
    return true;
    else 
    return false;
    }
    

    just try this may you be able to insert rows