PHP MySQL Delete record only if it exist - php

Having a bit of trouble, I have created a form to deleted a record from a linked MySQL database using PHP that works, but I am having an problem with how to make an error display if a uadnumber value for example already exists.
<form name="deleterecord" action="indexdelete.php" method="post">
UAD Username: <br/><input type="text" name="uadnumber" /><br/>
<input type="submit" onclick="return deletedatabase();" value="Delete" />
</form>
<?php
// find the values from the form
$uadnumber = $_POST['uadnumber'] ;
?>
<?php
$con=mysqli_connect($db_hostname,$db_username,$db_password,$db_database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$retval = mysqli_query($con,"DELETE FROM users WHERE uadnumber='$uadnumber'");
if(!$retval<0)
{
die('Could not delete data: ' . mysql_error());
}
echo "Deleted all linked data from user $uadnumber successfully"."<br><br>";
echo "<hr>";
echo "Below is the remaining users within the database";
mysqli_close($con);
?>

if (isset($_POST["uadnumber"])) {
$uadnumber = (int)$_POST["uadnumber"];
$db = new mysqli($db_hostname,$db_username,$db_password,$db_database);
if ($db->query("SELECT uadnumber FROM users WHERE uadnumber='".$uadnumber."'")->num_rows > 0) {
if ($db->query("DELETE FROM users WHERE uadnumber='".$uadnumber."'")->affected_rows > 0) {
echo 'Desired rows have been removed.';
} else {
echo 'No rows have been removed.';
}
} else {
echo 'There are no rows identified by given value.';
}
}

Related

MYSQL and PHP Loop Failure

What problem i am having right now, is that there is a while loop to post my topics retrieved from MySQL. Works perfectly fine, until I get into inputting data. I have recently created a comment system, where for each topic there will be a comment box to submit. The problem is the while loop runs it over and over again, so when i type a comment for one topic, it posts to all of them.
Here is my code:
//MYSQLI LOGIN DETAILS
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
//MYSQLI CREATE CONNECTION
$constatus = new mysqli($servername, $username, $password, $dbname);
//MYSQLI CHECK CONNECTION
if ($constatus->connect_error) {
die("Connection failed: " . $constatus->connect_error);
}
//MYSQLI COUNT COLUMNS
$sql = "SELECT NEWSID, AUTHOR, ADMINSTS, DATE, HEADING, ARTICLE FROM news ORDER BY NEWSID DESC";
$result = $constatus->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class=newsboard_topic>" .
"<div class=newsboard_authordate>" . $row["AUTHOR"];
if ($row["ADMINSTS"] == admin) {
echo
"<div class=newsboard_adminfx>
Admin
</div>";
} else if ($row["ADMINSTS"] == sadmin) {
echo
"<div class=newsboard_sadminfx>
Super Admin
</div>";
}
if ($_SESSION['adminsts'] == 'admin' || $_SESSION['adminsts'] == 'sadmin') {
echo "<span class=newsboard_adminactions> <img src='/image/remove.png' style='width:20px; height:20px;'> </span>";
}
echo
"<span class=date>" . $row["DATE"] .
"</span></div>
<h1>" . $row["HEADING"].
"</h1><p class=newsboard_topic_article>" .
$row["ARTICLE"] .
"</p>";
$sqlcomments = "SELECT newscomments.USERID, newscomments.COMMENT, userdata.FIRSTNAME, userdata.LASTNAME, userdata.ADMINSTATUS FROM newscomments JOIN userdata ON newscomments.USERID=userdata.ID WHERE NEWSID=$row[NEWSID] ORDER BY COMMENTID DESC";
$resultcomments = $constatus->query($sqlcomments);
echo "<div class=newsboard_comments>
Comments
<br>";
while($rowcomments = $resultcomments->fetch_assoc()) {
echo $rowcomments["FIRSTNAME"] . " " . $rowcomments["LASTNAME"] . " " . $rowcomments["COMMENT"] . "<br>";
}
if (isset($_SESSION['loggedon']) && $_SESSION['loggedon'] == true) {
echo '
<form method="post">
<input class=postheadline type="text" name="comment" />
<input class=submit type="submit" id="submit" name="submit" value="Comment"/>
</form>';
if (isset($_POST[submit])) {
if (!empty($_POST[comment])) {
$sqlcommentpost = "INSERT INTO newscomments (NEWSID, USERID, COMMENT) VALUES ('$row[NEWSID]', '$_SESSION[profileid]', '$_POST[comment]')";
if ($constatus->query($sqlcommentpost) === TRUE) {
echo "Posted Successfully!";
break;
} else {
echo "Fatal Error. Please try again";
break;
}
}
}
}
echo "</div></div>"; /*Ends newsboard_topic Div & newsboard_comments Div*/
}
} else {
echo "0 results";
}
Live example is online at www.geovillageva.com however you cannot see comments as it is for registered members only because it will have a name for posters.
Lets include the news id also in the form. You can have a hidden input field for this. Then use this news id $_POST[nid] while inserting.
if (isset($_SESSION['loggedon']) && $_SESSION['loggedon'] == true) {
echo '
<form method="post">
<input class=postheadline type="text" name="comment" />
<input type="hidden" name="nid" value="'.$row[NEWSID].'" />
<input class=submit type="submit" id="submit" name="submit" value="Comment"/>
</form>';
if (isset($_POST[submit])) {
if (!empty($_POST[comment])) {
$sqlcommentpost = "INSERT INTO newscomments (NEWSID, USERID, COMMENT) VALUES ('$_POST[nid]', '$_SESSION[profileid]', '$_POST[comment]')";
if ($constatus->query($sqlcommentpost) === TRUE) {
echo "Posted Successfully!";
break;
} else {
echo "Fatal Error. Please try again";
break;
}
}
}
}
So, your input block
if (isset($_SESSION['loggedon']) && $_SESSION['loggedon'] == true) {
echo '
<form method="post">
<input class=postheadline type="text" name="comment" />
<input class=submit type="submit" id="submit" name="submit" value="Comment"/>
</form>';
if (isset($_POST[submit])) {
if (!empty($_POST[comment])) {
$sqlcommentpost = "INSERT INTO newscomments (NEWSID, USERID, COMMENT) VALUES ('$row[NEWSID]', '$_SESSION[profileid]', '$_POST[comment]')";
if ($constatus->query($sqlcommentpost) === TRUE) {
echo "Posted Successfully!";
break;
} else {
echo "Fatal Error. Please try again";
break;
}
}
}
}
needs to go by itself before the display loop. On the query inserting using $row[NEWSID], you need to use $_POST['newsid'] instead (and you may need to add that to your form to be posted along with the comments).
Please note that you need to beef up the security on this considerably or you will be hacked.
You can try a .reset() on your form after the submission was successful(before the break).

