problem with form php and sql - php

Ok, so im new in php and sql, and I have this form that submits some names and cities into a database.
I managed to do it, but once a hit the submit button, i get an error:
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1"
but, when i check in phpmyadmin, the new record is there!!, so im not sure what's wrong, thats the problem.
this is the code:
<?php
mysql_connect("localhost", "name", "pass") or die(mysql_error());
echo "Connection to the server was successful!<br/>";
mysql_select_db("db_name") or die(mysql_error());
echo "Database was selected!<br/>";
$resultComuna = mysql_query("SELECT idComuna, nombre FROM comuna ORDER BY nombre ASC");
$resultGiro = mysql_query("SELECT idGiro, nombre FROM giro ORDER BY nombre ASC");
?>
<html>
<head>
<title>TEST</title>
</head>
<body>
<br/><br/>
<form name="form" method="POST" action="test_action.php">
<div align="center">
<!--///////////////// input nombre //////////////////////// -->
NOMBRE CLIENTE:
<input name="nombreCliente" type="text" maxlength="30" size="40"></>
<!-- ///////////////////////////////////////////////////////////// -->
<!-- ////////////////////drop box para giro ///////////////////// -->
GIRO:
<select name="giro">
<?php
while($row = mysql_fetch_assoc($resultGiro)){
echo "<option value=\"".$row['idGiro']."\">".$row['nombre']."</option><br/>";
}
?>
</select>
<!-- ///////////////////////////////////////////////////////////// -->
<!-- ////////////// dropbox para comunas //////////////////////// -->
COMUNA:
<select name="comunas">
<?php
while($row = mysql_fetch_assoc($resultComuna)){
echo "<option value=\"".$row['idComuna']."\">".$row['nombre']."</option><br/>";
}
?>
</select>
<!-- ////////////////////////////////////////////////////////////// -->
<input type="submit" value="Ingresar"> </>
</div>
</form>
</body>
</html>
and the test_action.php is:
<?php
$con = mysql_connect("localhost", "name", "pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("data_base", $con);
$query = mysql_query("SELECT max(idNombre)+1 as id FROM nombre");
$row = mysql_fetch_array($query);
$idMax = $row['id'];
$sql = mysql_query("INSERT INTO nombre VALUES ('".$idMax."','".$_POST['comunas']."',".$_POST['giro'].",'".$_POST['nombreCliente']."')");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "record added";
mysql_close($con)
?>

You're inserting the ID in single quotes:
$sql = mysql_query("INSERT INTO nombre VALUES ('".$idMax."','".$_POST['comunas']."',".$_POST['giro'].",'".$_POST['nombreCliente']."')");
Can you provide the table structure? ID is an integer or a varchar there?

Try changing test_action.php to:
<?php
$con = mysql_connect("localhost", "name", "pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("data_base", $con);
$query = mysql_query("SELECT max(idNombre)+1 as id FROM nombre");
$row = mysql_fetch_array($query);
$idMax = $row['id'];
$query = "INSERT INTO nombre VALUES ('".$idMax."','".$_POST['comunas']."',".$_POST['giro'].",'".$_POST['nombreCliente']."')";
$sql = mysql_query($query);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error().'<br>query: '.$query);
}
echo "record added";
mysql_close($con);
?>
It helps for debugging

Related

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>

updating database update

