I have an issue where I need to be able to use check boxes in order to delete and modify data in a mysql database.
What is the most efficient way of being able to use multiple submit buttons to either insert data based on what the user types into the text boxes, delete based on the check boxes selected, and modify based on the check boxes selected.
Here is the code I have so far:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Auto,Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
</table>
<tr><td><input type="submit" name="create" value="Add"/></td></tr>
<tr><td><input type="submit" name="delete" value="Delete"/></td></tr>
<tr><td><input type="submit" name="modify" value="Modify"/></td></tr>
</table>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info['Auto'];
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
if (isset($_POST['create'])) {
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
}
elseif (isset($_POST['delete'])) {
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql_delete = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result_delete = mysql_query($sql_delete);
}
if ($result_delete) {
echo $result_delete;
}
else {
echo "fail";
}
}
elseif (isset($_POST['modify'])) {
header('Location: modify_ticket.php');
}
mysql_close($conn);
?>
</form>
</BODY>
</HTML>
Insert.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
#header( 'Location: ticket_history.php' );
?>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result = mysql_query($sql);
}
header( 'Location: ticket_history.php' );
?>
Any help is appreciated!
Thank you!
Another way to do it is your submit button's have the same name,
So:
<input type="submit" name="submit" value="Delete" />
<input type="submit" name="submit" value="Edit" />
PHP:
switch(strtolower($_POST['submit'])){
case "delete":
// delete logic
break;
case "edit":
// edit logic
break;
}
I would take the insert and delete code and put it on top of the main file instead of having them into files. the simplest way would be to submit the form to itself and based on the submit button clicked run the code block
if($_POST['create']){
// insert code
}
elseif($_POST['delete']){
// delete code
}
continue the logic of if/else/elseif to handle all the cases. This strikes me as the simplest way to get done what you want to do.
Edit:
Not sure but seems like you are handling the $_POST['create'] etc after the HTML code. You should always do that sort of processing BEFORE the html rendering and even before the query to get the records you want to display, this way your get query will always bring up to date results.
When you use multiple submit buttons, you can use PHP to determine which button was pressed. Based on this, you can have your application do different things with the data.
It's not clear what you want to accomplish with multiple buttons. Perhaps you could give more detail.
[Edit]
Looking over your code in detail, it is plain to see that it is quickly becoming a maintenance nightmare. Even if your app is tiny and you don't want to code use MVC pattern, you I still recommend using classes and separating presentation from application logic and from data access. Then it's much easier to maintain the application(fix bugs) and make changes.
If you are building anything more than a trivial script, I recommend using one of the excellent PHP frameworks:
http://framework.zend.com/
http://www.symfony-project.org/
http://codeigniter.com/
http://cakephp.org/
and many more: http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#PHP
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Auto,Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
if (isset($_POST['create'])) {
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
}
elseif (isset($_POST['delete'])) {
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql_delete = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result_delete = mysql_query($sql_delete);
}
if ($result_delete) {
echo $result_delete;
}
else {
echo "fail";
}
}
elseif (isset($_POST['modify'])) {
header('Location: modify_ticket.php');
}
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
</table>
<tr><td><input type="submit" name="create" value="Add"/></td></tr>
<tr><td><input type="submit" name="delete" value="Delete"/></td></tr>
<tr><td><input type="submit" name="modify" value="Modify"/></td></tr>
</table>
</table>
I modified the code a little bit and THIS WILL WORK; however, it only works on the SECOND click.
When I select something and click DELETE, it will not delete, but when I do it again it will
Why is this? Thoughts?
Take the code for deletion and insertion above the select, so that the desired deletion of updation is done before you show the data.
Related
I have two tables in one database. The first one is the g1 where the buttons' data is located. The second is the gradeone, where the enrollees' data is located. I want to display the data from the table "gradeone" by clicking the
specific buttons.
Assuming that I added 2 sections. Section 1 and section 2. I click the button section1. By clicking it, I want to display the data of the enrollee from table "gradeone" where the section is 1.
<?php
$dsn = 'mysql:host=localhost;dbname=admin';
$username = 'root';
$password = '';
try{
// Connect To MySQL Database
$con = new PDO($dsn,$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo 'Not Connected '.$ex->getMessage();
}
$sectionnumber ="";
$datasuccess ="";
$error ="";
function getPosts(){
$posts = array();
$posts[1] = $_POST['sectionnumber'];
return $posts;
}
if(isset($_POST['add'])){
$data = getPosts();
if(empty($data[1])){
$error = 'Enter The User Data To Insert';
}else {
$insertStmt = $con->prepare('INSERT INTO g1(sectionnumber) VALUES(:sectionnumber)');
$insertStmt->execute(array(
':sectionnumber'=> $data[1]
));
if($insertStmt){
$datasuccess = "<font color='#f8234a'>New added</font>";
}
}
}
?> //Code for adding a button
<?php
require 'connection.php';
$sql = "SELECT sectionnumber FROM g1";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<button type='button' class='btn'>Section " . $row["sectionnumber"] . "</button></a><hr>";
}
} else { echo "<B>No Sections</B>"; }
$con->close();
?> //Code for displaying the button
<html>
<body>
<form action=">
<input type="number" name="sectionnumber">
<input type="submit" name="add">
</form>
</body>
</html>
I'm trying to make a PHP web application display the data from specific Countries from a dropdown but I can't figure it out how to use the WHERE [Column] = [Value1, Value2, Value3] on a PHP dropdown.
I'm using the "Adventure Works 2014 Full Database Backup" for test purpose.
<html>
</body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';
$connectionInfo = array( 'UID'=>$uid,
'PWD'=>$pwd,
'Database'=>$databaseName);
$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){
echo '';
}else{
echo 'Connection failure<br />';
die(print_r(sqlsrv_errors(),TRUE));
}
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo "<option value=";
echo $data['BusinessEntityID'];
echo ">";
echo $data['BusinessEntityID'];
echo "</option>";
}
?>
<input type="submit" value="Select Tower">
</select></br></br>
</form>
</body></html>
<?php
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$_SESSION['tower'] = $_POST['TowerSelect'];
echo "<tr>";
echo $_SESSION['tower'];
echo " selected. </p>";
echo('<td>'.$row['BusinessEntityID'].'</td><td>'.$row['FirstName'].'</td></tr>');
}
I believe I have this fixed. There were a number of problems with the code. You were referencing a $row but there was no SQL query that would have resulted in a $row, you were trying to post data after the closing HTML tag, you were trying to create rows for a table without declaring the table, and a few other things. Some of this was probably a result of quickly creating the test case. No problem. Try this...
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';
$connectionInfo = array( 'UID'=>$uid,'PWD'=>$pwd,'Database'=>$databaseName);
$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){echo '';}else{echo 'Connection failure<br />';die(print_r(sqlsrv_errors(),TRUE));}
?><html><body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo '<option value="'.$data['BusinessEntityID'].'">';
echo $data['BusinessEntityID'];
echo "</option>";
}
?><input type="submit" value="Select Tower">
</select></br></br>
</form>
<table cols="3" cellpadding="0" cellspacing="0" border="0">
<?php
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE BusinessEntityID = '".$_POST['TowerSelect']."'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($row=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
$_SESSION['tower'] = $_POST['TowerSelect'];
echo '<tr><td>'.$_SESSION['tower'].' selected.</td>';
echo '<td>'.$row['BusinessEntityID'].'</td>';
echo '<td>'.$row['FirstName'].'</td></tr>';
}
}
?></table></body></html>
Note: Though not important to answer your question, it is a best practice to use PDO and bound paramters when making database calls to protect yourself against SQL injection and other nasties. I recommend you look into it to protect your database. Cheers!
Ok, I got the solution, my select was wrong
$sql = "SELECT DISTINCT CountryRegionName FROM dbo.vKelvin ORDER BY CountryRegionName";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo '<option value="'.$data['CountryRegionName'].'">';
echo $data['CountryRegionName'];
echo "</option>";
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE BusinessEntityID = '".$_POST['TowerSelect']."'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($row=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
$_SESSION['tower'] = $_POST['TowerSelect'];
echo '<tr><td>'.$_SESSION['tower'].' selected.</td>';
echo '<td>'.$row['BusinessEntityID'].'</td>';
echo '<td>'.$row['FirstName'].'</td></tr>';
}
}
i am a newbie in php programming and i cant figure out where i have gone wrong as my php code wont execute.
As the title says i am trying to create check boxes in my site however the values will come from the mysql database.
I have a table named “campus” in MySQL database and it has 2 coloumns called id and room.
database
[![Database][1]][1]
http://i.imgur.com/uLP6niJ.png
current output
[![Current Output][2]][2]
http://i.imgur.com/cSOYPme.png
below is my code:
<?PHP
$hostname = "localhost";
$username = "root";
$password = "root";
$databaseName = "my computer";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$s = '';
$j = 0;
if ($q = $connect->query("SELECT * FROM `campus`")) {
while ($line = $q->fetch_assoc()) {
$s.= '<input type="checkbox" name="car'.$j.'" value="'.$line['room'].'">';
}
}
echo $s;
?>
</form>
</body>
</html>
You're not closing the while loop properly. Close the while loop as follow.
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="checkbox" name="car" value="<?php echo $line['room']?>" />
<?php
}
?>
Welcome to PHP!
An error is that you're missing the semicolon that's needed after any php function (such as echo)
<?php echo $line['room']; ?>
And there's the missing PHP tags around the closing }
A third error is that you're not telling mysqli which connection to run the query on it should have:
mysqli_query($dbCon, $sql);
Apart from that it looks good, personally I prefer to use a PDO connection but mysqli is still good, but there are a few formatting tricks that can help prevent problems.
For example it's always a good idea to use back-ticks (`)
So:
$sql = "SELECT `room` FROM `campus`";
However, for this it might be best to use the * query. Which selects everything from the column so:
$sql = "SELECT * FROM `campus`";
The reason is how you're getting the data, you're telling PHP to create an array using the results.. but you've only given it one piece of data for each row. So if you give it all of the data it just makes it a little easier to use.
Here's the full code:
<?php $dbCon = mysqli_connect("localhost", "root", "root", "my computer");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$sql = "SELECT * FROM `campus`";
$result = mysqli_query($dbCon, $sql);
while ($line = mysqli_fetch_array($result, MYSQL_ASSOC)) { ?>
<input type="checkbox" name="car" value="<?php echo $line['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Also, if you're interested, here's how it'd be done in PDO:
<?php
try{
$con = new \PDO("mysql:host=" . 'localhost' . ";dbname=" . 'My Computer', 'root', 'root');
}catch(PDOException $e){
echo "Connection Failed";
die();
} ?>
<html>
<body>
<form name="aform">
Choose a room:
<?php
$result = $con->prepare("SELECT * FROM `campus`")
$result->execute();
while ($row = $result->fetch()) { ?>
<input type="checkbox" name="car" value="<?php echo $row['room']; ?>"
<?php } ?>
</form>
</body>
</html>
Still not working? Feel free to comment and I'll see what's up :)
Thanks,
P110
Try with this
<?php
$sql = "SELECT room FROM campus";
$result = mysqli_query($sql);
$campusArray = mysqli_fetch_array($result, MYSQLI_ASSOC);
foreach ($campusArray as $campus): ?>
<input type="checkbox" name="car" value="<?php echo $campus['room'];?>" />
<?php endforeach; ?>
I hope with this you can solve your problem.
alternative syntax is excellent for improving legibility (for both PHP
and HTML!) in situations where you have a mix of them.
http://ca3.php.net/manual/en/control-structures.alternative-syntax.php
I am trying to add in a new row to a MySQL table. It is reading me the error Could not enter data: Column count doesn't match value count at row 1 . So far, I am using the code
if(! get_magic_quotes_gpc() )
{
$job_pos = addslashes ($_POST['job_pos']);
}
else
{
$job_pos = $_POST['job_pos'];
}
$job_pos_sort = "SELECT LAST(job_pos_sort) FROM careers;" + 1;
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())";
to insert a new row into the table.
Here is my entire code for the page, my page can be seen at http://thetotempole.ca/phptester/upanddowntest.php :
<?php
// connect to db
$conn = mysql_connect("xxxx","x","x","x") or die(mysql_error());
$db = mysql_select_db('x',$conn) or die(mysql_error());
// if an arrow link was clicked...
if ($_GET['dir'] && $_GET['id']) {
// make GET vars easier to handle
$dir = $_GET['dir'];
// cast as int and couple with switch for sql injection prevention for $id
$id = (int) $_GET['id'];
// decide what row we're swapping based on $dir
switch ($dir) {
// if we're going up, swap is 1 less than id
case 'up':
// make sure that there's a row above to swap
$swap = ($id > 1)? $id-- : 1;
break;
// if we're going down, swap is 1 more than id
case 'down':
// find out what the highest row is
$sql = "SELECT count(*) FROM careers";
$result = mysql_query($sql, $conn) or die(mysql_error());
$r = mysql_fetch_row($result);
$max = $r[0];
// make sure that there's a row below to swap with
$swap = ($id < $max)? $id++ : $max;
break;
// default value (sql injection prevention for $dir)
default:
$swap = $id;
} // end switch $dir
// swap the rows. Basic idea is to make $id=$swap and $swap=$id
$sql = "UPDATE careers SET job_pos_sort = CASE job_pos_sort WHEN $id THEN $swap WHEN $swap THEN $id END WHERE job_pos_sort IN ($id, $swap)";
$result = mysql_query($sql, $conn) or die(mysql_error());
} // end if GET
// set a result order with a default (sql infection prevention for $sortby)
$sortby = ($_GET['sortby'] == 'job_pos')? $_GET['sortby'] : 'job_pos_sort';
// pull the info from the table
$sql = "SELECT job_pos_sort, job_pos FROM careers ORDER BY $sortby";
$result = mysql_query($sql, $conn) or die(mysql_error());
// display table
echo "<table border = '1'>";
echo "<tr>";
// make column names links, passing sortby
echo "<td><a href='{$_SERVER['PHP_SELF']}?sortby=job_pos_sort'>job_pos_sort</a></td>";
echo "<td><a href='{$_SERVER['PHP_SELF']}?sortby=job_pos'>job_pos</a></td>";
echo "</tr>";
// display data 1 row at a time
while ($r = mysql_fetch_assoc($result)) {
echo "<tr>";
// make the links to change custom order, passing direction and the custom sort id
echo "<td align = 'center'><a href='{$_SERVER['PHP_SELF']}?dir=up&id={$r['job_pos_sort']}'>/\</a> ";
echo "<a href='{$_SERVER['PHP_SELF']}?dir=down&id={$r['job_pos_sort']}'>\/</a></td>";
echo "<td>{$r['job_pos']}</td>";
echo "</tr>";
} // end while $r
echo "</table>";
// end display table
?>
<html>
<head>
<title>Manage Careers</title>
</head>
<body>
<?php
if(isset($_POST['add']))
{
$dbhost = 'x';
$dbuser = 'xx';
$dbpass = 'xx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$job_pos = addslashes ($_POST['job_pos']);
}
else
{
$job_pos = $_POST['job_pos'];
}
$job_pos_sort = "SELECT LAST(job_pos_sort) FROM careers;" + 1;
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())";
mysql_select_db('x');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Job Position</td>
<td><input name="job_pos" type="text" id="job_pos"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="add" type="submit" id="add" value="Add Job Position">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
Any help is appreciated.
Regards,
Kelsey
I don't know what you are expecting to happen when specifying 2 columns, and trying to add 3
"INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())
Googling the error would help you. It exactly tells what you are getting wrong.
columns job_pos, job_pos_sort, but values - job_pos, job_post_sort and NOW(). You might have to specify the last column, which seems to be a datetime one
I hope you also are aware the $job_pos_sort is just a string, and want evaluate to anything, especially with adding 1 to the string (it may rise an error too)
And, you'd better switch to one of the modern DB API's regarding mysql - mysqli or PDO.
http://www.php.net/manual/en/mysqlinfo.api.choosing.php
you should run this :
SHOW COLUMNS FROM careers;
then maybe we know the name of the field missing here xxxxxx
it must be a sort of date.
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort, xxxxxx) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())";
or simply try this:
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort')";
this should work
i have a php page called page1.php with this form
<form id="myForm" action="page2.php" method="post">
<label for="name">a label:</label><input type="submit" name="SubmitCar" value="Done" id="fbutton" /> <br />
<br />
<select name="selectCar">
<?php
session_start();
$user = "cardatabase";
$password = "";
$host = "";
$database = "my_cardatabase";
$connessione = mysql_connect($host, $user, $password) or die( mysql_error() . " <br/> could not connect to server");
mysql_select_db($database, $connessione) or die( mysql_error() . " <br/> could not connect datbase");
$id = $_SESSION['myid'];
$query = "select IDCar
from Car";
$result = mysql_query($query, $connessione) or die(mysql_error());
if( mysql_num_rows($result) > 0 ) {
$array = array();
$i = 0;
while ($row = mysql_fetch_array($result)) {
$array[$i] = $row['IDCar'];
++$i;
}
for ($i = 0; $i < count($array); ++$i) {
echo "<option value='$array[$i]'>$array[$i]</option>";
}
}
mysql_close();
?>
</select>
</form>
Simply fill the select box from DB. Now here's the problem. When i reach page2.php i need the value of the select box and i tried this
page2.php
<?php
$value = $_POST['selectCar'];
?>
But it's not working, so i tried to use sessions in this way
page1.php
</form>
<?php
if(isset($_POST['SubmitCar'])){
$_SESSION['idAuto'] = $_POST['selectCar'];
}
?>
out of the form, but still not working. What can i do to get this value in page2.php??
Try using this code to build your <option> , and use mysqli when working with the database
$result = mysqli_query($connessione, $query) or die(mysql_error());
if( mysqli_num_rows($result) > 0 ) {
$i=0;
while ($row = mysqli_fetch_row$result)) {
echo "<option value='".$row[$i]."'>".$row[$i]."</option>";
$i++;
}
}
Also, it's not indicated to have mysql tables with names in uppercase, or fields with names in uppercase.
Page2.php
You forgot to echo it.
<?php
$value = $_POST['selectCar'];
echo $value;
?>
I found a simple workaround for my problem. It might not be perfect but it works.
i deleted the action="page2.php" in the form of page1
in page1.php add this code outside the form
This will do the trick
if(isset($_POST['SubmitCar'])){
$_SESSION['idCar'] = $_POST['selectCar'];
header('Location:page2.php');
}