displaying duplicate entry from database with php

I am trying to display data from search function in database but unfortunately i get duplicate entries, can anyone check this and help me a little bit:
I am using this query and this php Code where startdate and enddate are from the members table, all the others data are from person table:
$query = "select * FROM person, members where fname= '$fname' AND lname = '$lname'";
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
echo '<p><strong>'.($i+1).'. Name: ';
echo htmlspecialchars(stripslashes($row['fname']));
echo '</strong><br />Surname: ';
echo stripslashes($row['lname']);
echo '<br />Board: ';
echo stripslashes($row['board']);
echo '<br />Department: ';
echo stripslashes($row['departmentname']);
echo '<br />Start Date: ';
echo stripslashes($row['startdate']);
echo '<br />End Date: ';
echo stripslashes($row['enddate']);
echo '</p>';
This is what i get as output: So i want to be displayed only on person with name aa nd surname bb (not five times but only once).
1. Name: aa
Surname: bb
Board: Secur
Department: Telec
Start Date: 2016-07-01
Edn Date: 2016-07-31
2. Name: aa
Surname: bb
Board: Secur
Department: Telec
Start Date: 2016-07-19
Edn Date: 2016-07-21
after searching during the edit process the ID is not changing at all
<?php
function renderForm($personid, $personname, $personsurname, $error)
{
?>
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="personid" value="<?php echo $personid; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $personid; ?></p>
<strong>First Name: *</strong> <input type="text" name="personname" value="<?php echo $personname; ?>"/><br/>
<strong>Last Name: *</strong> <input type="text" name="personsurname" value="<?php echo $personsurname; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
$host = "localhost";
$user = "kkoikm_kum";
$pass = "datgbhnkum";
$db = "koikm_kum";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['personid']))
{
// get form data, making sure it is valid
$personid = $_POST['personid'];
$personname = mysql_real_escape_string(htmlspecialchars($_POST['personname']));
$personsurname = mysql_real_escape_string(htmlspecialchars($_POST['personsurname']));
// check that firstname/lastname fields are both filled in
if ($personname == '' || $personsurname == '')
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($personid, $personname, $personsurname, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE tblperson SET personname='$personname', personsurname='$personsurname' WHERE personid='$personid'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: home.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['personid']) && is_numeric($_GET['personid']) && $_GET['personid'] > 0)
{
// query db
$personid = $_GET['personid'];
$result = mysql_query("SELECT * FROM tblperson WHERE personid=$personid")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$personname = $row['personname'];
$personsurname = $row['personsurname'];
// show form
renderForm($personid, $personname, $personsurname, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
I have modified this code but seems that i have made mistakes and i cant find the. after being able to edit the name and surname i will add other fields also.
I'm assuming there is primary/unique key in your person table
$query = "select * FROM person, members where fname= '$fname' AND lname = '$lname' GROUP BY person.person_id";

How to get a dynamic form with php that gets data from a database

I've got a dropdown menu in a form on my website which is filled with values of a database table which shows all the school-classes of my school. Now I have a second page in which I display all students that are in a database table, wiich are in the selected class, in a form with checkboxes.
My question is now as following:
How can I get these two pages in one together? So that all students of the selected class get displayed when i just select the class in the dropdown menu without pressing the submit button.
My Sourcecode:
1) Code of the website in which the class gets selected:
<html>
<?php
$db_host = "localhost";
$database = "internat_db";
$con=mysqli_connect($db_host, "root", "", $database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$klassen = mysqli_query($con, "Select * from klassen");
echo '<form action="schueler_ausgabe.php" method="POST">';
echo '<select name="Klassenwahl">';
while($row = mysqli_fetch_array($klassen))
{
echo "<option value=".$row['Klasse'].">".$row['Klasse']."</option>";
}
echo '<input id="submit" name="submit" type="submit" value="Auswaehlen" />';
echo '</form>';
mysqli_close($con);
?>
</html>
2) Code of the website that displays all students:
<html>
<?php
$klassenname = $_POST["Klassenwahl"];
$db_host = "localhost";
$database = "internat_db";
$con=mysqli_connect($db_host, "root", "", $database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$zw = "Select vorname, nachname FROM schueler WHERE klasse = '".$klassenname."'";
$schueler = mysqli_query($con, $zw);
echo '<form action="" method="POST">';
while($row = mysqli_fetch_array($schueler))
{
echo "<input type='checkbox' name='schueler' value=".$row['vorname']." ".$row['nachname'].">".$row['vorname']." ".$row['nachname']."";
echo '<br>';
}
echo '<input id="submit" name="submit" type="submit" value="Auswaehlen" />';
echo '</form>';
mysqli_close($con);
?>
</html>
Thank you very much for any help/idea out there!

post array from checkboxes is always returning empty

i am trying to delete the email entries from check boxes in a form , but it is unable to fetch any value from 'todelete[]' array
here is the code:
<?php
$dbc= mysqli_connect('localhost','root','','customer_base')or die('Error connecting to MySQL server.');
$query = "select * from email_list";
$result= mysqli_query($dbc, $query)or die('Error querying database.');
while($row= mysqli_fetch_array($result)){
echo '<input type="checkbox" value="' .$row['id']. '"name="todelete[]" />';
echo $row['first_name'].' '.$row['last_name'].' '.$row['email'].' '.'<br />';
}
if((isset($_POST['submit']))&&(isset($_POST['todelete']))){
$output_form= false;
foreach($_POST['todelete'] as $delete_id){
$query = "delete from email_list where id = $delete_id";
mysqli_query($dbc,$query)or die('Error querying database.');
}
echo '<p>Customer entry removed</p>'.'<br />';
}elseif((isset($_POST['submit']))&&(empty($_POST['todelete']))){
echo "<p>you haven't selected any customer entry to delete!</p>";
$output_form= true;
}else {$output_form= true; }
mysqli_close($dbc);
if($output_form){
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" name="submit" value="remove" />
</form>
<?php
}
?>
now,if no checkbox is checked, it gives the message , to select the checkboxes, but even if the checkboxes are selected , it still returns the message to select the checkboxes.
So, it is never enters the loop for delete query , aka$_POST['todelete'] is always empty, but it should not. u tried to check whether the $_POST array is empty , it didn;t comeup with any thing ,
i tried to go through a lot of answers ,but it seems my query was unresolved... Need help !!
What am i doing wrong with the code ??
It seems your checkbox was outside the form tag.
just replace your code with my code below:
//check for $_POST values
if((isset($_POST['submit']))&&(isset($_POST['todelete']))){
$output_form= false;
foreach($_POST['todelete'] as $delete_id){
$query = "delete from email_list where id = $delete_id";
mysqli_query($dbc,$query)or die('Error querying database.');
}
echo '<p>Customer entry removed</p>'.'<br />';
}elseif((isset($_POST['submit']))&&(empty($_POST['todelete']))){
echo "<p>you haven't selected any customer entry to delete!</p>";
$output_form= true;
}else {
$output_form= true;
}
//check if to show form
if($output_form){ ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$dbc= mysqli_connect('localhost','root','','customer_base')or die('Error connecting to MySQL server.');
$query = "select * from email_list";
$result= mysqli_query($dbc, $query)or die('Error querying database.');
while($row= mysqli_fetch_array($result)){
echo '<input type="checkbox" value="' .$row['id']. '"name="todelete[]" />';
echo $row['first_name'].' '.$row['last_name'].' '.$row['email'].' '.'<br />';
}
mysqli_close($dbc);
?>
<input type="submit" name="submit" value="remove" />
</form>
<?php } ?>
as i can see you're using mysqli, i recommend you move on to PDO.

Updating records, getting successful message but data isn't being updated in database

I am building a "edit_post" page for my site so users can edit what they have previously posted(duh), I am getting the notification "Updated data successfully" but the data isn't being updated in mysql
<?php
if(isset($_POST['update'])){
$topic_id = $_POST['topic_id'];
$topic_data = $_POST['topic_data'];
$invisipost = isset($_POST['invisipost']) ? $_POST['invisipost'] : 0 ;
$sql = "UPDATE `topics` SET topic_data='$topic_data', invisipost='$invisipost' WHERE topic_id = '$topic_id'" ;
$retval = mysql_query($sql);
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close();
}
else
{
}
?>
Here is my form code
<form method="post" action="">
Here are the fields in the form I am trying to update
<textarea name="topic_data" cols="50" rows="3" id="topic_data"><? echo $rows['topic_data']; ?></textarea>
<input type="checkbox" name="invisipost" value="<? echo $rows['invisipost']; ?>">
And the form submission code
<input type="submit" name="update" value="Update">
I hope I have provided enough informataion.
You query is still failing, you are seeing "Updated data successfully" because it is outside of the if statement.
Try this:
if(!$retval){ //query has failed, produce error
die('Could not update data: ' . mysql_error());
}
else{ //query is successful
echo "Updated data successfully\n";
mysql_close();
}

Categories