Page 1 of 1

Php not inserting values into database

Posted: Thu Jun 18, 2009 4:35 am
by aravona
Ok I've got a form, with a drop down menu and my code appears to be happy enough when running a echo $sql however theres no input into my database, but theres no error either the code runs fine and happily redirects to my new page.

here my html form:

Code: Select all

<form action= "CreateChar.php" method="post">
<span class="style1">Character name:</span>
<input name="txtCharName" type="text" size="20" />
<br />
<br />
<span class="style1">Character Class:</span>
<select name="selCharClass">
<option value="Warrior" selected="selected">Warrior</option>
<option value="Mage" >Mage</option>
</select>
<br />
<br />
<input name="Create" type="submit" />
</form>
And heres my corresponding php code:

Code: Select all

<?php
    
 
    $link = mysql_connect('localhost','root','');
    mysql_select_db('gametest',$link);
 
    $CharClass = $_POST['selCharClass'];
 
    $sql = "INSERT INTO characters (CharName, Charclass) ";
    $sql = $sql . " values ('$_POST[txtCharName]', '$CharClass')";
 
 
 
    // echo $sql;
 
 
    echo "You have chosen your character."; 
 
?>
Thanks in advance

Aravona

Re: Php not inserting values into database

Posted: Thu Jun 18, 2009 4:44 am
by mattpointblank
You're not actually running your query - you're just producing a string ($sql) which contains it. You need to add this line:

Code: Select all

 
$result = mysql_query($sql) or die(mysql_error());
 
This runs your query using the mysql_query function, and prints an error if it fails.

Also, you should NEVER use $_POST values directly in queries. Google 'SQL injection' and learn about sanitising user input.

Re: Php not inserting values into database

Posted: Thu Jun 18, 2009 4:48 am
by aravona
I know about sql injection, a $dirtystuff will fix it later but I'm only testing everything on an internal system before I make everything secure :)

Thanks ^_^ worked fine, can't believe I forgot something so simple, guess its my fault for hacking apart my old code XD