Can $_POST differentiate between two elements with the same name? - php

New to PHP and reading through Robin Nixon's PHP, MySQL, Javascript book. I am having trouble with an example of inserting and deleting data using a PHP script, specifically with how the author uses $_POST.
The example is a pretty simple add records/delete records of books with multiple inputs. Here's the code:
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post('isbn');
$query = "DELETE FROM classics WHERE isbn='$isbn'";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br />" .
mysql_error() . "<br /><br />";
}
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$category = get_post('category');
$year = get_post('year');
$isbn = get_post('isbn');
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
echo "INSERT failed: $query<br />" .
mysql_error() . "<br /><br />";
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Category <input type="text" name="category" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
When you refer to an element in $_POST with if (isset($_POST['delete']) && isset($_POST['isbn'])), where delete and isbn are used as names multiple times, how does $_POST know which element to reference to delete? I assume that since you can only delete one record at a time, the element in the array will automatically point to the one that's already set. However, how does the second condition of isset($_POST['isbn']) know which "isbn" element to check for? Does the && make the $_POST['isbn'] "inherit" the correct row?
Thanks for the help! And apologies for any possible misuse of the vocab. Still getting used to everything.

Your question is actually well thought out. And the example given in the book seems quite sloppy to me. I am assuming in later chapters he will delve into the use of arrays in $_POST values. But anyway, here is the key to the functionality of the whole script:
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>
_END;
}
See that <form action="sqltest.php" method="post">? And see that closing </form>? And note that they are being rendered each time the for ($j = 0 ; $j < $rows ; ++$j) loop happens? There is one individual form element for each line. That is messy code, but it works. When one clicks submit on each individual listing, the wrapping form responds & parses the variables nested inside it.
Like I said, sloppy code. But works. And it’s because if you have 30 ISBNs listed this program will spit out 30 individually wrapped <form> items. Uggh! Seriously if the book does not address arrays later on in a way that addresses this face-palm of a coding mess find a new book.

Since there are multiple forms, the input elements of only one form are submitted.
So basically, sqltest.php receives only one array of $_POST containing ['delete'] and ['isbn'] with the corresponding values only once.
You can check this out by using print_r($_POST) in sqltest.php.

Related

Function get_post and return mysqli_real_escape_string - PHP

I'm a beginner at coding (I just have a small experience with Visual Basic and Pascal) and now I'm trying to learn some Web Development using O'Reilly's book "Learning PHP, MySQL, JavaScript, CSS & HTML 5".
The problem is that he is using MySQL instead of MySQLi, so I need to do small changes when I'm following thought the exercises.
In a chapter called "Accessing MySQL databases using PHP" he built a form where the user can add a new book (with title name, author, year, category and ISBN) to the database. My problem is that I have some error than doesn't allow to see in the web page the new book submitted.
I'm not sure, but I think it has to be something with the get_post and mysqli_real escape_string part.
This is the code I've written:
<?php //sqltest.php
require_once 'login.php';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysqli_error($db_server));
mysqli_select_db($db_server, $db_database)
or die ("Unable to select database: " . mysqli_error($db_server));
//Deleting a record.
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post('isbn');
$query = "DELETE FROM classics WHERE isbn = '$isbn'";
if (!mysqli_query($db_server,$query))
echo "DELETE failed: $query<br>" .
mysqli_error($query) . "<br><br>";
}
//Add new elements to the database.
if (isset($_POST['author']) && //Isset -> Determine if a variable is set and is not NULL.
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post($db_server, 'author');
$title = get_post($db_server, 'title');
$category = get_post($db_server, 'category');
$year = get_post($db_server, 'year');
$isbn = get_post($db_server, 'isbn');
}
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
//Displaying the form.
echo <<<_END
<form action = "sqltest.php" method="post"> <pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Category <input type="text" name="category" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysqli_query($db_server, $query);
if (!$result) die ("Database acess failed: " . mysqli_query_error($result));
$rows = mysqli_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="isbn" value="$row[4]">
<input type="submit" value="DELETE RECORD"></form>
_END;
}
function get_post($db_server, $var)
{
return mysqli_real_escape_string($db_server, $_POST[$var]);
}
mysqli_close($db_server);
?>
Just to explain my problem better: I fill the form with the details from the new book and then I submitted it but the new book doesn't appear on the web page (like the ones added before using MySQL command line).
Thanks for your time,
David
There is an error in your code, specific the name of database columns.
$query = "INSERT INTO classics (author, title, category, year, isbn) VALUES ('$author', '$title', '$category', '$year', '$isbn');";

