PHP how to insert select box value into database - php

i have a question
i already make a form to view two select box value with database and one text filed value
i want to know how to insert those value back into database with different table
my script on view select box value is something like this
<?php
$query = "SELECT gejala FROM gejala where idatribut =110000";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="gejala1">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['gejala']."'>".$row['gejala']."</option>";
}
?>
</select>
<p>Subatribut2
<?php
$query = "SELECT gejala FROM gejala where idatribut =110000";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="gejala2">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['gejala']."'>".$row['gejala']."</option>";
}
?>
</select>
<p>
<label>value
<input type="text" name="textfield">
</label>
<p>
<input name="submit" type="button" value="submit">
<p>
how to know how to insert this value into another table(pucuk) with same field
thankyou
i already try insert script
<?php
if(isset($_POST['gejala1'])) {
$gejala1 = $_POST['gejala1'];
$sql = "INSERT INTO pucuk (gejala1) VALUES ({$gejala2})";
$dbLink = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('cbrteh', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if(isset($_POST['gejala2'])) {
$gejala2 = $_POST['gejala2'];
$sql = "INSERT INTO pucuk (gejala2) VALUES ({$gejala2})";
$dbLink = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('cbrteh', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
}
?>
</form>
but when i hit submit button it still has no effect

In while loop itself u can write insert query and send the option box value into the field u want,try it !

after a submit, your select option value will be in the $_POST[] variable under the name of your select. Namely, here "gejala2"

put your code in a form with method=POST and after submitting your form you will get all your new values in _POST array
for example
if(isset($_POST['submit']))
{
$var1=$_POST['select1'];
$var2=$_POST['select2'];
$var3=$_POST['select3'];
//then write update/insert query as your requirement
}

Try this
<?php
if(isset($_POST['gejala1'])) {
$gejala1 = $_POST['gejala1'];
$sql = "INSERT INTO pucuk (gejala1) VALUES ({$gejala2})";
$dbLink = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('cbrteh', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if(isset($_POST['gejala2'])) {
$gejala2 = $_POST['gejala2'];
$sql = "INSERT INTO pucuk (gejala2) VALUES ({$gejala2})";
$dbLink = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('cbrteh', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
?>
<form action="" method="POST"><!-- add this -->
<?php
$query = "SELECT gejala FROM gejala where idatribut =110000";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="gejala1">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['gejala']."'>".$row['gejala']."</option>";
}
?>
</select>
<p>Subatribut2
<?php
$query = "SELECT gejala FROM gejala where idatribut =110000";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="gejala2">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['gejala']."'>".$row['gejala']."</option>";
}
?>
</select>
<p>
<label>value
<input type="text" name="textfield">
</label>
<p>
<input name="submit" type="submit" value="submit"> <!-- changed from type="button" to type="submit"> -->
<p>
</form>

Related

PHP - Insert Into Associative Table

I am trying to populate a mysql associative (many to many) table via a form submit. Basically, trying to use this page to associate a "Red Flag" to one-to-many "Products".
Screenshot of input form
FORM
<?php
require 'connect-db.php';
$sql = "SELECT ID, prod_name FROM catalog";
$result = mysqli_query($mysqli, $sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p><strong>Add Red Flag:</strong></p>
<form action="addRedFlag.php" method="post" id="rfForm">
<p>Description:
<br/><textarea rows="4" cols="50" name="rfDescription" form="rfForm"></textarea>
<p>Severity: <br/>
<input type="radio" name="severity" value="minor"/>Minor<br/>
<input type="radio" name="severity" value="moderate"/>Moderate<br/>
<input type="radio" name="severity" value="major"/>Major<p/>
<select name="prod_id">
<option value="">Choose a product</option>
<?php while($row = mysqli_fetch_assoc($result)){ ?>
<?php $id = $row['ID']; ?>
<?php $title = $row['prod_name']; ?>
<option value="<?php echo $id; ?>"><?php echo $title; ?></option>
<?php } ?>
</select>
<p/><input type="submit" value="Submit" name="submit" /></form><br>
Reset Form <br>
View Red Flag List<br>
Home
</body>
</html>
PHP HANDLER
<?php
// connect to the database
include("connect-db.php");
$value1 = $_POST['rfDescription'];
$value2 = $_POST['severity'];
$value3 = $_POST['prod_id'];
$sql = "INSERT INTO redFlag (description, severity) VALUES ('$value1', '$value2')";
$sql2 = "SELECT ID FROM redFlag WHERE (description = '$value1')";
$sql3 = "INSERT INTO prod_RF (cat_id, rf_id) VALUES ('$value3', '$value4')";
$result1 = mysqli_query($mysqli, $sql);
$result2 = mysqli_query($mysqli, $sql2);
if ($result1)
{
if ($result2)
{
$row = mysqli_fetch_assoc($result2);
$value4 = $row['ID'];
// echo $value4;
$result3 = mysqli_query($mysqli, $sql3);
if ($result3)
{
echo "success";
}
else {echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);}
}
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
?>
When executed, the code completes successfully BUT the value of rf_id in prod_RF table is always zero. This is strange because when I uncomment the
echo $value4;
line, the expected value is printed to the screen. For some reason, when I attempt to use that same value ($value4) as input to a SQL query ($sql3), something fails.
Thanks for any suggestions as I'm pretty new to all this.
A better way to do this is to use the MySQL function to get the last insert id so you can skip the second query.
$sql = "INSERT INTO redFlag (description, severity) VALUES ('$value1', '$value2')";
$sql3 = "INSERT INTO prod_RF (cat_id, rf_id) VALUES ('$value3', LAST_INSERT_ID())";
$result1 = mysqli_query($mysqli, $sql);
$result2 = mysqli_query($mysqli, $sql3);
// the $result2 query will insert the rf_id
// so you can test this result to see if it's all successful
That should remove a nice chunk of PHP from your code.
It looks like $value4 is not defined until after the $sql3 string has been crafted. Try defining $sql3 after you have defined $value4.

Fetching data issue from mysql database in this code

I am creating an Invitation Card app for my upcoming event which will be held. My code successfully inserts the data into mysql database named booking having table name data. But there is problem with retrieving. When I fill the form and submit, it saves data in db but generates nothing. It gives following error:
Fatal error: Call to a member function query() on resource in C:\xampp\htdocs\booking\index.php on line 44
Here is my code, please tell me how to resolve this issue. I shall be very thankful to you.
<html>
<body>
<?php
if(isset($_POST['add'])){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn){
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc()){
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
} else {
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
}
$sql = "INSERT INTO data ". "(CNIC, Name, FatherName, PostalAddress) " .
"VALUES('$emp_cnic', '$emp_name', '$emp_fname', '$emp_address')";
mysql_select_db('booking');
$retval = mysql_query($sql, $conn);
if(! $retval) {die('Could not enter data: ' . mysql_error());}
?>
<table border=2>
~~~~~~Your Invitation Card~~~~~
<tr><td>Your Name</td><td><?php
$sql = "SELECT name FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>Your Father Name</td><td>
$sql = "SELECT fname FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>Your CNIC Number</td><td>
$sql = "SELECT cnic FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>Your Postal Address</td><td>
$sql = "SELECT address FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>You are informed to approach Location XA-55 at 1800 Thursday with print of this
Invitation card to paticipate in the function. </td></tr><br>
</table>
<?php
mysql_close($conn);
} else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
Name: <input type="text" name="emp_name" id="emp_name"><br>
Father Name: <input type="text" name="emp_fname" id="emp_fname"><br>
CNIC: <input type="text" name="emp_cnic" id="emp_cnic"><br>
Address: <input type="text" name="emp_address" id="emp_address"><br>
<input type="submit" name="add" id="add" value="Submit">
<?php
}
?>
</body></html>
Change
$result = $conn->query($sql);
To
$result = mysql_query($sql);
For more info click here
I think you should be using mysql_query instead of $conn->query
I thin i spotted two errors in your code.
you should use
mysql_query($sql,$conn);
instead of (that was mentioned before)
$result = $conn->query($sql);
You missed a couple of opening php tags in your html table.
Try following code and let me know if it works.
if(! $conn){
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc()){
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
} else {
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
}
$sql = "INSERT INTO data ". "(CNIC, Name, FatherName, PostalAddress) " .
"VALUES('$emp_cnic', '$emp_name', '$emp_fname', '$emp_address')";
mysql_select_db('booking');
$retval = mysql_query($sql, $conn);
if(! $retval) {die('Could not enter data: ' . mysql_error());}
?>
<table border=2>
~~~~~~Your Invitation Card~~~~~
<tr><td>Your Name</td><td><?php
$sql = "SELECT name FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>Your Father Name</td><td>
<?php
$sql = "SELECT fname FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>Your CNIC Number</td><td>
<?php
$sql = "SELECT cnic FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>Your Postal Address</td><td>
<?php
$sql = "SELECT address FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>You are informed to approach Location XA-55 at 1800 Thursday with print of this
Invitation card to paticipate in the function. </td></tr><br>
</table>
<?php
mysql_close($conn);
} else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
Name: <input type="text" name="emp_name" id="emp_name"><br>
Father Name: <input type="text" name="emp_fname" id="emp_fname"><br>
CNIC: <input type="text" name="emp_cnic" id="emp_cnic"><br>
Address: <input type="text" name="emp_address" id="emp_address"><br>
<input type="submit" name="add" id="add" value="Submit">
<?php
}
?>
</body></html>

How to update specific rows through PHP form but I get undefined index: id

I want to create a book inventory with Create, Read, Update and Delete. I got it all going except for the Update query. Here is my code. First is the proj.php
<html>
<body>
<b>BOOK INVENTORY</b>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
Title: <input type="text" name="title">
Subtitle: <input type="text" name="subtitle">
Author: <input type="text" name="author">
Genre/Type: <select name="genre">
<option value="Business">Business</option>
<option value="Family">Family</option>
<option value="Romance">Romance</option>
<option value="Education">Education</option>
<option value="Self-help">Self-help</option>
<option value="Spiritual">Spiritual</option>
<option value="Music">Music</option>
</select>
Publish Date: <input type="date" name="publishdate">
Publisher: <input type="text" name="publisher">
Series: <input onkeypress="return isNumberKey(event)" type="text" name="series">
ISBN: <input type="text" name="isbn">
Pages: <input onkeypress="return isNumberKey(event)" type="text" name="pages">
Price: <input type="text" value="$" name="price">
<input type="submit" value="Create" name="submit">
</form>
<!--create new book entry-->
<?php
include 'connection.php';
if (!isset($_POST['submit'])) {
// form not submitted
}
else {
// get form input
// check to make sure it's all there
// escape input values for greater safety
$title = empty($_POST['title']) ? die ("ERROR: Enter a Title") : mysql_escape_string($_POST['title']);
$subtitle = empty($_POST['subtitle']) ? die ("ERROR: Enter an Subtitle") : mysql_escape_string($_POST['subtitle']);
$author = empty($_POST['author']) ? die ("ERROR: Enter an Author") : mysql_escape_string($_POST['author']);
$genre = empty($_POST['genre']) ? die ("ERROR: Enter a Genre/Type") : mysql_escape_string($_POST['genre']);
$publishdate = empty($_POST['publishdate']) ? die ("ERROR: Enter a Publish Date") : mysql_escape_string($_POST['publishdate']);
$publisher = empty($_POST['publisher']) ? die ("ERROR: Enter a Publisher") : mysql_escape_string($_POST['publisher']);
$series = empty($_POST['series']) ? die ("ERROR: Enter a Series") : mysql_escape_string($_POST['series']);
$isbn = empty($_POST['isbn']) ? die ("ERROR: Enter an ISBN") : mysql_escape_string($_POST['isbn']);
$pages = empty($_POST['pages']) ? die ("ERROR: Enter a Pages") : mysql_escape_string($_POST['pages']);
$price = empty($_POST['price']) ? die ("ERROR: Enter a Price") : mysql_escape_string($_POST['price']);
// create query
$insert = "INSERT INTO books (Title, Subtitle, Author, Genre, Publishdate, Publisher, Series, ISBN, Pages, Price)
VALUES ('$title', '$subtitle', '$author', '$genre', '$publishdate', '$publisher', '$series', '$isbn', '$pages', '$price')";
// execute query
$result = mysql_query($insert) or die ("Error in query: $insert. ".mysql_error());
// print message of the new book inserted
//echo "New book record created entitled "."$ ";
}
if (!isset($_POST['submit'])) {
}
$query = "SELECT * FROM symbols";
?>
<!------------><!------------><!------------><!------------><!------------>
<!------------><!------------><!------------><!------------><!------------>
<!--Delete Record-->
<?php
// set server access variables
$host = "localhost";
$user = "root";
$pass = "";
$db = "david";
// create mysqli object
// open connection
$mysqli = new mysqli($host, $user, $pass, $db);
// check for connection errors
if (mysqli_connect_errno()) {
die("Unable to connect!");
}
// if id provided, then delete that record
if (isset($_GET['id'])) {
// create query to delete record
$query = "DELETE FROM books WHERE id = ".$_GET['id'];
// execute query
if ($mysqli->query($query)) {
// print number of affected rows
echo $mysqli->affected_rows." row(s) affected";
}
else {
// print error message
echo "Error in query: $query. ".$mysqli->error;
}
}
// query to get records
$query = "SELECT * FROM books";
// execute query
if ($result = $mysqli->query($query)) {
// see if any rows were returned
if ($result->num_rows > 0) {
// yes
// print them one after another
echo "<table cellpadding=10 border=1>";
while($row = $result->fetch_array()) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>Delete</td>";
echo "<td>More...</td>";
echo "</tr>";
}
}
// free result set memory
$result->close();
}
else {
// print error message
echo "Error in query: $query. ".$mysqli->error;
}
// close connection
$mysqli->close();
?>
<?php
include 'edit.php';
if (!isset($_POST['submit'])) {
}
?>
And here is my edit.php where I get the error undefined index : id at line 5
<?php
mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db("david") or die(mysql_error());
$UID = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM books WHERE 'id' = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$title = $row['title'];
$subtitle = $row['subtitle'];
$author = $row['author'];
$genre = $row['genre'];
$publishdate = $row['publishdate'];
$publisher = $row['publisher'];
$series = $row['series'];
$isbn = $row['isbn'];
$pages = $row['pages'];
$price = $row['price'];
}
?>
<form action="update.php" method="get">
<input type="hidden" name="id" value="<?=$UID;?>">
Title: <input type="text" name="ud_title" value="<?=$title?>"><br>
Subtitle: <input type="text" name="ud_subtitle" value="<?=$subtitle?>"><br>
Author: <input type="text" name="ud_author" value="<?=$author?>"><br>
Genre: <input type="text" name="ud_genre" value="<?=$genre?>"><br>
Publish Date: <input type="text" name="ud_publishdate" value="<?=$publishdate?>"><br>
Publisher: <input type="text" name="ud_publisher" value="<?=$publisher?>"><br>
Series: <input type="text" name="ud_series" value="<?=$series?>"><br>
ISBN: <input type="text" name="ud_isbn" value="<?=$isbn?>"><br>
Pages: <input type="text" name="ud_pages" value="<?=$pages?>"><br>
Price: <input type="text" name="ud_price" value="<?=$price?>"><br>
<input type="Submit">
</form>
<?php
}else{
}
?>
and here is my update.php with the update query
<?php
mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db("david") or die(mysql_error());
$ud_ID = (int)$_POST["id"];
$ud_title = mysql_real_escape_string($_POST["ud_title"]);
$ud_subtitle = mysql_real_escape_string($_POST["ud_subtitle"]);
$ud_author = mysql_real_escape_string($_POST["ud_author"]);
$ud_genre = mysql_real_escape_string($_POST["ud_genre"]);
$ud_publishdate = mysql_real_escape_string($_POST["ud_publishdate"]);
$ud_publisher = mysql_real_escape_string($_POST["ud_publisher"]);
$ud_series = mysql_real_escape_string($_POST["ud_series"]);
$ud_isbn = mysql_real_escape_string($_POST["ud_isbn"]);
$ud_pages = mysql_real_escape_string($_POST["ud_pages"]);
$ud_price = mysql_real_escape_string($_POST["ud_price"]);
$query="UPDATE books
SET title = '$ud_title', subtitle = '$ud_subtitle', author = '$ud_author', genre = '$ud_genre', publishdate = '$ud_publishdate',
publisher = '$ud_publisher', series = '$ud_series', isbn = '$ud_isbn', pages = '$ud_pages', price = '$ud_price'
WHERE id='$ud_ID'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>($ud_ID) Record Updated<p>";
}else{
echo "<p>($ud_ID) Not Updated<p>";
}
?>
Please kindly help me get rid of this error:
undefined index: id at edit.php.
I'm shocked by the terrible formating and not able to read the code.
But according to your description, you get undefined index: id because you either did not include the id field in the form, or you include it in the url but use $_POST instead of $_GET.
EDIT:
If this is exactly the code you have, then the problem should be the last few lines in proj.php.
include 'edit.php' is not the correct way to call edit page, but you should use a link tag which links to edit.php?id=some_id, just like you did with show.php

