0

Thank you guys, worked it out, turns out it was in the js a word wasn't spelled correctly, always something simple

This is my script to write data to my database on my local server, it currently only writes to 2 fields, not the alias one, have I done anything wrong? I've triple checked the names in both the html form and the database field.

<?php
  // 1. Create connection to database

  mysql_connect('localhost','root','') or die('Could not connect to mysql: <hr>'.mysql_error());

  // 2. Select database

  mysql_select_db("trialdb") or die('Could not connect to database:<hr>'.mysql_error());

  // 3. Assign variables (after connection as required by escape string)

$alias = $_POST['alias'];
$name = $_POST['name'];
$email = $_POST['email'];

  // 4. Insert data into table

  mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')"); 
  Echo 'Your information has been successfully added to the database.';  
  print_r($_POST);
  mysql_close()
?>

2 Answers2

0

First of all you should always check if the POST variables are being sent correctly:

if (
    !isset($_POST['alias']) or
    !isset($_POST['name']) or
    !isset($_POST['email'])
) // something is wrong

Second, you don't want to inject user input directly into the sql query. You should perform some escaping first (or even better replace the mysql_* deprecated drivers with PDO or mysqli and just use prepared statements):

$alias = mysql_real_escape_string($_POST['alias']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);

Third, you may want to check if the query performed correctly before printing a success message:

$res = mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')"); 

echo ($res) 
    ? 'Your information has been successfully added to the database.' 
    : 'Your information couldn't be added to the database';
Community
  • 1
  • 1
Shoe
  • 74,840
  • 36
  • 166
  • 272
0

you can try

<?php

$conn = mysql_connect('localhost','root','') or die('Could not connect to mysql: '.mysql_error());

mysql_select_db("trialdb", $conn) or die('Could not connect to database:'.mysql_error());

$alias = $_POST['alias'];
$name = $_POST['name'];
$email = $_POST['email'];

mysql_query("INSERT INTO user_data (`alias`, `name`, `email`) VALUES ('$alias', '$name', '$email')", $conn); 

echo 'Your information has been successfully added to the database.';  

print_r($_POST); 

mysql_close();

?>
nsgulliver
  • 12,655
  • 23
  • 43
  • 64
khoa vo
  • 1
  • 2