addressbook in php - php

hallo!
I am a university student, and I want to make an address book, using php, where someone can view a table with all the listed contacts' details (e.g. name, phone, email) and there will be the possibility of
-adding a new contact and
-editing
-deleting an existing contact.
I have created a table with the relevant fields in my database, and I have written some code (found on the internet but it didn't work + 20hours of trying to make it work on my own.... without the proper result) which shows the table of contacts, but:
The edit doesn't work at all
When the delete works, it deletes the contacts from last to first and not the row I am selecting
when I put the code for deleting in comments, the "Add" works
when the code for deleting is functional, then the "Add" actually "Deletes" (unless the table is empty, in which case it adds up to ONE contact).
If anyone can give me some hints/suggestions on what to change, please please do!
Here is my code:
<html>
<head>
<title>Address Book</title>
</head>
<body>
<?php
mysql_connect("localhost", "mydb", "mypassword") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
if (isset($_POST['mode']))
{
$mode = $_POST['mode'];
$id = $_POST['id'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email= $_POST['email'];
if ($mode=="add")
{Print '<h2>Add Contact</h2> <p>
<form action="" method=post>
<table>
<tr><td>Name:</td><td><input type="text" name="name" /></td></tr>
<tr><td>Phone:</td><td><input type="text" name="phone" /></td></tr>
<tr><td>Email:</td><td><input type="text" name="email" /></td></tr>
<tr><td colspan="2" align="center">
<input type="hidden" name="mode" value="added" />
<input type="submit" value="Submit" />
</td></tr>
</table> </form> <p>'; }
if ($mode =="added")
{mysql_query ("INSERT INTO address (name, phone, email) VALUES ( '$name', '$phone', '$email')");
echo "New contact added successfully!";}
if ($mode=="edit")
{Print '<h2>Edit Contact</h2> <p>
<form action="" method=post>
<table>
<tr><td>Name:</td><td><input type="text" value="';
Print $name; print '" name="name" /></td></tr>
<tr><td>Phone:</td><td><input type="text" value="';
Print $phone; print '" name="phone" /></td></tr>
<tr><td>Email:</td><td><input type="text" value="';
Print $email; print '" name="email" /></td></tr>
<tr><td colspan="2" align="center"><input type="submit" /></td></tr>
<input type=hidden name=mode value=edited>
<input type=hidden name=id value='; Print $id; print '>
</table>
</form> <p>';
}
if($mode=="edited")
{mysql_query ("UPDATE address SET name = '$name', phone = '$phone', email = '$email' WHERE id = $id");
Print "Data Updated!<p>";}
if ($mode=="remove")
{mysql_query ("DELETE FROM address where id=$id");
Print "Entry has been removed <p>";}
}
$data = mysql_query("SELECT * FROM address ORDER BY name ASC")
or die(mysql_error());
Print '<h2>Address Book</h2><p>
<form action="" method=post>
<table border cellpadding=3>
<tr><th width=100>Name</th><th width=100>Phone</th><th width=200>Email</th><th width=100 colspan=2>Admin</th></tr>
<td colspan=5 align=right>
<input type ="hidden" name = "mode" value="add"/> <input type = "submit" value="Add Contact"/>';
while($info = mysql_fetch_array( $data ))
{
Print "<tr><td>".$info['name'] . "</td> ";
Print "<td>".$info['phone'] . "</td> ";
Print "<td> " .$info['email'] . "</td>";
Print '<td>
<input type ="hidden" name="mode" vlaue="edit"/>
<input type ="submit" value="Edit"
?id='. $info['id'] .'&name=' . $info['name'] .'
&phone=' . $info ['phone'] .'&email=' . $info['email'] .'/></td>';
Print "<td>
<input type ='hidden' name='mode' value='remove'/>
<input type ='hidden' name='id' value = ".$info['id']." />
<input type ='submit' value = 'remove' /> </td></tr> ";
}
Print "</table>";
Print " </form>";
if(!$mode) echo "You may add, edit or delete a contact";
echo $mode;
?>
</body>
</html>

The reason why things aren't behaving the way you expect is that all your rows are being put into one big form. Therefore there are multiple hidden fields <input type ='hidden' name='id' value = ".$info['id']." />, all of which get submitted when you click any of your 'submit' buttons. But actually the value that will be passed along to your script will be the last value i.e. the last row id.
One way you could get around it is to use a link with the ID as a $_GET argument in the URL, for example:
Edit
Then you can change the line near the top to use $mode = $_GET['mode']; and $id=$_GET['id']
Once you have got the ID in the way, you can display a form with editable fields just for that particular id.
if ($mode == 'edit')
{
$data = mysql_query("SELECT * FROM address WHERE id=$id");
// then fetch the row data and populate the HTML form
}
Of course, the above example is vulnerable to SQL injection http://php.net/manual/en/security.database.sql-injection.php so a slightly more robust method would be wise - see the link for advice!

Related

How to display certain row's data in a form after clicking edit? (PHP)

enter image description hereI'm new to PHP so please don't judge :D
I'm trying to make table with edit option. No matter in which row I click "Edit" button, only data from last row of the page gets loaded. What should I do?
$sql = "SELECT * FROM countries LIMIT " . $this_page_first_result . ',' . $results_per_page;
$result = $connection-> query($sql);
echo '<div style="text-align:center; font-weight: bold;">';
for ($page=1; $page<=$num_of_pages; $page++){
echo '' . $page . ' ';
}
echo '<div><br>';
if($result-> num_rows > 0){
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$Name = $row['Name'];
$Area = $row['Area'];
$Population = $row["Population"];
$Phone_code = $row["Phone_code"];
echo "<tr><td><a href='cities.php?id={$row['id']}'>".$row['Name']."</a></td><td>". $row["Area"] ."</td><td>"
. $row["Population"] ."</td><td>". $row["Phone_code"] ."</td><td><button id='update-button' onclick='openEdit()'>Update</button></td><td><button id='delete-button'>Delete</button></td></tr>";
}
print_r($row);
}
else{
echo "</table><h2 style='text-align:center'>There are no countries in the database..</h2>";
}
$connection-> close();
?>
</table>
<br>
<div style="text-align:center">
<button type="button" id="close-button-edit" onclick="closeEdit()" style="display:none">Close</button>
<div id="edit_form" style="display:none; text-align:left">
<form action="edit_country.php" method="POST" class="forms">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<p>Name: <input type="text" name="name" required value="<?php echo $Name; ?>"></p>
<p>Area: <input type="text" name="area" required value="<?php echo $Area; ?>"></p>
<p>Population: <input type="text" name="population" required value="<?php echo $Population; ?>"></p>
<p>Phone code: <input type="text" name="phone_code" required value="<?php echo $Phone_code; ?>"></p>
<input type="submit" name="update" value="Update">
</form>
</div>
There are two strategies that can be used for this problem: all php or using JavaScript.
PHP Only
This requires a submission to pre-fill the edit form. Each update button sends the id as a GET request (it is requesting information, not changing information, so use GET), in the form of an ordinary link, which the php script uses to populate the edit form.
<?php
// always start with php stuff and don't issue any html until you're done
// initialization
$sortDirection = 'asc';
if(isset($_REQUEST['sortDirection'])) {
// this decouples the value from user input. It can only be 'Asc' or 'Desc'
$sortDirection = $_REQUEST['sortDirection'] == 'asc' ? 'Asc' : 'desc';
}
$rowToEdit = '';
$pdo = new PDO( ... );
// Using PDO because it is more standard
// Leaving connection details to user. See https://phpdelusions.net/pdo_examples/connect_to_mysql for tutorial
// $pdo is assumed to be the pdo object
// deal with row delete. Destructive, so will be post, and delete button will be set
if(isset ($_POST['delete']) ) {
// delete from countries where id = ?
//redirect back to self (Post, Redirect, Get pattern).
// Always do this when done working with POST submissions!
header('Location: /countries.php');
exit;
}
// deal with row update. This changes data, so use POST
if(isset($_POST['id'])) {
// update countries set ...
// redirect back to self
header('Location: /countries.php');
exit;
}
// deal with request for row to edit, use GET for info requests
if(array_key_exists('id', $_GET) {
$rowToEdit = $pdo->prepare("select * from countries where id = ?");
$rowToEdit->execute([$id]);
// fall through to show page
}
// get all country rows (Note, OK to use $sortDirection here because it is decoupled from user input)
$country = $pdo->query("SELECT * FROM countries ORDER BY NAME $sortDirection")->fetchAll(PDO::FETCH_GROUP);
// got all our data, dealt with user input, now we can present the view
?>
<html>
<head>
</head>
<body>
<h1>Countries</h1>
Sort Asc
Sort Desc
<table>
<tr>
<th>Name</th>
<th>Area</th>
<th>Population</th>
<th>Phone</th>
<th></th>
<th></th>
</tr>
<?php foreach( $country as $row): ?>
<tr>
<td><a href='cities.php?country_id=<?=$row['id']?>'><?=$row['Name']?></a></td>
<td><?=$row["Area"]?></td>
<td><?=$row["Population"]?></td>
<td><?=$row["Phone_code"]?></td>
<td> <a href='countries.php?id=<?=$row['id']?>'>Update</a> </td>
<td>
<form method="post">
<input type="hidden" name="id" value="<?=$row['id']?>" />
<button id='delete-button'>Delete</button>
</form>
</td>
</tr>
</table>
<?php if($rowToEdit): ?>
<div style="text-align:center">
<form action="countries.php" method="POST" class="forms">
<input type="hidden" name="id" value="<?= rowToEdit ['id']?>">
<input type="hidden" name="sortDirection" value="<?= $sortDirection?>">
<p>Name: <input type="text" name="name" required value="<?= $rowToEdit['Name']?>"></p>
<p>Area: <input type="text" name="area" required value="<?= $rowToEdit['Area']?>"></p>
<p>Population: <input type="text" name="population" required value="<?= $rowToEdit["Population"]?>"></p>
<p>Phone code: <input type="text" name="phone_code" required value="<?= $rowToEdit["Phone_code"]?>"></p>
<input type="submit" name="update" value="Update">
</form>
</div>
<?php endif; ?>
</body>
</html>

Can't select user from mysql table.

I asked a question before about my code with submitting users. After a few days of just guessing, I finally got it working. But, now. I can't select the user inside the table for a login. This is my code.
<?php
if($_POST['submit_id'] == 1)
{
//echo $_POST['fname'];
$playerf = $_POST['fname'];
$playerl = $_POST['lname'];
$name = $_POST['firstname'];
$link = mysqli_connect("localhost","tester","abc123","biscuit") or die(" Did not connect. " . mysqli_error($link));
$query = "SELECT firstname FROM Users" or die("Did not work." . mysqli_error($link));
if($name != $fname)
{
echo "Does not match.";
}
else
{
header ("Location: game.php");
}
}
?>
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" > <br />
Firstname: <input type="text" name="fname" id= "fname" required = "1"> <br />
Lastname: <input type = "text" name = "lname" id= "lname" required = "1"> <br />
<input type = "submit" value = "Register" id="submit_id" >
<input name="submit_id" type="hidden" id="submit_id" value="1">
<input type = "reset" name="Reset" value="Reset Page" class = "account">
</form>
</td>
</tr>
</table>
When I try to submit a user for it to identify/match, it doesn't and sends me straight into the game. Can someone help? A Beta is due in 3 days.!!!
You are not executing your query nor are you fetching the results:
$query = mysqli_query($link, "SELECT firstname FROM Users") or die("Did not work." . mysqli_error($link));
$user = mysqli_fetch_assoc($link, $query);
if($name != $user['firstname'])
Additionally:
Where did $fname come from? Did you just make that up?
You don't seem to use your POST variables which are probably necessary for you to run your query and get an exact match for your user. The above code will return every user but only check the first one. I doubt that is what you want.
You have two POST variables that seem to hold a first name. Does that look correct to you?

assign data from one table to a specific table (group)

I have a classrooms in schools and when I click on a certain classroom, I want to add students into it but my actual code is doing something stupid. It adds a student but i can see the student in all classrooms, not just in the one that i added him into. So when Im in classroom number 1, I see a form in there, I can add a student there, ... see how it works here:
here is the code: http://www.xxxx.xx/projekt/
here is my code in file trieda.php
<table align="center"><tr><td>
<form action="vlozit2.php" method="post">
Meno: <input type="text" name="meno" placeholder="Janko" maxlength="15" required>
Priezvisko: <input type="text" name="priezvisko" placeholder="Hruška" maxlength="20" required>
<input type="hidden" name="id_triedy" value="<?= $trieda['id_triedy'] ?>" />
<input type="submit" name="submit" value="Pridať študenta do triedy">
</form>
</td></tr></table>
<?php
$result = mysqli_query($prip,"SELECT * FROM student ORDER BY meno");
while($student = mysqli_fetch_array($result))
{
echo "<br /><table cellspacing='1' cellpadding='1' class='tabulka1' align='center'><tr>";
echo "<td width='200'><a href='student.php?id_triedy=".$trieda['id_triedy']."".id_student=".$student['id_student']."'>".$student['meno']." ".$student['priezvisko']."</a></td>";
?>
<td width='300px' align='right' bgcolor="#fbfbfb">Zmazať</td>
</tr></table>
<?php
}
?>
here is vlozit2.php (a code that works for the form to add a student)
if(isset($_POST['submit']))
{
//meno a priezvisko
$student = $_POST['meno'];
$student = $_POST['priezvisko'];
$trieda = $_POST['id_triedy'];
//connect to the database
include 'config.php';
//insert results from the form input
$sql = "INSERT INTO student (meno, priezvisko, id_triedy) VALUES('$_POST[meno]', '$_POST[priezvisko]', '$_POST[id_triedy]')";
$add = "<table align='center'>
<tr>
<td> Študent bol úspešne pridaný do triedy. </td>
</tr>
<tr>
<td><a href='./trieda.php'><strong>Späť</strong></a></td>
</tr>
</table>";
$not_add = "<table align='center'>
<tr>
<td> Študent s týmto menom a priezviskom už je v tejto triede. </td>
</tr>
<tr>
<td><a href='./trieda.php'><strong>Späť</strong></a></td>
</tr>
</table>";
if (mysqli_query($prip, $sql)) {
echo $add;
}else{
echo $not_add;
}
mysqli_close($prip);
}
?>
Try to replace your part of code with these snipets:
1) in trieda.php
<form action="vlozit2.php?id_triedy=<?php echo $_GET["id_triedy"];?>" method="post">
Meno: <input type="text" name="meno" placeholder="Janko" maxlength="15" required>
Priezvisko: <input type="text" name="priezvisko" placeholder="Hruška" maxlength="20" required>
<input type="submit" name="submit" value="Pridať študenta do triedy">
</form>
2) in vlozit2.php
$student = $_POST['meno'];
$priezvisko = $_POST['priezvisko'];
$id_trieda = $_GET['id_triedy'];
and
$sql = "INSERT INTO student (meno, priezvisko, id_triedy) VALUES( '{$student}', '{$priezvisko}', {$id_trieda} )";
Hopefully you store your id_trieda as INT type.
In your vlozit2.php file is nothing about inserting of class id. So put
<input type="hidden" name="classId" value="<?= $trieda['id'] ?>" />
to your form and in vlozit2.php get this value from $_POST['classId'] and insert it with other students data or anywhere you want to have it.

PHP page is storing form input variables after user submits

I wasn't sure what else to call the title...I have a PHP page that accesses a certain MySQL database, pulls the values from the table, and places them in an HTML form (POST method - PHP_SELF). The user can then view the values, alter them as they wish, and submit them. The page then takes those values and updates the MySQL database. Everything works perfectly except that when the user submits and the page goes to show the new updated variables, it still shows the old values. The user is forced refresh the page before the new variables show up. I thought that PHP was perhaps not deleting the variables, so I unset all stored variables after the script was over and it's still not working. I ever tried putting a sleep timer before the script started, and that didn't work either. I'd appreciate any suggestions. Here is my script just for reference:
<html>
<body>
<?php
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
?>
</body>
</html>
You are displaying the data from the database before you update it.
It is normally good practice to do all your database connectivity at the top of the page, then display the results.
In your code (even if a user has submitted an update), you query the data, pull it from database and display it, then run the update with what the user submitted.
Changing your code to this should do the trick (Do read the note below though):
<html>
<body>
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
</body>
</html>
Bad note - your code is wide open to injection attacks. You are using form data with no verification. That's a big red flag. Secondly, you are using deprecated mysql_* functions. Your code should be using mysqli_* functions or better yet move to PDO. It is much safer and you will be able to do a lot more with it.
Edit 2: The page IS being updated after the user submits the form, but the page you display to the user is querying the database before you update it - and using that to display the page to the user.

How to send multiple row value submit button?

I get the values from same row, but many values with fetch array. I did it, but with buttons, as many as how many values there are. If I have 5 rows, then I should have five submits, but I want one submit button.
Here is my code:
$result2 = mysql_query ("select * from price where dom='$cat'",$db);
$myrow2= mysql_fetch_array($result2);
<form action="priceupdatetes.php" method="post">
<?php
do {
echo <<<here
<td><input name="etiket[$myrow2[id]]" type="text" value="$myrow2[etiket]"/></td>
<td><input name="pricestandart[$myrow2[id]]" type="text" value="$myrow2[pricestandart]"/></td>
<td><input name="number[$myrow2[id]]" type="text" value="$myrow2[number]"/></td>
<td><input name="totalunper[$myrow2[id]]" type="text" value="$myrow2[totalunper]" disabled="disabled"/></td>
<td><input name="discount[$myrow2[id]]" type="text" value="$myrow2[discount]"/></td>
<td><input name="totalwithper[$myrow2[id]]" type="text" value="$myrow2[totalwithper]" disabled="disabled"/></td>
</tr>
here;
}
while($myrow2= mysql_fetch_array($result2)) ;
?>
<input NAME="id[]" TYPE=hidden value="<?php foreach($myrow2[id] as $mid) {print $mid;} ?> "/>
<input name="submit" type="submit" value="Submit"/><br>
</form>
HERE is UPDATEPAGE.php:
if (isset($_POST['etiket'])) {$etiket = $_POST['etiket']; }
if (isset($_POST['pricestandart'])) {$pricestandart = $_POST['pricestandart'];}
if (isset($_POST['number'])) {$number = $_POST['number']; }
if (isset($_POST['discount'])) {$discount = $_POST['discount']; }
if (isset($_POST['id'])) {$id = $_POST['id']; }
$totalunper=$pricestandart*$number;
$percent=$discount/100;
$totalwithper1=$totalunper*$percent;
$totalwithper=$totalunper-$totalwithper1;
foreach($id as $team_id)
{
$result = mysql_query("UPDATE price SET etiket='$etiket[$team_id]',pricestandart='$pricestandart[$team_id]',number='$number[$team_id]',totalunper='$totalunper[$team_id]',discount='$discount[$team_id]',totalwithper='$totalwithper[$team_id]' WHERE id='$team_id'"); }
How can I get values with different id's and update them?
<input NAME="id[]" TYPE=hidden value="<?php foreach($myrow2[id] as $mid) {print $mid;} ?> "/>
is wrong. $myrow2[id] is not an array. Inside your while-loop, you should add:
<input NAME="id[]" TYPE="hidden" value="$myrow2[id]"/>

Categories