There are two php files one contains the form and the other contains the code to insert the form data to the table in a database.
This is the submit form code from the first file
<form name="form" action="insert_dataE.php" onSubmit="return
validation()" method="post" id="formServiceEntry">
<fieldset id="fieldSetServiceEntry">
<legend align="center">Please fill the form</legend>
<p class="FieldHeading"><i>Vehicle No(*): </i></p>
<input id="VehicleNoFieldArea" type="text" name="VehicleNoField"
size="6" maxlength="8"/>
<p class="FieldHeading"><i>Description(*):</i></p>
<textarea id="descriptionFieldArea" name="descriptionField"
rows="2" cols="20" size="15" maxlength="18"></textarea>
<p class="FieldHeading"><i>Total(*):</i></p>
<input id="totalFieldArea" name="totalField" type="text"
size="4" maxlength="4"/>
<p id="amountFieldHeading"><i>Bill(*):</i></p>
<input id="amountFieldArea" name="amountField" type="text"
size="3" maxlength="3" onKeyUp="balance();" />
<br/>
<div id="divisionRadioButton">
<h3 id="radioButtonHeading">Service(*):</h3>
Service
<input class="textFields" type="radio"
name="serviceSelection" value="service" checked />
<br/>
Wash
<input class="textFields" type="radio"
name="serviceSelection" value="wash" />
</div>
<p id="balanceFieldHeading"><i>Balance(*):</i></p>
<input id="balanceFieldArea" name="balanceField" type="text"
size="4" maxlength="4"/>
</fieldset>
<input class="btnsSE" type="submit" name="Button" value="Submit" />
<input class="btnsSE" type="reset" name="Button" value="Reset Form"/>
<input type="button" class="btnsSE" value="Back to the staff
interface" onClick="window.location='staffE.php';"/>
</form>
This is the insert data code from the second file
<?php
// Connects to your Database
$conn=mysql_connect("localhost", "webgeek1_service", "6defyu4642070") or
die(mysql_error());
mysql_select_db("webgeek1_software_order", $conn) or die(mysql_error());
$result = mysql_query("SELECT * FROM application", $conn);
$num_rows = mysql_num_rows($result);
$num_rows = $num_rows + 1;
$id= $num_rows;
$dateAndTime = date('y-m-d H:i:s',time());
$vehicleNo=mysql_real_escape_string($_POST['VehicleNoField']);
$description=mysql_real_escape_string($_POST['descriptionField']);
$amount=mysql_real_escape_string($_POST['amountField']);
$service=mysql_real_escape_string($_POST['serviceSelection']);
// Build an sql statment to add the query details
$sql="INSERT INTO `webgeek1_software_order`.`application`(`serialNo`,
`dateAndTime` , `vehicleNo` , `description` ,`amount`,`service`)
VALUES
('$id',
'$dateAndTime','$vehicleNo','$description','$amount','$service')";
$result = mysql_query($sql, $conn);
if($result)
{
echo "<p id='headingInsertData'>Service Station Web Application</p>";
echo "<p id='receiptHeading'>Receipt</p>";
echo "<div id='mainFieldsInsertData'>";
echo "Serial No: " . " " . $id;
echo "<br/>";
echo "Date and Time: " . " " . $dateAndTime;
echo "<br/>";
echo "Vehicle No: " . " " . $vehicleNo;
echo "<br/>";
echo "Description: " . " " . $description;
echo "<br/>";
echo "Amount: " . " " . $amount;
echo "<br/>";
echo "Service:" . " " . $service;
echo "<br/>";
echo "<br/>";
echo"Thanks for using our services";
echo "</div>";
echo "<div id='footerInsertData'>";
echo "<i>Developed by: Web Geeks - Information Technology (IT)
Company</i>";
echo "</div>";
echo "<div align='center'>";
echo "<input class='btns' type='button' value='Print'
onClick='javascript: window.print();'/>";
echo "<input type='button' class='btns' value='Back to the
Application' onClick='newDoc()'/>";
echo "</div>";
}
else
{
echo "ERROR";
}
// close connection
mysql_close($conn);
?>
The error you're having (Duplicate entry '51' for key 'PRIMARY') seems pretty logical since you're giving your specified ID to row instead of writing automatically. Moreover, you're using ID based off of the amount of rows there currently are. This leads to MySQL error with ID duplication.
To solve this issue:
Modify serialNo column and tick a checkbox on A_I column (AUTO_INCREMENT). This will make sure you will always have unique ID.
Remove entirely this part in your code:
$result = mysql_query("SELECT * FROM application", $conn);
$num_rows = mysql_num_rows($result);
$num_rows = $num_rows + 1;
$id= $num_rows;
Modify your query:
This is modified already
$sql="INSERT INTO `webgeek1_software_order`.`application` (`dateAndTime`, `vehicleNo`, `description`,`amount`, `service`) VALUES('$dateAndTime', '$vehicleNo', '$description', '$amount', '$service')";
I believe database should automatically set what next ID should come after inserting new data. This will prevent your from getting such errors as ID duplication because you're no longer inserting your own number.
A side note (but important): you should use mysqli or PDO statements because mysql extension is deprecated (and is even removed in PHP 7.0.0).
In the structure for my table in phpmyadmin, I needed to set the column 'serialNo' to AI (Autoincrement) and in the insert data code, I needed to comment the lines:
$num_rows = mysql_num_rows($result);
$num_rows = $num_rows + 1;
$id= $num_rows;
Similarly, I needed to remove the 'serialNo' from the insert query in the same file. At last I needed to comment the lines :
echo "Serial No: " . " " . $id;
echo "<br/>";
in the insert data code
Related
I have a system where people can indicate whether they are attending an event. There are several events to choose from. The events come from the database and have a unique id. Everything works fine, except the event and date can't be posted together. Only when I make a checkbox of the date (or the event) everything neatly posted. A hidden textfield always posts the wrong date or event.
<form action="insert.php" method="post">
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "user", "pass", "db");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM events WHERE datum >= CURDATE() AND toon > 0 ORDER BY datum";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<input type=\"radio\" id=\"datum\" name=\"datum\" value=\" "; echo "" . $row['datum'] . "\" required> ";
echo "<input type=\"checkbox\" id=\"event\" name=\"event\" value=\" "; echo "" . $row['event'] . "\"> ";
print date('l d/m/Y', strtotime($row['datum']));
echo " ";
if(strlen($row['url']) > 0):
echo " <a href=\" " . $row['url'] . " \" target=\"_blank\">";
endif;
echo "" . $row['event'] . "</a>";
echo " " . $row['info'] . "";
echo "<br>";
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
<br><br>
<label for="naam">Naam:</label>
<input type="text" name="naam" id="naam" placeholder="Jouw naam..." required>
<input type="hidden" id="mee" name="mee" value="mee">
<label for="opmerking">Opmerking:</label>
<input type="text" name="opmerking" id="opmerking" placeholder="Eventuele opmerkingen...">
<input type="hidden" id="toon" name="toon" value="0">
<input type="submit" value="Ik ga mee!" class="w3-button w3-black">
</form>
</div>
There are a number of issues
Each input must have a different name, otherwise how are you going to know which one has been entered?
Because you have used escape characters for the double quotes, there is confusion there. To, clarify I have used single quotes inside.
Each id must also be unique
As a suggestion, in the loop
$event = $row['event'];
echo "<input type='radio' id='datum-$event' name='datum-$event' value='' $row['datum'] required> ";
So, now the id and name are unique. When this radio button is selected you will have
$_POST['datum-eventname'];
You dont need two inputs in the loop.
so I have this page that shows today's matches by default, it has this datepicker form
<form method="post">
<p> Select Date:<input id="datepicker" type="text" size="8" /> </p>
<input type="submit" value="Submit" name="usub" />
</form>
<?php
if(isset($_POST["usub"])){ $date = $_POST["datepicker"]; }
else{ $date = date('Y-m-d'); }
$data = mysql_query("SELECT * FROM todaysmatches where matchdate='$date'") or die(mysql_error());
echo $_POST["usub"];
echo "<h4>$today Matches</h4> </br>";
//table
if (mysql_num_rows($data)==0){
echo " No Matches";
echo "</br>";
echo "<h4> Sorry About That Check For other Days Or you can Check the Library</h4>";
}
else{
echo "<table border='1'>
<tr>
<th>Match</th>
<th>Tourmanet</th>
<th>Date</th>
</tr>";
while($info = mysql_fetch_array( $data ))
{
echo "<tr>";
echo "<td>" . $info['curmatch'] . "</td>";
echo "<td>" . $info['tournamentname'] . "</td>";
echo "<td>" . $info['matchdate'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
what I want is if the user choose a date in the form it would go in the query and bring the data associated with that date while keeping today as the default one when they first load the page
You need to quote the datevalue in the query as
SELECT * FROM todaysmatches where matchdate= '$today'
$data = mysql_query("SELECT * FROM todaysmatches where matchdate='$today'")
Now to get the datepicker value you need to change a bit in the form and use name attributes as
<form method="post">
<p> Select Date:<input id="datepicker" type="text" size="8" name="datepicker"/> </p>
<input type="submit" value="Submit" name="usub"/>
</form>
Then in PHP you have do as
if(isset($_POST["usub"])){
$date = $_POST["datepicker"];
}
And use it in the query and in the else part you can have the query to get the data from today's date
NOTE : Make sure that the date you are passing from date picker to query is in proper format.
I am new to PHP and I made a simple program where you can apply your name and age, it will take the data to the database and the table will be added with a new row.
I want to add a new column where you can click "change", only the data from that particular row will show up in a few textboxes and can be changed. when pressing submit I want to use the UPDATE function to update the records.
example/plot:
Mike Towards 23 Change
Tyler Frankenstein 24
Change Sophie Baker 22
Change
I want to change the age of Sophie Baker to 24 so I press Change on that row.
Now I only want to get the data from that row and make some changes.
The code I have this far:
Drawing the table above the input fields and the input:
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<html>
<body>
<br />
<form action="insert.php" method="post"><br />
<input type="text" name="firstname"> Firstname <br />
<input type="text" name="lastname"> Lastname <br />
<input type="text" name="age"> Age
<p><input type="submit"></p>
</form>
</body>
</html>
Parser:
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added to the database";
echo "<p><a href=sql2.php>Back to form</a></p>";
mysqli_close($con);
?>
I have tried a few things, but I cant figure out how to show the content on the row I want to select.
Change the actual data with the update function won't be the problem, so I only need help to get the actual data from the correct row.
you'd need to select with the primary key of that table if any exists. if not you should create one. I assume you have a primary key named PersonID:
$query = "SELECT * FROM Persons WHERE PersonID = '" . ($_GET['PersonID']) . "'";
to add the edit button:
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th><th>Action</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td><a href = '?PersonID=" . $row['PersonID'] . "'>Edit</a></td>";
echo "</tr>";
}
echo "</table>";
I assume you have a column named "id".
you can do the following:
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// when you are in "edit mode" just display the row you will edit row
if (isset($_GET['id'])
$result = mysqli_query($con,"SELECT * FROM Persons where id = ".(int)$_GET['id']);
else
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td><a href='?id=" . $row['id'] . "'>change</a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<html>
<body>
<br />
<form action="update.php" method="post"><br />
<input type="hidden" name="id" value="<?php echo isset($_GET['id']?$_GET['id']:'') ?>" />
<input type="text" name="firstname" value="<?php echo isset($row['FirstName'])?$row['FirstName']:'' ?>"/> Firstname <br />
<input type="text" name="lastname" value="<?php echo isset($row['LastName'])?$row['LastName']:'' ?>"/> Lastname <br />
<input type="text" name="age" value="<?php echo isset($row['Age'])?$row['Age']:'' ?>"/> Age
<p><input type="submit"></p>
</form>
</body>
</html>
update.php (handle both insertion and update):
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['id'])
$sql="UPDATE Persons set FirstName = ?, LastName = ?, Age = ?
WHERE id = ".(int)$_POST['id'];
else
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES (?, ?, ?)";
$sth = mysqli_prepare($con, $sql);
$sth->bind_param($_POST[firstname],$_POST[lastname],$_POST[age]);
if (!$sth->execute())
{
die('Error: ' . mysqli_error($con));
}
echo "1 record ".(isset($_POST['id']?'modified':'added')." to the database";
echo "<p><a href=sql2.php>Back to form</a></p>";
Thanks in advance for any light shed.
I have a mysql database consisting of customers with some fields pertaining to each customer. currently running on one of my lamp servers. There is security risks with my code at the moment, but I plan to get the functionality i'm looking for and then reconfigure the code for a tighter security. At the moment I have an html index file that calls on php script to search mysql database by firstname or lastname. Upon this query it displays a list of users and allows me to modify the user. When I click modify it pulls the correct customer id number, but it is not displaying any current information, nor allowing me to update the info.
To summarize, I would like to search a customer, and it pull up selected fields and show the content and allow me to actively change the data and resend it to the database.
My search.html code:
<html>
<body>
<form action="scripts/search.php" method="post">
Firstname: <input type="text" name="firstname">
<input type="submit">
</form>
<form action="scripts/lastnamesearch.php" method="post">
Lastname: <input type="text" name="lastname">
<input type="submit">
</form>
<form action="scripts/phonenumbersearch.php" method="post">
Phone Number: <input type="text" name="phone">
<input type="submit">
</form>
</body>
</html>
MY search.PHP Script:
//this script allows me to search the database by filling out one of the forms and clicking submit. Each of the forms calls upon it's own individual script, I realize that this is probably cumbersome, due to my lack of coding knowledge.
<?php
$con=mysqli_connect("localhost","root","*****","*******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM customers WHERE `firstname` LIKE '$_POST[firstname]'");
echo "<table border='1'>
<tr>
<th>id</th>
<th>firstname</th>
<th>lastname</th>
<th>phone</th>
<th>address</th>
<th>notes</th>
<th>additional notes</th>
<th>passwords</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['notes'] . "</td>";
echo "<td>" . $row['addnotes'] . "</td>";
echo "<td>" . $row['passwords'] . "</td>";
echo "Modify User";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
My modify.php script:
//this is where I believe one of my problems lie. when I click modify user on the search.php script it calls on this script and it loads the correct user/customer id in the address bar, but it doesn't show any existing data, nor does it update the data that I fill in the cells.
<?php
$con=mysqli_connect("localhost","root","crapola1","Computition");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$mysqli_query = "SELECT * FROM customers WHERE ID = $_get[id]";
$mysqli_result = mysqli_query($mysqli_query);
$customer = mysqli_fetch_array($mysqli_result);
?>
<h1> You are modifying a user</h1>
<form action="<?php echo $SERVER['PHP_SELF']; ?>" method="post">
Firstname<input type="text" name="inputFirstname" value="<?php echo $row['firstname']; ?>" /><br />
Notes<input type="text" name="inputNotes" value="<?php echo $row['notes']; ?>" />
<br />
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
<input type="submit" name="submit" value="Modify" />
</form>
Thanks again,
I've been searching on this topic for about a week now and have pieced together this much, but can't seem to get over this "hump"
$_GET is a super global array . It should be in UPPERCASE.
Change the query on your modify.php here
SELECT * FROM customers WHERE ID = $_get[id] to upper case.
Must be..
SELECT * FROM customers WHERE ID = ".$_GET['id']
Also, It is strictly not advised to pass the $_GET or $_POST parameters directly to your query as it leads to SQL injection. You need to switch over to PreparedStatements
I am trying to sort my results by using a drop down menu. I want to get a value from the drop down and enter it into a MySQL statement by assigning it to a variable. I have tried a few things with no success. Any ideas? Thank you.Before I could pull the data from the table and it displayed correctly. It's just the sorting issue.
<form name="order" method="post">
<select name='order'>
<option value='ORDER BY product_name ASC'>A-Z
<option value='ORDER BY product_name DSC'>Z-A
<input type="submit" value="Submit" />
</select>
</form>
<div id="Products">
<p>
Products:
</p><?php
$con=mysqli_connect("localhost","root","","db_tc");
// Check connection
$order=$_POST['order'];
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tbl_products ORDER BY $order");
while($row = mysqli_fetch_array($result))
{
echo "<div id='item'>";
echo "<div id= 'pic'><img class='pic' src='". $row['product_img'] . "'/></div>";
echo "<div id= 'itemname'><h1> " . $row['product_name'] . "</h1></div>";
echo "<div id= 'price'> <h2>Price:</h2><br>£" . $row['product_price'] . "</div>";
echo "<div id= 'signed'> <h2>Signed:</h2><br>" . $row['product_signed'] . "</div>";
echo "<div id= 'type'> <h2>Type:</h2><br>" . $row['product_type'] . "</div>";
echo "</div>";
}
echo "</table>";
mysqli_close($con);
?>
</div>
well the value you are sending with the $_POST field is "ORDER BY name ASC" and you try to add it to a sql statement which already contains "ORDER BY" clause which might be the problem for you. And I guess it's "DESC" not "DSC"
Have you considered, what would have happened if someone added a single quote to the value of the select field and post that? You should always escape the values you receive from the user. Better if you use prepared statements too.