I am having trouble getting this form to successfully submit the data to the database. I have verified that the database/table exists (schema shown below) and for some reason it's not inserting it into the database. When I try to submit sample data, it doesn't change the page and just sits there. What is going on?
<body>
<?php if($_SERVER["REQUEST_METHOD"] != "POST"){ ?>
<h1>My Favorite Foods</h1>
<form action="index.php" method="post" id="foodForm">
Name: <input type="text" name="foodname" id="nameField"></input><br />
Type: <select name="foodtype" id="typeField">
<option value="fruit">Fruit</option>
<option value="vegetable">Vegetable</option>
<option value="dairy">Dairy</option>
<option value="meat">Meat</option>
<option value="grain">Grain</option>
<option value="other">Other</option>
</select><br />
Number of Calories: <input type="text" name="foodcals" id="calsField"></input><br />
Healthy? <input type="checkbox" name="foodhealth" value="healthy" id="healthyField"></input><br />
Additional Notes:<br />
<textarea name="foodnotes" id="notesField"></textarea><br />
<input type="submit" value="Add" onclick="validateForm();return false;"></input>
</form>
<?php }else{ ?>
<!-- form handling and output printing stuff goes here -->
<?php $insert = "INSERT INTO Foods(Name, Type, NumCals, Healthy, Notes) VALUES ('$_POST[foodname]', '$_POST[foodtype]', '$_POST[foodcals]', '$_POST[foodhealth]', '$_POST[foodnotes]'";
$con = mysqli_connect("localhost","root");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db("mydb");
$result = mysqli_query($con, $insert);
if ($result) {
echo "Food added successfully.";
/*while ($row = mysqli_fetch_array($result)) {
echo $row['Name'] . ", " . $row['Type'] . ", " . $row['NumCals'] . ", " . $row['Healthy'] . ", " . $row['Notes'];
echo "<br>";
} */
} else {
echo "Error adding person";
mysqli_error($con);
}
} ?>
</body>
</html>
Schema:
Foods(PID INT NOT NULL AUTO_INCREMENT,PRIMARY KEY(PID),Name VARCHAR(20),Type VARCHAR(9),NumCals INT,Healthy BOOL,Notes TEXT)
This attribute in the submit button:
onclick="validateForm();return false;"
prevents the form from submitting. return false means that the browser should not perform the default action from clicking the button.
Assuming the validateForm() function returns a boolean indicating whether validation was successful, change that to:
onclick="return validateForm();"
Change:
} else {
echo "Error adding person";
mysqli_error($con);
to:
} else {
echo "Error adding person: " . mysqli_error($con);
So that the error message will be displayed.
And you're missing the ) at the end of your INSERT statement.
Related
I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// 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);
}
?>
This is my db : link link
<?php
$con=mysqli_connect("localhost","root","","organisation");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM org_insert");
echo "<!doctype html>
<html lang=\"en\">
<head>
<!-- Bootstrap CSS -->
<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">
<title>Hello, world!</title>
</head>
<body>
<table border='1'>
<tr>
<th>below_whom</th>
<th>name</th>
</tr>";
$row = mysqli_fetch_array($result);
#echo '<pre>'; print_r($row); echo '</pre>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['below_whom'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<div class="form-group">
<label for="usr">below_whom:</label>
<input type="text" name ="below_whom" id="below_whom" class="form-control">
</div>
<div class="form-group">
<label for="usr">name:</label>
<input type="text" name ="name" id="name" class="form-control">
</div>
<form method="post">
<input type="button" name="submit" id="submit" class="btn btn-primary" value="submit"/>
</form>
<?php
$con=mysqli_connect("localhost","root","","organisation");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit']))
{
if($below_whom !=''||$name !=''){
$below_whom=$_POST['below_whom'];
$name=$_POST['name'];
$query=mysqli_query("INSERT INTO org_insert VALUES ('$below_whom','$name');");
$query_run = mysqli_query($con,$query);
echo "<p>query inserted.</p>";
}else{
echo "<p>Insertion Failed.</p>";
}
}
mysqli_close($con);
echo"</body>
</html>";
?>
The text under p tag isn't getting executed, ie, the program is not going inside the if statement itself. I have rechecked the syntax, what is the problem? Is the syntax incorrect? I am pretty sure the connection with sql is correct. I have also refereed to some articles, still I am stuck here.
use post variables before if loop as shown below
if(isset($_POST['submit']))
{
$below_whom=$_POST['below_whom'];
$name=$_POST['name'];
if($below_whom !=''||$name !=''){
$query=mysqli_query("INSERT INTO org_insert VALUES ('$below_whom','$name');");
$query_run = mysqli_query($con,$query);
echo "<p>query inserted.</p>";
}else{
echo "<p>Insertion Failed.</p>";
}
}
and in HTML Code add type as submit and start form tag before div as
<form method="post" action=""> and closes after input tag
<input type="submit" name="submit" id="submit" class="btn btn-primary" value="submit"/>
One of the issues that I am able to see is that Your query should be:
$query=mysqli_query("INSERT INTO `org_insert`(`below_whom`,`name`) VALUES ('$below_whom','$name')");
Hope this helps.
Change the mysqli_fetch_array to mysqli_fetch_assoc or add a parameter too
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
I want to show data from a Oracle database into a listbox.
, but I don't no how to do that.
Now I'm using a textbox and that works good.
This is my HTML code
<form name="form1" method="get" action="Get_opdracht.php"
Opdrachtnummer: <br /> <input id="Password1" type="number" name="nummer1" required="required"/>
<input type="submit" name="submit1" value="Zoeken" />
<hr />
</form>
PHP code (get_opdracht.php)
// database connect
$conn = oci_connect('username', 'password', 'connect');
// variable textbox
$username = $_GET['nummer1'];
// SELECT query
$array = oci_parse($conn, "SELECT * FROM OPD_VW, MDW_VW WHERE OPD_OPDRACHTNUMMER = '$username'");
$query = oci_execute($array);
//show data on page
while (($row = oci_fetch_array($array, OCI_BOTH)) != false) {
echo "<h1>Opdrachtnummer: " . $row['OPD_OPDRACHTNUMMER'] . "</h1><p> <b>Status: </b>" . $row['OPD_STATUS'] . "<p><b>Registratiedatum: </b>" . $row['OPD_REGISTRATIEDATUM'] . "<p><b>Einddatum: </b>" . $row['OPD_EINDDATUM'] . "<p><b>BTW tarief: </b>". $row['OPD_BTW_TARIEF'] . "<p><b>Totale contractsom: €</b>" . $row['OPD_TOTALE_CONTRACTSOM'] . "<p><b>Percentage gerealiseerd: </b>" . $row['OPD_PERCENTAGE_GEREALISEERD'] . "%";
oci_free_statement($array);
oci_close($conn);
To create a listbox you need to use the select multiple as shown below.
<select name="myselect" multiple="multiple">
<option value="value">OPTION</option>
<option value="value">OPTION</option>
</select>
I'm trying to make a form that will allow a user to edit records in the database.
My main.php is a table where the user can click on a record to edit / delete:
echo "<td>".$row["fname"].", ".$row["first_name"]."</center></td>";
echo "<td><center>".$row["gender"]."</center></td>";
echo "<td><center>".$row["city"]."</center></td>";
echo "<td><center>".$row["extra"]."</center></td>";
echo '<td><center><img src="edit_icon.png"/><center></td>';
echo '<td><center><img src="delete.gif"/><center></td>';
echo "</tr>";
}
?>
<input type="hidden" name="p_ID" value="<?php echo $row["p_ID"]?>"></input>
<input type="hidden" name="lname" value="<?php echo $row["lname"]?>"></input>
etc..
When the user clicks the edit icon, it redirects to the form page where I need the values ($row['fname']) to show up in their respective fields. I've tried suggested solutions but I still don't know how to accomplish this correctly. I keep getting errors. This is what I've tried with my form.php
#$submit=$_POST['submit'];
#$lname=$_GET['lname'];
#$gender=$_GET['gender'];
#$city=$_GET['city'];
#$extra=$_GET['extra'];
?>
Last name <input type="text" name="lname" value= <?php echo $lname ?>><br><br>
Gender <input type="radio" name="gender" value="M" <?php if($gender=="M") {echo "checked";} else {echo " ";} ?>/>M
<input type="radio" name="gender" value="F" <?php if($gender=="F") {echo "checked";} else {echo " ";} ?>/>F<br><br>
City <select name="city">
<option value="x">Select</option>
<?php
$db=mysql_connect("localhost","root") or die('Not connected : ' . mysql_error());
mysql_select_db("my_db",$db) or die (mysql_error());
$SQL="SELECT * FROM cities";
$result=mysql_query($SQL) or die(mysql_error());
$num_results=mysql_num_rows($result);
mysql_close($db);
for ($i=0;$i<$num_results;$i++)
{
$row=mysql_fetch_array($result);
echo"<option value='".$row['city_id']."'", $row['city_id']==$row['city_ID']? " selected='selected'" : '',">".$row['city']."</option>";
}
?>
</select><br><br>
Extra <input type="checkbox" name="extra" value="yes" <?php if($extra=="yes") {echo "checked";} else {echo " ";} ?>/><br><br>
And I'm not really concerned with any SQL injections or anything right now, I just need this working. I'd be grateful for any help!
Errors: Undefined index for everything
You are closing the connection before mysql_query is used in mysql_fetch_array.
You are trying to fetch the rows incorrectly.
mysql_close isn't needed unless you have a lot of processing after the query because the connection is closed after the script has finished running anyway.
Also, declare your variables like this to remove the undefined index errors:
$submit = isset($_POST['submit']) ? mysql_real_escape_string($_POST['submit']) : "";
Note: this also protects against sql injection but mysql_real_escape_string() will only work after you connect.
<?php
$db=mysql_connect("localhost","root") or die('Not connected : ' . mysql_error());
mysql_select_db("my_db",$db) or die (mysql_error());
$submit = isset($_POST['submit']) ? mysql_real_escape_string($_POST['submit']) : "";
//other vars here
$SQL="SELECT * FROM cities";
$result=mysql_query($SQL) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['city_id']."'>".$row['city']."</option>";
}
mysql_close(); // now you can close the connection
?>
What you need is form submission check. Here is the general form of a single-page update script:
<?php
if(isset($_POST['submit'])) {
// Form was submitted, process it and display message
exit(); // Prevent form from being displayed again
}
?>
<!doctype html>
<html>
<body>
<form method="POST" action="form.php">
<!-- fields -->
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
I have written the code to connect the database in the following form
insert.php
<html>
<body>
<?php
$conn=new mysqli('localhost','root','');
if($conn->connect_error){
die("connection failed" .$conn->connect_error);
}
echo "DB connected successfully";
mysqli_select_db($conn,"namesql_db");
echo "\n DB is selected as Test successfully";
$sql="INSERT INTO namesql_table(age,fwaist) VALUES('$_POST[age]','$_POST[fwaist]')";
if($conn->query($sql)===TRUE){
echo "New record created successfully";
} else {
echo "Error:" .$sql."<br>" .$conn->error;
}
mysqli_close($conn);
?>
</body>
</html>
And i have written the code for age and waist like:
</head>
<body bgcolor="lightyellow" text="black" style="font-size:18pt; font-family:Garamond"><center>
<h2>DIABETES RISK SCORE SYSTEM</h2></center>
<form action="insert.php" method="post">
<label for="age">Enter your Age: </label>
<select name="age">
<option value="">--select the age--</option>
<option value="21-34">21-34</option>
<option value="35-49">35-49</option>
<option value="50-80">50-80</option>
</select>
<p></p>
<script>
var select = document.querySelector('select');
var para = document.querySelector('p');
select.onchange = setage;
function setage() {
var choice = select.value;
if(choice === "21-34") {
para.textContent = 'The score is 0';
} else if(choice === "35-49") {
para.textContent = 'The score is 22';
} else if(choice === "50-80") {
para.textContent = 'The score is 34';
} else {
para.textContent = '';
}
}
</script>
<br/><br/><img src="age1.jpg" align="right" width="300" height="300">
<input type="submit"/>
</form>
BACK
NEXT
while developing the UI using this code am getting the score.For example if i click the age 21-34 am getting the score as 0.But in database am getting only the category as 21-34 am not getting score..Can anybody tell me ...
Thanks in advance