Displaying query results after submitting a PHP form

I am currently working on a school project using php and mysql. I have created a form with three drop down boxes where users select types of data they are looking for. However, I am having a lot of trouble displaying the results after the form is submitted. Here is my current code:
<?php
require_once 'connection.php';
?>
<form action="stats.php" method ="post">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>
Specify Date, Month, and County
</legend>
<p>
<label for="year">
Please select a year
</label>
<select name= 'year'>
<?php
$query = "select distinct year from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
?>
</select>
</p>
<p>
<label for="month">
Please select a month
<label>
<select name= 'month'>
<?php
$query = "select distinct month from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->month."'>".$row->month."</option>";
}
?>
</select>
</p>
<p>
<label for="location">
Please specify a location
</label>
<select name='select'>
<?php
$query = "select * from unemployed";
$result = $conn->query($query);
while ($finfo = $result->fetch_field()) {
echo "<option value='".$finfo->name."'>".$finfo->name."</option>";
}
?>
</select>
</p>
<input type ="submit" />
</fieldset>
</form>
<?php
if (isset($_POST['submitted'])) {
include('connection.php');
$gYear = $_POST["year"];
$gMonth = $_POST["month"];
$gSelect = $_POST["select"];
$query = "select $gSelect from unemployed where year='$gYear' and month='$gMonth'";
$result = $conn->query($query) or die('error getting data');
echo"<table>";
echo "<tr><th>Year</th><th>Time</th><th>$gSelect</th></tr>";
while ($row = $result->fetch_object()){
echo "<tr><td>";
echo $row['Year'];
echo "</td><td>";
echo $row['Month'];
echo "</td><td>";
echo $row['$gSelect'];
echo "</td></tr>";
}
echo "</table";
} // end of main if statement
?>
I am almost certain my problem lies within my while statement. I get the titles of my table columns to show up (Year, Month, $gSelect), but I am not getting my query results to be displayed.
I have tried:
while ($row = $result->fetch_object())
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
Neither of these are working for me. I have looked at php.net for guidance. I am still confused with what to do. If anyone could help me, I would really appreciate it.
Always check your returns:
if( ! $result = $conn->query($query) ) {
die('Error: ' . $conn->error());
} else {
while($row = $result->fetch_object()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
}
Also putting error_reporting(E_ALL); at the top of your script while you're developing it will help enormously as well.
You should really look into passing variables as parameters to your query instead of injecting them as variables directly into your query. This can lead to sql injection attacks.
Also, here's a quick example of how to write a query using PDO and mysql:
//Simple Query
$dbh = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
//Useful during development.
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//mysql can have prepares depending on the version: http://stackoverflow.com/questions/10113562/pdo-mysql-use-pdoattr-emulate-prepares-or-not
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sth = $dbh->query("SELECT * FROM table");
var_dump($sth->fetchAll(PDO::FETCH_ASSOC));
//Now with pass params and a prepared statement:
$query = "SELECT * FROM table WHERE someCol = ?";
$sth = $dbh->prepare($query);
$sth->bindValue(1,"SomeValue");
$sth->execute();
$results = $sth->fetchAll(PDO::FETCH_ASSOC));

