Mysql database only entering one time - php

I am trying to enter new information into a database everytime a user clicks a submit button in my form. It works perfectly but it only works one time. So it will enter one row into the database and after that if the user fill out the form again and clicks submit no information will be entered into the database until i delete the previous row so it works if the database is empty. Here is my code to enter it into the database if you need more info to help let me know i will rate u up and everything thanks in advance
if($_POST['submit']){
$query = mysql_query("SELECT * FROM chanels WHERE cname = '$cname'");
$numrows = mysql_num_rows($query);
if($numrows == 1) {
echo "You Channel has already been added. Go back your <a
href='./memberpage.php'>Station Page.</a>";
}else{
if($_POST['description']){
$description = $_POST['description'];
if(strlen($description) < 250 ){
$code = $_GET['code'];
$category = $_POST['category'];
mysql_query("INSERT INTO chanels VALUES
('','$code','$cname','$category','$description',''
)");
echo "You Channel has been added. Go back your <a
href='./memberpage.php'>Station Page.</a>";
}else
echo "Your description must be less than 250 characters!";
}else
echo "You must enter a description!";
}
}

Your if else statement has limited the functionality.
You can add one row because of the line
if($numrows == 1){
after you add one row, the if statement condition is met, $numrows =1. At this point the else statement where you actually add rows to the database never runs!

You have a conditional specifying, if a record exist for the cname, don't do anything. I think that might have something to do with your insert only executing once. I don't know what the cname is, and if the cname differs after each submit, but if it doesn't you will never be able to get into the else conditional.
$query = mysql_query("SELECT * FROM chanels WHERE cname = '$cname'");
$numrows = mysql_num_rows($query);
if($numrows == 1){
echo "You Channel has already been added. Go back your <a href='./memberpage.php'>Station Page.</a>";
}

Related

PHP echo break tag

In my PHP script, there are 3 echo, based on the conditionals
echo "Error"
echo "User already existed"
echo "Success"
One of the echo will be passed to my android apps, if (s.equals("Success")), where s is the echo message.
But the echo I got when the registration success is <br />, according to the logcat. For User already existed have no problem.
Since s is not Success, I can't start another activity which is depended on the string. Can anyone explain how the break tag got echoed? The registration information successfully inserted into database, though.
elseif ($roleID == "C") {
$sql6 = "SELECT runnerID FROM tr_customer WHERE customerID = '$newID'";
$check4 = mysqli_fetch_array(mysqli_query($con,$sql6));
if(!isset($check4)) {
// add into db
$customerID = $roleID . $newID;
$sql7 = "INSERT INTO tr_customer(customerID, name, phoneNo, locationID, roleID, email) VALUES ('$customerID', '$name', '$phoneNo', '$locationID', '$roleID', '$email')";
if(mysqli_query($con,$sql7)) {
echo "Success";
}
} else {
$newID = checkExist();
}
I would examine the code where the variable is defined. If you could post that part of the code as an edit then perhaps someone can review it for you as well. There is just not enough information here to discern where your error is coming from.
EDIT:
Consider changing the way you check for a successful update.
$result = mysqli_query($con,$sql7);
if(mysqli_num_rows($result) == 1){
echo "Success";
}

PHP help: Follow System in Microblogging

I'm making a site similar to Instagram. I am very new to php. I created a follow button in the user's profile.
How do you make the follow button disappear when you already followed the user?
How do you replace it with unfollow button?
// my php code for following
if (isset($_POST['addfriend'])){
$fromuser = $user;
$touser = $username;
if($fromuser == $username){
$Msg = "You cannot follow yourself<br/>";
}
else
{
$getID= mysql_query("SELECT userID FROM user WHERE username='$user'");
$get_ID_row = mysql_fetch_assoc($getID);
$ID_db = $get_ID_row['userID'];
$sql = "insert into following (userID, fromUser, toUser)
values ('$ID_db','$fromuser', '$touser')";
$result = mysql_query($sql);
$Msg= "Success! <br/>";
}
}
else{
//Do nothing
}
//my code for the follow button
<form action="<?php $user;?>" method ="POST">
<?php echo $Msg; ?>
<input type = "submit" name ="addfriend" value = "Follow"/>
</form>
On the page where you are going to show the Follow or Unfollow button, first run a MySQL query to find out if you are already following the person:
$sql = "select * from following
where userID = $user
and fromUser = $fromUser
and toUser = $toUser";
$result = mysql_query($sql);
if( $result) {
if( mysql_num_rows($result) > 0) {
// if we get here we know we are already following that person
....[see below]
Now dynamically create whichever button you need:-
if( mysql_num_rows($result) > 0) {
// if we get here we know we are already following that person
echo '<input type = "submit" name ="removefriend" value = "Un-follow"/>';
}
else
{
echo '<input type = "submit" name ="addfriend" value = "Follow"/>';
}
And on the following page where you are getting the form results, check for both buttons:
if (isset($_POST['addfriend'])) {
...[do what you already have]
}
else
if (isset($_POST['removefriend'])) {
...[do SQL to remove the record from the following table]
}
Please be aware also that as of PHP v5.5 this style of MySQL is deprecated. At some stage in the future you will have to convert your programs to the MySQLi or PDO_MySQL extensions, before they eventually discontinue support. See the PHP manual about this at eg http://php.net/manual/en/mysqlinfo.api.choosing.php.
Would be easier with OO PHP. However, if you chose procedural, let's assume we have a table of friends. Which keeps the id of each of my friends.
e.g.: Smith follows John
Then you do something like
$following = mysql_query("SELECT COUNT(*) FROM followers WHERE followerid = ".$_SESSION['id']." AND followeeid = ".$username);
Check if You follow the person already:
if($following){//$following == true
}

How to make a button delete a row in my database that's also in my HTML?

I have some codes which pretty much gives me all of the Emails and Times from my database and puts it in my HTML. For every Email there is 1 Time. I pretty much want a delete button next to all of the Email+Time and when the button is pressed I want it to delete just that Email+Time. This is my code which gives me all the Emails + Times from my database:
require_once"database.php";
$result = $db->query("SELECT * FROM reserveringen");
if($result->num_rows != 0) {
$message = array();
while($rows = $result->fetch_assoc()) {
$Email = $rows["Email"];
$Tijd = $rows["Tijd"];
$message[] = "$Email $Tijd <input type='button' value='Verwijder afspraak' name='verwijderen'/>";
}
}
<?php
if($message) {
foreach($message as $value) {
?>
<p><?= $value; ?></p>
<?php
}
}
?>
I've tried some stuff and I do have a delete button next to every Email+Time, but how do I get it that when it's pressed to just delete the Email+Time that's next to it.
http://prntscr.com/5x08bl
EDIT:
Okay, let me try to be a bit more specific.
In my database I have a table called "reserveringen". In that table there are 2 columns called "Email" and "Tijd" Everytime when I add an Email and Tijd it automatically places a button next to it in my HTML.(See printscreen above). In this printscreen you can also see that there are 3 Emails + Tijds at the moment and they all have their own button next to it. I'm not a PHP-expert but I want that if I click on 1 of those buttons it deletes the Email + Tijd that's next to it. Not just in my HTML, but also in my database. I hope this is a bit more specific.
Your possible solution is to add an anchor tag on the button and post the id of the respective content along with it.
The anchor href has the value of the page that performs the deletion query of depending upon the received content id.
<input type='button' value='Verwijder afspraak' name='verwijderen'/>
where delete.php executes your deletion query according to the id(email id) you pass along with it.
On deletion page simply get this id with $_GET['id'] and perform the deletion query on the table.
After deleting redirect the page using header('Location:yourpage.php')
Surround your button with <a> tag and in href pass path to your controller and id that u want to delete
while($rows = $result->fetch_assoc()) {
$Email = $rows["Email"];
$Tijd = $rows["Tijd"];
$message[] = "$Email $Tijd <a href='delete?id=$Tijd'><input type='button' value='Verwijder afspraak' name='verwijderen'/></a>";
}
}
and then, in scirpt under delete, get the id that you passed via $_GET['id'] and remove it from database and then redirect to your view.

Send hidden variables from one page to another

I have a Login script that is on my home page for my Login form that is also on my home page. When the user submits the form to Login he/she submits his/her username and password.
The database that the script accesses has the Username, Password, and Email Address stored from the users registration.
Once the user logs in successfully, he/she is redirected to a page that loads their previous "reviews" on the page which are stored within a different table within the same database.
I need to send the email from one table to the query on the redirected page.
Here is the code of my PHP code that processes the Login:
<?php
//If the user has submitted the form
if(isset($_REQUEST['username'])){
//protect the posted value then store them to variables
$username = protect($_POST['username']);
$password = protect($_POST['password']);
//Check if the username or password boxes were not filled in
if(!$username || !$password){
//if not display an error message
echo "<center>You need to fill in a <b>Username</b> and a <b>Password</b>!</center>";
}else{
//if they were continue checking
//select all rows from the table where the username matches the one entered by the user
$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."'");
$num = mysql_num_rows($res);
//check if there was no match
if($num == 0){
//if none, display an error message
echo "<center>The <b>Username</b> you supplied does not exist!</center>";
}else{
//if there was a match continue checking
//select all rows where the username and password match the ones submitted by the user
$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'");
$num = mysql_num_rows($res);
//check if there was no match
if($num == 0){
//if none display error message
echo "<center>The <b>Password</b> you supplied does not match the one for that username!</center>";
}else{
//if there was continue checking
//split all fields from the correct row into an associative array
$row = mysql_fetch_assoc($res);
//check to see if the user has not activated their account yet
if($row['active'] != 1){
//if not display error message
echo "<center>You have not yet <b>Activated</b> your account!</center>";
}else{
//if they have log them in
//set the login session storing there id - we use this to see if they are logged in or not
$_SESSION['uid'] = $row['id'];
//update the online field to 50 seconds into the future
$time = date('U')+50;
mysql_query("UPDATE `users` SET `online` = '".$time."' WHERE `id` = '".$_SESSION['uid']."'");
//redirect them to the usersonline page
echo 'REDIRECT';
}
}
}
}
exit;
}
?>
Here is the PHP Code that is on the Re-directed to page:
<?php
$con=mysqli_connect("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM comments
WHERE email='$_POST[email]' ORDER BY dt");
while($row = mysqli_fetch_array($result))
{
echo $row['dt'] ." " . $row['email'] . " " . $row['body'];
echo "<br>";
echo "<br>";
}
?>
I need to add something to the first code to pick up the email address out of the table it uses to verify the Login information and send it to the second code to receive the "reviews." I have tried googling an answer and came up with nothing. Please help!
Since you have used the $_SESSION array in your code(which maybe is copied from somewhere), you can similarly store the email address in the same array.
$_SESSION['email'] = $row['email'];
In the later page, you'd need to replace $_POST['email'] with $_SESSION['email'].

submit one or another query

I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app.
I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present,
the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are
obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my
understanding (and guess-ology).
I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php,
etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other.
Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up)
cheers, s
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
and:
<form id="invoiceData" method="post" action="/html/form.php">
When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this:
<form
id="invoiceData"
method="post"
action="/html/form.php?ID=<?php echo $_GET['ID']; ?>"
>
This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure.
Hope this helps!
$_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to
<form id="invoiceData" method="post" action="/html/form.php?ID=12">
Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.

Categories