Page 1 of 1
Insert data into table- simple problem
Posted: Sun Dec 14, 2008 11:15 am
by fuzzyfuzz
Hi!
I posted the data in this script from a form - the variables in this code stored the data inserted from the textboxes in the form.
from some reason this doesn't work.
Any Idea?
Code: Select all
<?php
$x = $_POST['name'];
$y = $_POST['age'];
$z= $_POST['subject'];
$mysql_link= mysql_connect('localhost','root','') or die("ERROR:cannot connect");
echo "connected successfully to MySQL server.";
mysql_select_db('pets',$mysql_link) or die ("could not open db".mysql_error());
echo "connected successfully to pets.";
mysql_query("INSERT INTO students (name, age, subject)
VALUES ($x, $y, $z)");
mysql_close($mysql_link);
?>
Re: Insert data into table- simple problem
Posted: Sun Dec 14, 2008 12:59 pm
by SteveC
Code: Select all
<?php
$x = $_POST['name'];
$y = $_POST['age'];
$z= $_POST['subject'];
$mysql_link= mysql_connect('localhost','root','') or die("ERROR:cannot connect");
echo "connected successfully to MySQL server.";
mysql_select_db('pets',$mysql_link) or die ("could not open db".mysql_error());
echo "connected successfully to pets.";
mysql_query("INSERT INTO students (name, age, subject)
VALUES ($x, $y, $z)");
mysql_close($mysql_link);
?>
Yes, you need to encase your values with quotes or double quotes, what you have here is wrong:
Code: Select all
INSERT INTO students (name, age, subject)
VALUES ($x, $y, $z)
You need:
Code: Select all
INSERT INTO students (name, age, subject)
VALUES ('$x', '$y', '$z')
You don't necessarily need quotes around the age, but it certainly doesn't hurt.
Re: Insert data into table- simple problem
Posted: Sun Dec 14, 2008 12:59 pm
by jaoudestudios
Do you get any errors? or does it just not add the info to the database?
Can you post your database schema!
Re: Insert data into table- simple problem
Posted: Mon Dec 15, 2008 2:00 pm
by cavemaneca
SteveC wrote:
Code: Select all
INSERT INTO students (name, age, subject)
VALUES ('$x', '$y', '$z')
Does this really work? I would do that script something like this.
Code: Select all
$query = "INSERT INTO `students` (`name`, `age`, `subject`)
VALUES ('".$x."', '".$y."', '".$z."')";
$result = mysql_query($query);
I like it this way because I have them separated and also I can check the results. Mainly, It just helps me debug. But I didn't know you could make it smoother, like one line, and have it still look good.
Re: Insert data into table- simple problem
Posted: Mon Dec 15, 2008 2:09 pm
by jaoudestudios
An even better way is to be more precise...
Code: Select all
// mysql
INSERT INTO students SET name = '$name', age = '$age', subject = '$subject'
// php
$q = "INSERT INTO students SET name = '".$name."', age = '".$age."', subject = '".$subject."'";
Yes to your question cavemaneca, it is possible to put the query straight into mysql_query() - but it is lazy. Plus when queries become more complicated like 5 to 10 lines long it makes it more difficult to follow!