php - insert multiple rows into mysql from form loop

So I am displaying multiple html forms on a page - works great because I am just using a simple loop to display it 80 times but the issue I am facing is I would like to take all 80 forms and submit them into multiple rows in my database. It's only submitting the last form (which is 80)
If anyone can help me find the issue... I would really appreciate it! I've done some searching before submitting this question but I can't seem to find a answer.
Here is what my table looks like:
Here is my form builder
<?php
// Counts the number of forms
$counter = 1;
echo '<form action="insert.php" method="post">';
// Loop through forms
for ($i = 1; $i < 81; $i++) {
$username = 'admin';
$title = 'test';
$name = 'a';
$image_src = '<img src="image/'.$i.'.jpg">';
$transition = 'fade';
$group_name = '0';
echo '<hr>' . '('. $counter .')'. '<br>';
echo "
<label>Username:</label>
<input type='text' name='username' id=' required='required' value='".$username."'/>
<br /><br />
<label>Title:</label>
<input type='text' name='title' id=' required='required' value='".$title."'/>
<br/><br />
<label>Name:</label>
<input type='text' name='name' id=' required='required' value='".$name."'/>
<br/><br />
<label>Content:</label>
<input type='text' name='content' id=' required='required' value='".$image_src."'/>
<br/><br />
<label>Image:</label>
<input type='text' name='image' id=' required='required' value='images/".$i.".jpg'/>
<br/><br />
<label>CSS Animate:</label>
<input type='text' name='cssanimate' id=' required='required' value='".$transition."'/>
<br/><br />
<label>Group Name:</label>
<input type='text' name='group_name' id=' value='0'/>
<br/><br />
";
$counter++;
}
echo '<input type="submit" value="Submit" name="submit"/>';
echo '</form>';
?>
Here is my php code: (insert.php)
<?php
$con=mysqli_connect("localhost","admin","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO table_name (username, title, name, content, image, cssanimate, group_name, group_sort) VALUES ('".$_POST["username"]."', '".$_POST["title"]."', '".$_POST["name"]."', '".$_POST["content"]."', '".$_POST["image"]."', '".$_POST["cssanimate"]."', '".$_POST["group_name"]."', '".$_POST["group_sort"]."') ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
} echo "Added!";
mysqli_close($con);
?>
If you have 80 elements with this name:
name='username'
Then how will this code know which one to use?:
$_POST['username']
Essentially, as your browser builds the form submission, each successive element of the same name over-writes the previous one. So you end up with only the last record.
Instead, give them an array-style name:
name='username[]'
(Repeat for all your duplicated form elements.)
Then in the PHP code, this would itself be an array:
$_POST['username']
You could loop over that array:
for ($i = 0; $i < count($_POST['username']); $i++) {
$username = $_POST['username'][$i];
$title = $_POST['title'][$i];
// etc.
}
This assumes that all of your arrays will be the same length. Which, given this HTML, I suppose they should be. But you can add error checking for that just in case. Either way, each iteration of the loop would build variables equating to that "record" which was submitted.
From there you should be able to build your SQL query with those variables. However, please note that your current way of doing that is extremely unsafe and wide open to SQL injection. To correct that, this is a good place to start.
Side note: Your HTML has invalid id attributes. Additionally, if you want to specify id attributes in that loop, you're going to need to ensure that they are somehow different. Duplicated ids in HTML is invalid.

Update button in PHP/Mysql needs to clicked twice in order to work?

