Jump to content

passing a text field

- - - - -

  • Please log in to reply
1 reply to this topic

#1
brad35309

brad35309

    Newbie

  • Members
  • Pip
  • 2 posts
allright Hello everyone this will be my first post. i got an internship at the Milwaukee Zoo and i've been assigned some work with php. PHp is new to me so im having troubles understanding some concepts. i have a strong programming backround so i learn new languages relatively fast so lets jump into it: heres my code for a practice page just to get a feel for php.

<body>
<label>Enter Something</label><input type="text" name="textfield" id="textfield" />
<input name="button" type="submit" id="button" onclick="<?php
$text = textfield;
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("inventory", $con);

mysql_query("INSERT INTO main (Department,Location)
VALUES ($text,'Homeduh')");

mysql_close($con);
?>
" value="Submit" />
<form id="form1" name="form1" method="post" action="">
</form>
</body>

So ultimately the goal here was to pass the input from "textfield" to the variable $text as its typed into the box. when the user hits the submit button it will send $text and homeduh to my sql database. it dosen't work!

#2
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
  • Location:New York, NY
Congratulations on your internship and welcome to CodeCall. When posting code, please use [noparse]
...
...
and

Quote

...
[/noparse]
tags when appropriate.

(Untested)
<?php

$con = mysql_connect("localhost","root","root");

if (!$con)

{

die('Could not connect: ' . mysql_error());

}


mysql_select_db("inventory", $con);


if(isset($_POST['textfield']) && $_POST['textfield'] != "") {

    $text = mysql_real_escape_string($_POST['textfield']);

    mysql_query("INSERT INTO main (Department,Location) VALUES ($text,'Homeduh')") or die(mysql_error());

}

mysql_close($con);

?>


<body>

<label>Enter Something</label>

<form id="form1" name="form1" method="post" action="">

    <input type="text" name="textfield" id="textfield" />

    <input name="button" type="submit" id="button" value="Submit" />

</form>

</body>

Depending on the form method, PHP will allow you to access form elements with either the $_GET or $_POST super global associative array. The arrays key will correspond to your form element names. So when the form is submitted, you can access the data via $_POST['textfield']. Obviousally, you want to make sure the variable has a value before you insert it, and the mysql_real_escape_strin() is used as a security precaution to prevent SQL injections.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users