Php not inserting values into database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aravona
Forum Contributor
Posts: 347
Joined: Sat Jun 13, 2009 3:59 pm
Location: England

Php not inserting values into database

Post 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
mattpointblank
Forum Contributor
Posts: 304
Joined: Tue Dec 23, 2008 6:29 am

Re: Php not inserting values into database

Post 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.
aravona
Forum Contributor
Posts: 347
Joined: Sat Jun 13, 2009 3:59 pm
Location: England

Re: Php not inserting values into database

Post 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
Post Reply