I am fairly new to php and sql trying to figure out to get the form button to be only be clicked once to update. The program already has an add, search, and delete working just fine and just need to get this to work. It seems to be updating, but it doesn't output the update until I click again. Here is my code:
if (isset($_POST['update']) &&
isset($_POST['name']) &&
isset($_POST['planet']) &&
isset($_POST['country']) &&
isset($_POST['population']) &&
isset($_POST['density']))
{
$name = get_post($conn, 'name');
$planet = get_post($conn, 'planet');
$country = get_post($conn, 'country');
$population = get_post($conn, 'population');
$density = get_post($conn, 'density');
$sql = "UPDATE cities SET planet = '$planet', country = '$country', population = '$population', density = $density WHERE name = '$name' ;";
$result = $conn->query($sql);
if (!$result) die ("Database access failed: " . $conn->error);
}
echo <<<_END
<pre>
name $row[0]
planet $row[1]
country $row[2]
population $row[3]
density $row[4]
</pre>
<form action="Hw05.php" method="post"><pre>
<input type="hidden" name="update" value="yes">
name <input type="text" name="name" value="$row[0]">
planet <input type="text" name="planet" value="$row[1]">
country <input type="text" name="country" value="$row[2]">
population <input type="int" name="population" value="$row[3]">
density <input type="int" name="density" value="$row[4]">
<input type="submit" value="UPDATE RECORD">
</pre></form>
_END;
Any help would be appreciated, like I am said I am new to Php/mysql and more of a Java guy. (However I do like php).
The query that stores data in $row is not in your code, so I think this query is done before the UPDATE query. You should make your SELECT query after your UPDATE, because data in $row is selected before that you update table.
Your variables might be populated before the update happens. You need to do a SELECT query again to get the updated values.

Calling an array element created from a for loop

