PHP/MySQL question [facebook-related] - php

Okay... I'm having the following problem - in my facebook application I let people add quotes sending them to my DB with their user_id, post_id and date. Then there's a browse page where people see the posts - so far, so good. But then I add a button that lets my users set the said post as their status. Still all good. However when I hit the button what it does is setting all the posts in the DB as my status, one by one until they all print out as my statuses. I'm sure that it is because of the 'while' function I use and because I am not sure how to print out all posts and being able to add to each the said button, holding only the specific post_id from the db ._.'
So in other words, it is a PHP/MySQL problem mainly, so even if you are not familiar with FBML, you can still help me out with the code...
Think of it as a list of posts and each should have a button doing something and being somehow attached to only the specific post.
The code is the following:
.... some code here ....
$query = 'SELECT * FROM tb_table ORDER BY `time` DESC';
$results = mysql_query($query);
---some other code---
while($line = mysql_fetch_assoc($results)) {
echo '<TABLE BORDER=0><TR VALIGN=TOP><TD>';
echo "<fb:profile-pic uid=".$line['userid']." size='square' facebook-logo='true'></fb:profile-pic></TD>";
echo "<TD>".$line['postid']."<br>"."<br>"."Posted by: ".$data['first_name'].$data['last_name']."<br>".date("F j, Y, g:i a", $line['fb_time'])."</TD>";
//Problems start from here
echo $facebook->api_client->users_setStatus($line['postid']) ;
echo '<div id="statusdiv" style="display:<?=$visibility;?>;">
<form method="POST">
<input type="submit" value="change status" />
</form>
</div> ';
echo "</TR></TABLE><br>";

The thing you're doing now is every time you loop through your mysql resultset you call the users_setStatus function which then sets your status (for every iteration).
You want to add a hidden input field to the form which contains the $line['postid'] and then call users_setStatus after a POST of the form. In that way you only change your status once.
Update
Remove the call to users_setStatus from the while loop.
Change your form like this:
echo '<div id="statusdiv" style="display:<?=$visibility;?>;">
<form method="POST">
<input type="submit" value="change status" />
<input type="hidden" name="line" value="'.$line['postid]'.'" />
</form>
</div> ';
Then, catch the POST variable upon submitting. With something like:
if (isset($_POST['line'])) {
echo $facebook->api_client->users_setStatus($_POST['line']) ;
}
See http://www.w3schools.com/php/php_forms.asp for more info.

Related

Is it possible to GET data from two pages ago?

I am creating a database wherein users can select a title (search.php) and then the specific page for that title will be shown with its corresponding details (indiv.php).
They will be able to select a title from search.php and here is the code for the title link:
<a href="indiv.php?titleID=' . $row['titleID'] . '">
Then the indiv.php will be able to show the details for that title based on the titleID they have selected from search.php. Here is the code for indiv.php:
<?php
include "databaseconnect.php";
$titleID = $_GET["titleID"];
$sql = ("SELECT titleID, authorsID, yearID,
FROM table
WHERE titleID = '$titleID'");
$result = $mysqli->query($sql);
$row = mysqli_fetch_assoc($result);
$mysqli->close();
?>
In this indiv.php, I also added a comment section form.
<form action="indiv.php" method="POST">
<input type="text" name="nameID" placeholder="Enter your name" required>
<textarea name="commentID" placeholder="Write your comment here" required></textarea>
<input type="submit" name="submit" value="Post Comment">
</form>
The problem is, every time I try to submit a comment, the page refreshes and does not show its corresponding details (just shows an error - see below) because $titleID = $_GET["titleID"]; cannot fetch the titleID anymore from search.php but tries to find it in indiv.php because of my <form action="indiv.php" method="POST"> in the comment section. Is there a way to prevent this from happening? I want to still be able to show the details based on titleID even after posting a comment.
The error is: Notice: Trying to access array offset on value of type null in...
Thanks in advance! I am not familiar with PHP so I hope you can help me out.

PHP foreach executing code multiple times

At the bottom of this code you'll see an 'Accept Offer' button, when I click on that another piece of code gets executed as you can see on the bottom of this post.
For example this project has 3 bidders, so 3 times bidder_id and writer_bid so I use 'foreach' and load it in divs, works fine, but now I need to store those variables in a database, which technically works but it doesn't store the bids from the row I pull them from, it just takes the data from the last row, that is if I place the code at the bottom of this thread in my header.
However when I put it inside the loop it executes three times, I saw that when I got an error message that I had to close 3 times cause there are 3 rows in the database table that I pull the data from.
How can I prevent this, and either have it load once when the code is inside the foreach loop, or have it pull the correct writer_bid and bidder_id to store.
<div class="WB-Bottom-block lefts">
<?php $getBidders=" AND project_id=$project_id"; $bidders=getBidder($getBidders); foreach($bidders as $bidder) {
$bidder_id=$bidder['writer_id'];
$writer_bid=$bidder['writer_bid'];
?>
<div class="findwriters_boxes">
<div class="findwriters_right">
<div style="float:right;margin-top:6px;width:170px;">
<input type="hidden" name="writer_bid" id="writer_bid" value="<?php echo $writer_bid; ?>" />
<input type="hidden" name="bidder_id" id="bidder_id" value="<?php echo $bidder_id; ?>" />
<input type="submit" class="homebtn11" name="submit" id="submit" value="Accept Offer"/>
</div>
</div>
</div><?php } ?>
Below the code that needs to be executed and that results in issues, whether I place it inside the foreach loop, or inside the header instead.
As you can see I tried to store it in input fields so that it stays there so the header can pull it on refresh of the page / click of the button.
<?php if(isset($_POST['todo']) && $_POST['todo']=='submit_project') {
$balance=get_client_balance_info($current_user->ID);
$writer_bid=$_POST['writer_bid'];
$bidder_id=$_POST['bidder_id'];
if($balance >= $_POST['writer_bid']) {
global $wpdb;
$sql3="UPDATE `wp_project` SET `writer_id` = '".$bidder_id."' WHERE `id` =". $project_id;
$wpdb->query($sql3);
$sql4="UPDATE `wp_project` SET `price` = '".$writer_bid."' WHERE `id` =". $project_id;
$wpdb->query($sql4);
$sql5="UPDATE `wp_project` SET `status` = '2' WHERE `id` =". $project_id;
$wpdb->query($sql5);
$success_msg="You accepted a bid, the money will be deducted from your account.";
}
else $fail_msg="Your balance is not sufficient.";
I think you should make a form for each div that you are adding right now you are putting the bidder_id in the different inputs but the same name.
So it will get the last inputs, maybe it's better to specify the inputs with the row id or to separate the forms or make the input names as array.
I hope this helps you.
I fixed it with the help of Diar Selimi like this:
<div style="float:right;margin-top:6px;width:170px;">
<form action="" name="frmeditor" method="post" id="frmeditor" >
<input type="hidden" name="todo" id="todo" value="submit_project" />
<input type="hidden" name="writer_bid" id="writer_bid" value="<?php echo $writer_bid; ?>" />
<input type="hidden" name="writer_id" id="writer_id" value="<?php echo $writer_id; ?>" />
<input type="submit" class="homebtn11" name="submit" id="submit" value="Accept Offer"/>
</form>
Before that my form and value="submit_project" tags were scattered all over the place!

PHP retrieving variables from a large SQL result set

I have been working on my own PHP project. I have hit an obstacle. I am trying to retrieve the results of a database and print out a form for each result set.
I then wish to interact with one particular result either be deleting it or passing it into a function etc..
Heres is my current code :
<?php
while($row = mysqli_fetch_array($result)){
echo '<div id="post">'; ?>
<form action="" method="post">
<?php
echo "<font size=4>".$row['post']."<br>";
echo "posted by : ".$row['username']."<br>";
$id = $row['p_id']; ?>
<input type="submit" name="choice" value="Y">
<input type="submit" name="choice" value="N">
</form>
<br>
</div>
}
<?php
if($_POST['choice']=="Y"){
// progress
functionA();
}
else if($_POST['choice']=="N"){
// delete or remove
functionB();
}
?>
So my goal here would be click Y to progress that particular result or N to delete/remove the result.
However currently by clicking either button all results either get deleted or progress. I do know that the id should be used to differentiate between posts but I cant quite seem to get it to work. Once the button is pressed it passes all results to either function.
First of all, I suppose you want to know the record to delete. So, add an input to your form:
<input type="hidden" name="id" value="<?php echo $row['p_id']; ?>">
Then, in your script, call:
if( $_POST['choice'] == "Y" )
{
// progress
functionA( $_POST['id'] );
}
elseif( $_POST['choice']=="N" )
{
// delete or remove
functionB( $_POST['id'] );
}
Additional problem: how you can use your db connection inside the functions? Assuming your mysqli connection is named $conn, call the function(s) in this way:
functionA( $_POST['id'], $conn );
Side note: First process $_POST values, then retrieve db records and print it.
Side note 2: take a look at prepared statement.
Read more about variable scope
Read more about prepared statements
Use two different <input type="radio">s for each item with the id in the value and let the user select which to delete and which to process.
So for an item with id 1 the outputted HTML would look like:
<input type="radio" name="items[1]" value="delete"><input type="radio" name="items[1]" value="process">
The name forces the items to go to _POST as an array with the ids as keys and the selected action as their values.
Example html: https://jsfiddle.net/gu1gkwod/

PHP with input form with text - do a MySQL query when form focus changes

I am looking for some help about how to make input form handling in PHP.
What I need is when a user writes data into a text form (table1), and moves to another text form (like pressing TAB, or selecting with mouse), then it should start and MySQL query to see if such data written at table1 already existing in the matching MySQL table.
My goal is like to do it without pressing submit button. Something like when google checks if an username you want to register already exists.
I am thinking about something like this:
$duplicate_data_test ="";
if (focus has moved to another form field - how to check ?) {
$query = "SELECT table1 FROM testdatabase WHERE table1 = "' . (table1 from the form below - how to get data from the this form field without POST?) .'";
$result = mysqli_query($con,$query);
if(mysqli_num_rows($result)>0) {
$duplicate_data_test = "This data is already found in the database. Choose something else";
}
}
echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">';
echo '<input type="text" maxlength="30" name="table1">';
echo '<span class="duplicaterror">'. $duplicate_data_test.' </span>';
echo '<input type="text" maxlength="30" name="table2">';
echo '<input type="submit" value="OK">';
echo '</form>';
Thank you very much for your help!
You cannot do your "interface" check with php.
Your "focus has moved to another form field" has to be done with javascript.
First, Build your form with html like this
<form name="testForm" action="postForm.php" method="POST" id="myForm">
<label>INPUT 1 : </label>
<input type="text" id="in1" value="" name="input1" />
<label>INPUT 2 : </label>
<input type="text" id="in2" value="" name="input2" />
<div style="color:red;font-weight:bold;" id="error"></div>
<button id="submitButton">SUBMIT</button>
</form>
Then make your checks when user clicks on submit button with javascript/jquery & ajax (prevent event form posting) like this :
$(document).on('click','#submitButton',function(event){
event.preventDefault();
if($.trim($('#in1').val()) == ''){
//input 1 is empty
$("#error").html('INPUT ONE IS EMPTY');
}//....continue checks
Finally, if your checks are good, then post your form
$("#myForm").submit();
and if your checks are not good then display user a message!
$("#error").html("MESSAGE!");
I made you a little example on how to do it (it's not the best way to do it but it's just an example) on jsfiddle, check this link : http://jsfiddle.net/9ayo89jt/2/
hope it helps!
checking if something exists will need an AJAX call
put the query that checks the database in a separate php file and call it with AJAX
to submit once all input fields are filled, you will need to use javascript .. check if field 1,2,3,..etc. are not empty .. formName.submit()
this is a bad approach in my opinion

Cant get $_POST values from multiple forms

i got a bit of a problem, as you guys can see in my code, i got a foreach looping through my img folder, showing all the images, well i left out the proper styling of the images, since the problem is the form inside every image.
i need to get the value from the radio input, so i can tell my other script to select all the info from the DB where the ID has the same value as the input.
and i needed a if statement so that if nothing is set i can show something saying you need to select a radio before you can listen to any stations.
but my if statement keeps showing 'error', even tho i click on the buttons
i hope anyone could help me out :)
if(isset($_POST['submitRadio')):
$test = $_POST['radio'];
echo $test;
else:
echo 'error';
endif;
foreach(glob('img/radios/big/*.png') as path):
printf('
<form method="post">
<input class="hidden" type="text" name="radio" value="1">
<input type="submit" name="submitRadio" value="Go!">
</form>
');
endforeach;
after doing what GolezTrol told me to do:
<div class="row text-center">
<?php
$sql = "SELECT * FROM radio";
$stmt = $Db->dbh->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
if(isset($_POST['submitRadio'])):
$test = $_POST['submitRadio'];
echo $test;
else:
echo 'error';
endif;
?>
<form method="post">
<?
foreach($result as $radio):
printf('
<button type="submit"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
?>
</form>
I've removed my previous solution. I only just saw that you have no actual radio button but hidden elements, so basically the buttons are the radios.
That changes it a little bit because you actually have the alternative suggestion I proposed earlier: The buttons themselves work as radiobuttons that immediately post the chosen option.
To solve your issue, you can use a button instead of an input for submitting the form. In a button, you can make the caption and the value differ from each other, so you can just put the id (or filename, or whatever you need) in the value of the button and don't need the hidden input at all. The content of the button tag is the caption it gets, so the code can look like this:
if(isset($_POST['selectedFile')):
$test = $_POST['selectedFile'];
echo $test;
else:
echo 'error';
endif;
?><form method="post"><? // Open the form outside of the loop
foreach(glob('img/radios/big/*.png') as path):
// Not sure what you want to do here. Put the filename instead of
// "1" in the value?
$filename = basename($path, '.png');
?>
<button type="submit"
name="selectedFile"
value="<?=$filename?>">
Go!
</button>
<?
endforeach;
?></form><? // Close the form
In this example I've pulled the form tags out of the loop, because strictly you only need one form. But since there are now no radiobuttons at all, you could also have one form per button. It would still work.
By the way, I saw you mentioned a database in your comment. Of course I didn't take that into account, since you didn't mention that in the question. Anyway, it shouldn't change the basic concept, only the way the 'value' is determined.
First, the value code in radio tag is always 1. So if any radio button is selected, you will always gets 1. Instead the value clause should have the filename. So you get to know which image (radio button) is selected.
For none of the image (radio button) selected, you may use
if (!isset($_POST['radio']))<br>{<br>//php code }

Categories