I have a VERY simple form that is not working. What I am trying to accomplish is when the user clicks the update button, they are presented with a form filled in with the information. When they change the information and click update, they are sent back to the main form with all of their changes presented. Everything works but the update. When you change something and click update, nothing is changed. Here is the update form code:
<h4>Update Record</h4>
<?PHP
$con=mysqli_connect("localhost", "root", "", "customers");
//check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
?>
<form action="update_process.php" method="get">
Band: <input type="text" name="artist" value="<?php echo $_GET['artist'] ?>"/><br/>
Album: <input type="text" name="title" value="<?php echo $_GET['title'] ?>" /><br/>
Format: <select name="format">
<option value="Compact Disc" name="compact disc">compact disc</option>
<option value="Album" name="album">album</option>
<option value="Cassette" name="cassette">cassette</option>
<option value="MP3" name="mp3">mp3</option>
</select><br/>
Notes: <TEXTAREA NAME="notes" ROWS="3" COLS="30"><?php echo $_GET['notes'] ?>
</TEXTAREA><br/>
<input type="submit" value="Update" />
</form>
And here is the code for the update_process.php file:
<?php
$artist = $_GET['artist'];
$title = $_GET['title'];
$format = $_GET['format'];
$notes = $_GET['notes'];
//create connection to DB
$con=mysqli_connect("localhost", "root", "", "customers");
//check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "UPDATE music SET title='$title', artist='$artist', format='$format', notes='$notes'
WHERE id='$id'";
if ($con->query($sql) === TRUE) {
header('Location:index.php');
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
?>
In the WHERE clause you says where id = '$id', but where is the $id value set?
I think $id does not have a value.
I see some problems with your code:
1 - where id $id defined?
2 - I guess id is an integer field, so the 's around $id are not needed;
You've mixed object based and function based programming. You started with function based, so I'll show you that way. To query a database, you need to run:
mysqli_query($con,$sql);
Rather than:
$con->query($sql)
There are a few other problems security wise with your code, but skip the rest of my answer if you don't care.
You're not checking to see whether those GET parameters exist before you use them. Use:
if(isset($_GET['artist'],$_GET['track'],...)) {...}
You're also not escaping your query strings, making your site vulnerable to SQL injection. Use:
$artist = mysqli_real_escape_string($con,$_GET['artist']);
Good luck! Just go read the PHP docs, making sure you either take object or function approach for the entire script.
Related
I have a database called school with a table called persons. On my PHP/HTML form I have a selector option with a drop down. I want to pass the value of the drop down into my database.
I thought the below would work, single option is only available. Can anyone see where I am going wrong? DI feel I need to store the value somewhere but Im not sure its even been captured.
index.php
<form action="insert.php" method="post">
<div>
<div>
<div>
<div><label for="Criticality">Criticality</label><select name="critical">
<option value="Critical">Critical</option>
<option value="Important">Important</option>
<option value="Support">Support</option>
<option value="Non Critical">Non Critical</option>
</select></div>
<button type="submit" value="Submit">Submit</button>
</div>
</div>
</div>
</form>
insert.php
<?php
$link = mysqli_connect("127.0.0.1", "root", "password", "school");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$critical = mysqli_real_escape_string($link, $_REQUEST['critical']);
$sql = "INSERT INTO persons (critical) VALUES ('$critical')";
if(mysqli_query($link, $sql)){
header("Location: success.html");
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
How can I loop through results of a MySQL query and display them in option values in the html form in my script.
I have tried putting the values manually into the option tags and values, but I want to do it depending on whats already inside the database. Do I need another connection to the database to run in the same part as the form element itself?
<title>Add a unit</title>
</head>
<body>
<div class= "container">
<h1>Add a unit</h1>
<?php // Script 12.4 - add_size.php
// This script adds a blog size to the database.
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form.
// Connect and select:
$connection = mysqli_connect('localhost', $user, $password, $database);
mysqli_set_charset($connection, 'utf8');
// Validate the form data:
$problem = false;
if (!empty($_POST['unit']) && !empty($_POST['size']) && !empty($_POST['price'] && isset($_POST['building'])) {
$unit = mysqli_real_escape_string($connection, trim(strip_tags($_POST['unit'])));
$size = mysqli_real_escape_string($connection, trim(strip_tags($_POST['size'])));
$price = mysqli_real_escape_string($connection, trim(strip_tags($_POST['price'])));
$building = mysqli_real_escape_string($connection, trim(strip_tags($_POST['building'])));
} else {
echo '<p style="color: red;">Please submit a unit and an size and price.</p>';
}
if (!$problem) {
// Define the query:
$query = "INSERT INTO individualspecs (Space, Size, Price, fk_Id, Id) VALUES ('${unit}', '${size}', '${price}', '${building}', 0)";
// Execute the query:
if (#mysqli_query($connection, $query)) {
echo '<p>The unit has been added!</p>';
// why doesnt print "$msg"; work when using $i
} else {
echo '<p style="color: red;">Could not add the unit because:<br>'.mysqli_error($connection).'.</p><p>The query being run was: '.$query.'</p>';
echo $msg;
}
mysqli_close($connection); // Close the connection.
} // No problem!
} // End of form submission IF.
// Display the form:
?>
<form action="add_units.php" method="post" enctype="multipart/form-data">
<p>Select Building: <select name="building">
<option value="<?php echo ?>"><?php echo ?></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</p>
<p>Enter Unit: <input type="text" name="unit" size="40" maxsize="100"></p>
<p>Enter Size in Sq Feet: <input type="number" name="size" size="40" maxsize="100"></p>
<p>Enter Price: <input type="text" name="price" size="40" maxsize="100"></p>
<!-- removed upload photos -->
<input type="submit" name="submit" value="Add indiviual Space!">
</form>
</div>
</body>
</html>
I would like the select dropdown menu to show a list of all buildings currently in the database so that the user can select a building to add his unit to.
If no buildings exist in database handle situation i.e. echo 'No buildings found in database, you need to
add a building record before attempting to add individual units';
Here is my buildings table:
https://imgur.com/a/2KMOUBD
Here is my units table:
https://imgur.com/a/w24IFuy
Here's a simple code to do what you need
Your code is so messed up, try to clean it :-)
We connect to mysql DB Using PDO class because it's more powerful and secure
you can change root with your db username
pass with your db password
db with your db name
read more about PDO here
// connect to db
$dbh = new \PDO('mysql:host=127.0.0.1;dbname=db', "root", "pass");
// query to select from db
$q = 'SELECT * FROM users';
// prepare and execute the query
$buildsq = $dbh->prepare($q);
$buildsq->execute();
// fetch the results and save them to $build var
$builds = $buildsq->fetchAll();
// check if their is results and print them
if($buildsq->rowCount()) {
foreach ($builds as $build) {
echo '<option value="">' . $build['name'] . '</option>';
}
} else {
echo "<option>No results </option>";
}
It's not the best, but it does what you need.
Try to put connection part in a function to clean up your code.
can anybody post an code for option list which can retrieve data dynamically from database, and once user selects from option list a record, that record must post it ($_POST) to database.. !!
ive tried this, it retrieves records from db, but not posting it :
<?php
require_once "db.php";
if (isset($_POST['a_id']) {
$a = $_POST ['a_id'];
$sql = "INSERT INTO projektet
VALUES ('$a')";
mysql_query($sql);
}
HERE IS THE PART SEEMS NOT WORKING :
<form method="post">
<select name="a_id">
<?php
$host="localhost";
$username = 'root';
$password = "";
$con = mysql_connect($host,$username,$password);
mysql_select_db('naho',$con);
// Checking connection
if (!$con){
echo ("Failed to connect to MySQL:. " .mysql_error($con));
}
else {
echo("db connect");
}
$result = mysql_query("SELECT * from `arqitekti`");
if($result == FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_array($result)){
?>
<option value="<?php '.row[a_id];'?>"><?php echo $row["a_emri"];?></option>
<?php }
?>
</select>
<input type="submit" value="submit"/>
</form>
<option value="<?php '.row[a_id];'?>"><?php echo $row["a_emri"];?></option>
This line looks strange... Shouldn't it be:
<option value="<?php echo $row[a_id]; ?>"><?php echo $row["a_emri"];?></option>
I think that your code is POSTing, but it wasn't getting any value because of the value declaration on the options of the select. After that change it should work.
PS: If your POST code isn't in the same page as your HTML, it's <form method="POST" action="YOUR_PAGE">, not only <form method="POST">.
Problem: Need to store field value when doing this query on my database. Have a couple pages that's using this same syntax but for some odd reason this isn't cooperating..
HTML
<form method="post" action="listPage.php">
<fieldset>
<legend>Pull some data</legend>
<label for="name">Name</label>
<input type="text" name="name" id="name" maxlength="255" />
<hr />
<br />
<input type="submit" value="find event" />
</fieldset>
</form>
listPage.php
<?php
//CONNECT TO DATABASE
$user="root";
$password="";
$database="db";
$connection=mysql_connect('localhost',$user,$password);
#mysql_select_db($database) or die( "Unable to select database");
echo "NOT running...";
//STORE ALL DATA FROM PREVIOUS FORM
if (isset($_POST['name'])) {
$name = mysql_real_escape_string($_POST['name']);
$query="SELECT event FROM events WHERE event='$name'";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_numrows($result);
echo "running...";
while ($row = mysql_fetch_array($result))
{
echo $row['event'] . " // ";
echo "<br />";
}
}
mysql_close($connection);
?>
Check to see if the post value is set before doing anything with it. (Also, don't forget to call mysql_real_escape_string() on it).
It may not be set if this code occurs on the page when it initially loads or is refreshed after having data posted to it.
// Don't attempt any of this unless you actually have a $_POST value
if (isset($_POST['name'])) {
$name = mysql_real_escape_string($_POST['name']);
$query="SELECT event FROM events WHERE event='$name'";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_numrows($result);
while ($row = mysql_fetch_array($result))
{
echo $row['event'] . " // ";
echo "<br />";
}
}
I couldn't quickly find any documentation regarding possible reserved words for POST or html form variables, so I went to
http://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml_form_method_post
and changed fname field to name, (clicked edit and click me button) and the POST variable was not passed or recognized.
So you might consider changing the name of your field to something other than name.
I was looking online for a script that demonstrates how I would go about making it possible for users on my site able to edit fields and such, but I could not find anything about it. So I was wondering if someone could explain to me how it works or just demonstrate with a script? To make it clear, I want users to be able to edit stuff that they've submitted by simply clicking 'edit' and pressing a button to update whatever it was they changed.
Edit: I forgot to mention that what's been changed should update a table in a MySQL database.
You need 2 PHP files to do this. You could use a single file but the concept is easier to explain this way.
A form that will load the database content into the fields where users can then edit the values and then submit them for change by pressing a button once done.
A file that receives the changed information and updates the database.
Here is a code example for the first file:
<?php
// connect to SQL
$dbcnx = #mysql_connect("localhost", "db_name", "password");
if (!$dbcnx) {
echo( "<P>Unable to connect to the database server at this time.</P>" );
exit();
}
// connect to database
$dbcon = #mysql_select_db("db_table", $dbcnx);
if (!$dbcon) {
echo( "<P>Unable to locate DB table at this time.</P>" );
exit();
}
#data preparation for the query
$id = intval($_GET["id"]);
# selects title and description fields from database
$sql = "SELECT * FROM table_name WHERE id=$id";
$result = mysql_query($sql) or die(mysql_error());
# retrieved by using $row['col_name']
$row = mysql_fetch_array($result);
?>
<h3>Edit</h3>
<form action="save_edit.php" enctype="multipart/form-data" method="post" name="myForm" />
<table>
<tr>
<td><b>Title</b></td>
<td><input type="text" size="70" maxlength="100" name="title" value="<?php echo $row['title'] ?>"></td>
</tr>
<tr>
<td><b>Description</b></td>
<td><textarea cols="80" rows="18" name="description"><?php echo $row['description']; ?></textarea></td>
</tr>
</table>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input name="enter" type="submit" value="Edit">
</form>
<?php
mysql_close($dbcnx);
?>
And here is an example of code for the second file where it receives the changes made by the user and updates the database.
<?php
// connect to SQL
$dbcnx = #mysql_connect("localhost", "db_name", "password");
if (!$dbcnx) {
echo( "<P>Unable to connect to the database server at this time.</P>" );
exit();
}
// connect to database
$dbcon = #mysql_select_db("db_table", $dbcnx);
if (!$dbcon) {
echo( "<P>Unable to locate DB table at this time.</P>" );
exit();
}
#data preparation for the query
$id = intval($_POST["id"]);
foreach ($_POST as $key => $value) $_POST[$key] = mysql_real_escape_string($value);
$sql = "UPDATE table_name SET
title='$_POST[title]',
description='$_POST[description]',
WHERE id=$id";
if (!mysql_query($sql,$dbcnx)) {
die('Error: ' . mysql_error());
}
mysql_close($dbcnx);
header ("location: http://www.domain.com/url_to_go_to_after_update");
?>
If you just need an idea how to create a basic edit form in PhP, that's easy enough. When they click the edit button take them to a new form. Pull the content from the database, using whatever database accessing api you are, and then initialize the field with it. For example, where $content has the content of the field:
echo '<textarea name="content">'.htmlspecialchars($content).'</textarea>';
When they submit the form, take whats now in the field and use it to update the table. It's the same as the original insert script, except that you use update statements instead of insert.
I'm not sure I understood what you said. If you want a way to edit things in place, you can use this jQuery plugin: Jeditable (with Ajax).
To extend Daniel's code a bit
<?php
$filename = "file.txt";
if ($_SERVER['REQUEST_METHOD'] == 'POST']) {
file_put_contents($filename, $_POST['content']);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
$content = htmlspecialchars(file_get_contents($filename));
?>
<form method="POST">
<textarea name="content"><?php echo $content?></textarea><br>
<input type="submit">
</form>