I have an array that is created from a mysqli query.
The array then goes through a for loop to display a table.
Within the table there is a form submit that needs to take the selected row and pass the information into a variable to be modified.
I tried to take a screenshot, but I just joined and have no rep. In theory, the user needs to be able to select Modify and the array elements for that row need to pass into text input boxes with a preset value of $row[$j][0] where $j is fixed based on the row selected to modify.
Here is what this part of the code looks like.
if (isset($_POST['Select']) &&
isset($_POST['Search']))
{
$Select = get_post($con,'Select');
$Search = get_post($con,'Search');
if ($Select == "Invalid")
{
echo "<br /><br />Please select a search catagory";
}
else if ($Search == NULL)
echo "<br /><br />Please enter search field";
else
{
$query = "SELECT * FROM table WHERE $Select LIKE '$Search%'";
$result = mysqli_query($con,$query);
if (!mysqli_query($con,$query)) {
die('Error: ' . mysqli_error($con));
}
$rows = mysqli_num_rows($result);
echo "<table id='myTable' class='tablesorter'>
<thead><tr>
<th>Modify</th>
<th>Field1</th>
<th>Field2</th>
<th>etc...</th>
</tr></thead><tbody>";
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_row($result);
$modrow[$j] = $row;
echo <<<_END
<tr>
<td><form action="Lookup.php" method="post"><input type="submit" value="Modify" /><input type="hidden" name="submitted" value="$modrow[$j]"</form></td>
<td>$row[0]</td>
<td>$row[1]</td>
<td>etc...</td>
</tr><br />
_END;
}
echo "</tbody></table>";
if (isset($_POST['submitted']))
{
echo <<<_END
<form action="Lookup.php" method="post"><pre>
Field1 <input type="text" name="Field1" size="50" **value="$modrow[$j][0]"** />
...more of the same...
From what I gather, you're wanting to pass a request to the server containing some form of identifier for the row so that you may create a form for users to modify that row's data. Sorry if I misunderstood - I would ask first if I understood you correctly as a comment, but don't have enough rep.
You can use an id to submit to the server.
<button type="submit" name="modify" value="<?= $theRowsId ?>">Modify</button>
Think of the values of name and value attributes as a function/method and value being passed respectively.
Now when Modify is clicked, you can get retrieve the ID, perform a query for the ID and populate the input with the rows data.
$rowId = $_POST['modify'];

PHP Issue with deleting from MySQL

I do have programming experience, but new to php. I do have an issue with an example I was doing from this tutorial. I looked over it millions of times, googled, ect ect. I don't have an idea why my code isnt working.
The purpose is to basically just test inserting and deleting in sql from php, using a button for Add Record and Delete Record. The Add record button works perfectly, but delete doesnt do a thing other than reload the page. Heres the code...
<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['type']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
if (isset($_POST['delete']) && $isbn != "")
{
echo "worked!!!!!!!!!!!!!!";
$query = "DELETE FROM classics WHERE isbn='$isbn'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
//if (!mysql_query($query, $db_server))
//echo "DELETE failed: $query" . mysql_error();
}
else
{
echo "nooooooooooooooooooo";
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$type', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Type $row[2]
Year $row[3]
ISBN $row[4]
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="$row[4]" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
I have looked over this many times, still no idea why this won't work. Is it the for loop that is making this button not work? Note, you will see echo "worked!!!"; and in the else echo "noooooooo"; that was for me to test whether the button was being tested, yet nothing prints. So maybe i missed something in the button code itself? Also, no errors are printed, and my editor (and myself) have missed the syntax error (if thats the case).
The code for the delete button is at the end, before I closed the DB.
Thanks for your help in advance.
Your problem is your first if block.
You're checking for the presence of the posted variables author title type year isbn. Whereas in your delete code the only variables sent are delete and isbn. Therefore the first if block is completely missed (including the delete code).
You need to modify your first if to be if(isset($_POST)) { // a form has been posted. Then it should work.
Another way to do it:
if(isset($_POST['delete']) && isset($_POST['isbn']) && !empty($_POST['isbn'])){
//delete code here
}
if(isset($_POST['author']) && isset($_POST['title']) && isset....){
// insert code here
}
EDIT: rewritten code:
<?php // sqltest.php
// I don't know what's in here, so I've left it
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST))
{
if (isset($_POST['delete']) && !empty($_POST['isbn']))
{
echo "Deleting";
$query = "DELETE FROM classics WHERE isbn='".mysql_real_escape_string($_POST['isbn'])."'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
}
else
{
echo "Inserting";
$query = "INSERT INTO classics VALUES ('".mysql_real_escape_string($_POST['author'])."', '".mysql_real_escape_string($_POST['title'])."', '".mysql_real_escape_string($_POST['type'])."', '".mysql_real_escape_string($_POST['year'])."', '".mysql_real_escape_string($_POST['isbn'])."')";
if (!mysql_query($query))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
// you don't need echo's here... just html
?>
<form action="sqltest.php" method="post">
<pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre>
</form>
<?php
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
// a better way to do this:
while($row = mysql_fetch_array($result)){
?>
<pre>
Author <?php echo $row[0]; ?>
Title <?php echo $row[1]; ?>
Type <?php echo $row[2]; ?>
Year <?php echo $row[3]; ?>
ISBN <?php echo $row[4]; ?>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="<?php echo $row[4]; ?>" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
<?php
}
mysql_close($db_server);
?>
Verify the method you used in your form. Make sure it's POST like this:
Form action="yourpage.php" method="POST"
and in your code above, replace the following:
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
with
$author = $_POST['author'];
$title = $_POST['title'];
$type = $_POST['type'];
$year = $_POST['year'];
$isbn = $_POST['isbn'];
Finally, there is no need to check again if the $isbn is not null as you did it in your isset() method. So remove $isbn!="" in the if below:
if (isset($_POST['delete']) && $isbn != "")
{
}
becomes:
if (isset($_POST['delete']))
{
}
Since you are testing, checking if the user clicked the delete button is of less importance. So you can also remove it for a while and add it later because you are sure that, that code is accessible after clicking the delete button.
You have no form field named delete, so it is impossible for your delete code path to ever be taken.
I'm guessing you're tryign to use the value of the submit button to decide what to do? In that case, you're also missing a name attribute on the submit button - without that, it cannot submit any value with the form. You probably want:
<input type="submit" name="submit" value="DELETE RECORD" />
and then have
if (isset($_POST['submit']) && ($_POST['submit'] == 'DELETE RECORD')) {
...
}

Categories