insert selected option into table

I have this code and I'm trying to put the selected state in a subcat table.
So far it returns an empty value. I'm not sure if this is clear or not, but all I want is: select a state from the select option and submit it. I want to get the selected state name into my table subcat.
enter <?php
include("connect.php");
$state = $row['states']; //Select name
if (isset($_POST[submit])){
$query = "INSERT INTO subcat (sub_name) VALUES ('$state')";
mysql_query($query) or die(mysql_error());
}
?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM state");
echo "<select name='states'>
<option value=''>Select a state</option>";
while ($row = mysql_fetch_assoc($sql)) {
echo "<option value='$row[id]'>$row[name]</option>";
}
echo "</select>";
?>
<input type="submit" name="submit" value="Continue" />
</form> here
Thanks
Change $state = $row['states'] to $state = $_POST['states']
<?php
include("connect.php");
if (isset($_POST[submit]))
{
$state = $_POST['states']; //Select name
$query = "INSERT INTO subcat (sub_name) VALUES ('$state')";
mysql_query($query) or die(mysql_error());
}
?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM state");
echo "<select name='states'>
<option value=''>Select a state</option>";
while ($row = mysql_fetch_assoc($sql)) {
echo "<option value='$row[id]'>$row[name]</option>"; // if you want to
//get the name into table, then use like this
//echo "<option value='$row[name]'>$row[name]</option>"; or
//echo "<option>$row[name]</option>";
}
echo "</select>";
?>
<input type="submit" name="submit" value="Continue" />
</form>
Try this:
enter <?php
include("connect.php");
if (isset($_POST[submit])){
$state = $_POST['states'];
$query = "INSERT INTO subcat (sub_name) VALUES ('".mysql_real_escape_string($state)."')";
mysql_query($query) or die(mysql_error());
}
?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM state");
echo '<select name="states" id="states">
<option value="">Select a state</option>';
while ($row = mysql_fetch_assoc($sql)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';
?>
<input type="submit" name="submit" value="Continue" />
</form> here
Dont forget to use mysql_real_escape_string to prevent SQL injections. I have replaced $state = $row['states']; with $state = $_POST['states'];
I dont know where u got $row from...
The above will insert the states name into the database.

Categories