I am having trouble getting the database to update. Is there something wrong with my sql update statement? I checked the sql statement and it says that there were no records in the database. I am not sure what to do.
<!-- template for mySql database access. -->
<!DOCTYPE html>
<html>
<head>
<title>CRUD</title>
<link href="/sandvig/mis314/assignments/style.css" rel="stylesheet" type="text/css">
</head>
<div class="pageContainer centerText">
<h3>CRUD (Create, Read, Update, & Delete) Database</h3>
<?php
//include database connection
include("DatabaseConnection2.php");
//connect to database
$link = fConnectToDatabase();
//Retrieve parameters from querystring and sanitize
$nameF = fCleanString($link, $_GET['nameF'], 15);
$nameL = fCleanString($link, $_GET['nameL'], 15);
$deleteID = fCleanNumber($_GET['deleteID']);
$updateID = fCleanNumber($_GET['updateID']);
$updateID2 = fCleanNumber($_GET['updateID2']);
//Populate Textbox
if (!empty($updateID)) {
$sql = "SELECT NameL, NameF
FROM customertbl
WHERE custID = '$updateID'";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
$row = mysqli_fetch_array($result);
$strFName2 = $row[NameF];
$strLName2= $row[NameL];
}
?>
<hr>
<form class="formLayout">
<div class="formGroup">
<label>First name:</label>
<input name="nameF" type="text" autofocus value="<? echo $strFName2; ?>">
</div>
<div class="formGroup">
<label>Last name:</label>
<input name="nameL" type="text" value="<? echo $strLName2; ?>">
</div>
<div class="formGroup">
<label> </label>
<button>Submit</button>
<input type="hidden" name="updateID2" value="<? echo $updateID; ?>">
</div>
</form>
<?php
//Update
if (!empty($updateID2))
{
$sql = "UPDATE customertbl
SET NameL = '$strFName2', NameF ='$strLName2'
WHERE custID = '$updateID2' ";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
//Insert
if (!empty($nameF) && !empty($nameL)) {
$sql = "Insert into customertbl (NameL, NameF)
VALUES ('$nameL', '$nameF')";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
//Delete
if (!empty($deleteID)) {
$sql = "Delete from customertbl WHERE CustID= '$deleteID' ";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
}
//List records
$sql = 'SELECT custID, NameF, NameL
FROM customertbl order by custID';
//$result is an array containing query results
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
echo "<p>" . mysqli_num_rows($result) . " records in the database</p>";
?>
<table class="simpleTable">
<tr>
<th>Cust. ID</th>
<th>F. Name</th>
<th>L. Name</th>
<th>Delete</th>
<th>Update</th>
</tr>
<?php
// iterate through the retrieved records
while ($row = mysqli_fetch_array($result)) {
//Field names are case sensitive and must match
//the case used in sql statement
$custID = $row['custID'];
echo "<tr>
<td>$custID</td>
<td>$row[NameF]</td>
<td>$row[NameL]</td>
<td><a href='?deleteID=$custID'>Delete</a></td>
<td><a href='?updateID=$custID'>Update</a></td>
</tr>";
}
?>
</table>
</div>
</body>
</html>
The offending code block
//Update
if (!empty($updateID2))
{
$sql = "UPDATE customertbl
SET NameL = '$strFName2', NameF ='$strLName2'
WHERE custID = '$updateID2' ";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
makes references to variables $strFName2 and $strLName2 which are variables that are only populated conditionally.
//Populate Textbox
if (!empty($updateID)) {
$sql = "SELECT NameL, NameF
FROM customertbl
WHERE custID = '$updateID'";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
$row = mysqli_fetch_array($result);
$strFName2 = $row[NameF];
$strLName2= $row[NameL];
}
Since the variables $strFName2 and $strLName2 are undefined during the UPDATE SQL query, you're not seeing the desired results.
The query should reference $nameF and $nameL since those variables are always defined (not contained within a conditional) and the form inputs use nameF and nameL in their name attributes.
$sql = "UPDATE customertbl
SET NameL = '$nameF', NameF ='$nameL'
WHERE custID = '$updateID2';";
You also need to fix your DELETE query to reference the column custID and not CustID as it appears your schema uses the former.
$sql = "Delete from customertbl WHERE custID= '$deleteID' ";

PHP how to insert select box value into database

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>

insert values from multiple checkbox into database PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
handling checked checkboxes PHP
i have this problem. I have a webpage that show car registration number and it's violation. And we can change the status of the violation from 1=not treated to 2=treated. I want to use multiple check box to choose which car registration status that i want to change
here's the screenshot of my web
)
how i change the status of both car registration number ?
here's my webpage code
<div id="content">
<div class="content_item">
<?php
$con = mysql_connect("localhost","fpjarmul","fpjarmul");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("fpjarmul", $con);
$query = "SELECT * FROM laporan WHERE status = '1'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{?>
<form action="ubahdata.php" method="post">
<input type="checkbox" name="idlaporan" value="<?php echo $row['idlaporan'] ?>" /><?php echo "ID : {$row['idlaporan']}" ?><br />
<?php echo "Nomor Polisi : {$row['platkendaraan']} <br>" .
"Status : {$row['status']} <br>" .
"Tanggal Laporan : {$row['tanggallapor']} <br><br>"; ?>
<?php
}
?>
<input type="submit">
</form>
and here's my script
<?php include 'header.php'; ?>
<?php
$con = mysql_connect("localhost","fpjarmul","fpjarmul");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("fpjarmul", $con);
$sql=("UPDATE laporan set status='2' where idlaporan='$_POST[idlaporan]'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
<?php include 'footer.php'; ?>
Please try the following approach:
Change the checkbox 'name' as 'idlaporan[]' (<input type="checkbox" name="idlaporan[]" )
After form submit, selected check box values will be present in the Server side array $_POST['idlaporan']
Use a foreach loop to update values in database.
foreach ($_POST['idlaporan'] as $idlaporan) {
$sql=("UPDATE laporan set status='2' where idlaporan='$idlaporan'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added<br/>";
}

Only one select list works on PHP form

Disclaimer: It's been a while since I last wrote any code. The quality of my code is likely to be sub-par. You've been warned.
I have a basic form that's meant to search flat files on our server. The "search engine" I created as two select lists: one for the file names and one for the customer site files come from.
For a reason I can't figure out, whatever option I select from the second select list is never captured when I hit Submit.
However, whatever option I select from the first select list is always captured.
What am I missing? I am sure it's starting right at me.... Any hints welcome. Thank you.
Here's my code:
<HTML>
<head><title>SEARCH TOOL - PROTOTYPE</title></head>
<body><h1>SEARCH TOOL - PROTOTYPE</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Filename (one item)</legend><select name="DBFilename" id="DBFilename">
<?php $con = mysql_connect("localhost", "user", "pass"); if (!$con) { die('Could not connect: ' . mysql_error());}
mysql_select_db("dev", $con) or die(mysql_error());
$result = mysql_query("select distinct filename from search_test");
while ($row = mysql_fetch_array($result))
{ ?> <option value="<?php echo $row['filename']; ?>"><?php echo $row['filename']; ?></option> <?php } mysql_close($con); ?>
</select></fieldset>
<fieldset>
<legend>Site (one item)</legend><select name="DBSite" id="DBSite">
<?php $con = mysql_connect("localhost", "user", "pass"); if (!$con) { die('Could not connect: ' . mysql_error());}
mysql_select_db("dev", $con) or die(mysql_error());
$result = mysql_query("select distinct site from search_test");
while ($row = mysql_fetch_array($result))
{ ?> <option value="<?php echo $row['site']; ?>"><?php echo $row['site']; ?></option> <?php } mysql_close($con);
?>
</select></fieldset>
<input type="submit" name="submit" value="submit" >
<input type="button" value="Reset Form" onClick="this.form.reset();return false;" />
</form>
</body>
</HTML>
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['DBFilename'])) {doFileSearch();}
elseif (!empty($_POST['DBSite'])) {doSite();}
}
function doFileSearch() {
$mydir = $_SERVER['DOCUMENT_ROOT'] . "/filedepot";
$dir = opendir($mydir);
$DBFilename = $_POST['DBFilename'];
$con = mysql_connect("localhost", "user", "pass");
if (!$con) {die('Could not connect: ' . mysql_error());}
mysql_select_db("dev", $con) or die("Couldn't select the database.");
$getfilename = mysql_query("select filename from search_test where filename='" . $DBFilename . "'") or die(mysql_error());
echo "<table><tbody><tr><td>Results.</td></tr>";
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
echo '<tr><td>' . $filename . '</td></tr>';
}
echo "</table></body>";
}
function doSite() {
$mydir = $_SERVER['DOCUMENT_ROOT'] . "/filedepot";
$dir = opendir($mydir);
$DBSite = $_POST['DBSite'];
$con = mysql_connect("localhost", "user", "pass");
if (!$con) {die('Could not connect: ' . mysql_error());}
mysql_select_db("dev", $con) or die("Couldn't select the database.");
$getfilename = mysql_query("select distinct filename from search_test where site='" . $DBSite . "'") or die(mysql_error());
echo "<table><tbody><tr><td>Results.</td></tr>";
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
echo '<tr><td>' . $filename . '</td></tr>';
}
echo "</table></body>";
}
?>
You have no part of your form with name='submit'
There for you will never get into the if statement that says: if (isset($_POST['submit'])) { because it will always be false
Complete re-re-write here => http://pastebin.com/raw.php?i=qi5F7X2e
There are several problems with my form.
a) Neither one of my SELECT lists are ever empty.
b) I never check for return the values from my functions.
This one is working.
Thanks to all for taking the time.

Categories