okay friends,
I have two tables
1st table: social_networks
2nd table: members_social_accounts
In the user control panel, I have a page contains a form where I list all the social networks; and in a front of each one of them there is an input text box.
When the member opens that page, he will see all the social networks listed, and if he previously added his account in any social network, then he will see it in the text box, otherwise, the text box will be empty. I used the following code to that:
$s = mysqli_query($link, "SELECT social_networks.network_id, social_networks.network_name, members_social_accounts.member_account FROM social_networks LEFT JOIN members_social_accounts ON social_networks.network_id = members_social_accounts.network_id AND members_social_accounts.member_id = '$member_id' ORDER BY social_networks.network_id");
while($i = mysqli_fetch_assoc($s)){
$network_id = $i['network_id'];
$network_name = $i['network_name'];
$member_account = $i['member_account'];
}
and the input box is:
<?=$network_name;?> = <input type="text" name="ids[<?=$network_id;?>]" id="<?=$network_id;?>" value="<?=$member_account;?>" /><br />
Now, what I am trying to do is when the user update the page (submit the form), I want the code to update the database by the following steps:
If the member (e.g. $member_id =1 ) has already added his account to that network (e.g. $network_id = 1) then, we will UPDATE the members_social_accounts table with the member network account (e.g. $member_account = 1111111111). So, I DO NOT add a new record for the same member_id and the same network_id but with different account value.
so, the database table will be something like this:
else if the member (e.g. $member_id=1) is adding a new account (e.g. $member_account = 2222222222) to a network (e.g. $network_id = 3), then I want to INSERT that to the members_social_accounts table as a new record, and the table will be for example like the following:
What I've tried so far is the following:
<?php
if(isset($_POST))
{
foreach($_POST['ids'] AS $ids)
{
$s = mysqli_query($link, "SELECT * FROM members_social_accounts WHERE network_id = '{$ids}' AND member_id = '$member_id'");
echo $n = mysqli_num_rows($s);
if($n == 1)
{
// UPDATE the members_social_accounts table
}
else
{
// INSERT a new record in members_social_accounts table
}
}
}
?>
but I have a problem which is that $_POST[ids] AS $ids is getting the member_account (e.g. aaaaaaaaaa and bbbbbbbbbb) instead getting the netword_id (e.g. 1 and 2). Therefore, I am not able to update or insert in the members_social_accounts table.
I appreciate your help in pointing what is wrong with my code or logic.
Thanks in advance
P.S. You can download a copy of the files and the database from this link:
sample files and db
This is due to the fact that the actual value of your input is the member_account field.
<input type="text" name="ids[<?=$network_id;?>]" id="<?=$network_id;?>" value="<?=$member_account;?>" />
Take a look at the value which has been assigned the return from $member_account variable.
You could just do:
<input type="hidden" name="nid" value="<?=$network_id;?>"/>
Then you can do $_POST['nid'] to get the real value of the network id.
Related
Mission: Verify that "players" have placed vintage promotional jpegs on their social media site(s). Doing so earns them crypto tokens towards game play. All non-verified postings are displayed on an administrator's dashboard with a checkbox if the listing has been visually verified and "Approved." The value of each checkbox is the database ID of the listing (see screen capture). Once the listings have been verified and the check box ticked, the page is POST(ed) to a query page where the default value "confirm" is changed from 0 to 1. This then awards them the designated tokens.
enter image description here
However, I haven't found the right formula of code to get the UDPATE to work. The checkbox values will display in "echo" mode, but the SQL won't function within the FOREACH loop.
<?php
$checked_arr = $_POST['checkbox'];
$count = count($checked_arr);
echo "There are ".$count." checkboxe(s) are checked <br>";
foreach($_POST['checkbox'] as $val) {
$sql = "UPDATE media SET confirm = 1 WHERE id = $val " ;
echo "$val\n";
?>
Scoured the Net for working examples, including Stack Overflow, but to no avail. Assume there's a simple answer here, but as a novice PHP programmer, it eludes me.
Thank you in advance for suggestions.
you could use the IN operation in the conditional.
The only thing you would have to do is capture all the IDS and do an "implode" to give it the format that is needed for the sql.
for example:
<?php
$ids = [];
foreach($_POST['checkbox'] as $val){
$ids[] = $val;
}
$values = implode(",", $ids); // => 'id1, id2, id3, ...'
// this is a massive update based on selected items
$sql = "UPDATE media SET confirm = 1 WHERE id IN ($values)";
?>
I have a Table where user can create row with adding input fields dynamically (combination with jquery). I'm successfully able to insert it into the mysql database.
If users want to edit the added already existing fields, I have an edit page where the values are fetched from the mysql DB and populated again into the dynamically creatable table.
Now there are the below probabilities:-
User only makes minor changes on the existing values. In that case
the table has to be UPDATED with the changed values
User Deletes one/multiple row(randomly selected and as per users wish). So when form submitted the php query should only DELETE that perticular row/s in the DB.
User ADDS another row to the previous existing row values, in that case the php query should UPDATE the previous values and INSERT the newly added row values.
The above sequence is not necessarilly restricted the same order. User can perform all the above three function simultaneously at the same time.
Now my problem is(only for the backend) I'm finding a hard time to frame a php & sql query so as to update to the mysql.
my php
if(isset($_POST['submit'])){
$number1 = count($_POST['item']); //
for($i=0; $i<$number1; $i++){
$item = strip_tags(trim($_POST['item'][$i]));
$description = strip_tags(trim($_POST['description'][$i]));
$unitcost = strip_tags(trim($_POST['unitcost'][$i]));
$qty = strip_tags(trim($_POST['qty'][$i])); // Quantity
$sno = strip_tags(trim($_POST['sno'][$i]));// serial number
//QUERY1 if minor updates to above variable then UPDATE (eg, qty value is changed from 3 to 4)
//QUERY2 if row is deleted then DELETE that particular row from db (eg, sno 3 deleted from the table should DELETE corresponding mysql DB values also)
//QUERY3 if row is added then that particular row values should be INSERT (eg, sno 4 is added which is not in the mysql db. So this has to be INSERTED.)
}
}
Pardon me to have asked such question. I'm wasting a whole lot of time with the above queries unable to execute properly. I only require an idea not necessarily the whole code.
Hope all of you out there would advice me some ideas on how this could be implemented. Thanks for the help in advance. Expecting a positive reply.
NB: Just to remind you again, The front end is a Dynamically ADD/DELETE Input Field table
This sounds like a frontend problem. You need to define how you tell the backend whats happening.
<input name="items[$i][name]" />
This will show up as nice array to loop through in php.
foreach($_POST[items] AS $item){
if( $item['delete'] ){
//delete code
}
}else{
//Insert/Update
}
If you want to delete something simply make the field hidden and add a flag to it.
<input type="hidden" name="items[$i][delete]" value="1" />
<input type="hidden" name="items[$i][id]" />
Thank for the reply, appreciate #ckrudelux and #codefather for their intention to help me.
Although their advise didn't help me to structure my query. So I had a long workaround and found out below solution. I'm posting the solution because I couldn't find any article online when it comes to UPDATE/DELETE a dynamically generated input table.
Hope this would be of help to someone.
So what I did basically is that I took all the values into array.
In my dynamically generated add input table code, I added an <input type="hidden" name="sno[]" value="newrow">. So this will be clubbed with the form post. I'm using the normal html post and not ajax.
now my submit.php has ben changed to below
if(isset($_POST['submit'])){
$productid = $_POST['productd'];// No striptag functions
// due to illustration purpose
// First of all, we need to fetch the querying db table.
// This is required in order to compare the existing row values
// with the posted values
$fetchproduct = $link->prepare("SELECT * FROM product WHERE productid=?");
$fetchproduct ->bind_param('s',$productid);
$fetchproduct ->execute();
$fetchresult = $fetchproduct ->get_result();
$serialnumber=array(); // Assigning array to fetch the primary key: Serial Number
while($row = $fetchresult->fetch_assoc()){
$serialnumber[] = $row["sno"];
}
//Newly Inserted Values
//$_POST['sno'] is taken from the dynamic input field defined earlier in this post.
//Basically what we are doing here is we are comparing (the values
//which have been posted from the primary page) and (values present in the db table).
//The difference will give an array of newly inserted table input field values
$insert = array_diff($_POST['sno'],$serialnumber);
//Deleted Values
// This will Difference those values in the db table and values which are
// deleted from the primary dynamic table page
$delete = array_diff($serialnumber,$_POST['sno']);
$countdelete = count($delete); // Counting how many values have been
// lined up for deleting
//Updated Values
// array_intersect will give us the common values present in both the array.
// This means that there is no deletion or insertion to the dynamic table fields.
$intersect = array_intersect($serialnumber, $_POST['sno']);
$update = array_values($intersect);
$countupdate = count($update);
//INSERT ADDED VALUES TO DB
foreach($insert as $key=>$ivalue){
// ID
if(isset($_POST['id'][$key]) && !empty($_POST['id'][$key])) {
$id = strip_tags(trim($_POST['id'][$key]));
}
// ITEM
if(isset($_POST['item'][$key]) && !empty($_POST['item'][$key])) {
$item = strip_tags(trim($_POST['item'][$key]));
}
// DESCRIPTION
if(isset($_POST['description'][$key]) && !empty($_POST['description'][$key])) {
$description = strip_tags(trim($_POST['description'][$key]));
}
// UNITCOST
if(isset($_POST['unitcost'][$key]) && !empty($_POST['unitcost'][$key])) {
$unitcost = strip_tags(trim($_POST['unitcost'][$key]));
}
// QUANTITY
if(isset($_POST['qty'][$key]) && !empty($_POST['qty'][$key])) {
$qty = strip_tags(trim($_POST['qty'][$key]));
}
// AMOUNT
if(isset($_POST['amount'][$key]) && !empty($_POST['amount'][$key])) {
$amount = strip_tags(trim($_POST['amount'][$key]));
}
// INSERT INTO THE DATABASE
$inserttable = $link->prepare("INSERT INTO product (productid, item, description, unitcost, qty, amount) VALUES(?,?,?,?,?,?)");
$inserttable->bind_param('ssssss', $id, $item, $description, $unitcost, $qty, $amount);
$inserttable->execute();
if($inserttable){
header( 'Location:to/your/redirect page.php' ) ; // NOT MANDADTORY, You can put whatever you want
$_SESSION['updatemsg'] = "Success";
}
}
//UPDATE EXISTING VALUES TO DB
for($j=0; $j<$countupdate; $j++){
// ID
if(isset($_POST['id'][$j]) && !empty($_POST['id'][$j])) {
$uid = strip_tags(trim($_POST['id'][$j]));
}
// ITEM
if(isset($_POST['item'][$j]) && !empty($_POST['item'][$j])) {
$uitem = strip_tags(trim($_POST['item'][$j]));
}
// DESCRIPTION
if(isset($_POST['description'][$j]) && !empty($_POST['description'][$j])) {
$udescription = strip_tags(trim($_POST['description'][$j]));
}
// UNITCOST
if(isset($_POST['unitcost'][$j]) && !empty($_POST['unitcost'][$j])) {
$uunitcost = strip_tags(trim($_POST['unitcost'][$j]));
}
// QUANTITY
if(isset($_POST['qty'][$j]) && !empty($_POST['qty'][$j])) {
$uqty = strip_tags(trim($_POST['qty'][$j]));
}
// AMOUNT
if(isset($_POST['amount'][$j]) && !empty($_POST['amount'][$j])) {
$uamount = strip_tags(trim($_POST['amount'][$j]));
}
// UPDATE THE DATABASE
$updatetable = $link->prepare("UPDATE product SET item=?, description=?, unitcost=?, qty=?, amount=? WHERE sno=?");
$updatetable->bind_param('ssssss', $uitem, $udescription, $uunitcost, $uqty, $uamount, $update[$j]);
$updatetable->execute();
if($updatetable){
$_SESSION['updatemsg'] = "Success";
}
}
//DELETE VALUES FROM DB
foreach($delete as $sno){
$deletetable = $link->prepare("DELETE FROM product WHERE sno=?");
$deletetable->bind_param('s', $sno);
$deletetable->execute();
if($deletetable){
$_SESSION['updatemsg'] = "Success";
}
}
}else {
$_SESSION['updatemsg'] = "Error";
}
}
PHP
<?php include("connect.php");?>
<?php
$activityoneid = "select activity.activity_name,activity.activity_id
from activity
join serviceactivitymap on activity.activity_id = serviceactivitymap.activity_id";
$activityonevalue = $conn->query($activityoneid) or die ($conn>error.__LINE__);
$activitiesone = [];
while ($row = $activityonevalue->fetch_assoc()) {
$activitiesone[] = $row;
}
//for services
$service = "select * from service";
$servicevalue = $conn->query($service) or die ($conn>error.__LINE__);
$services = [];
while ($row = $servicevalue->fetch_assoc()) {
$services[] = $row;
}
foreach($services as $serve)
{
?>
<input type = "checkbox" name = "service" value="<?php echo $serve['service_id']?>">
<?php echo $serve['service_name']?>
<br>
<?php foreach($activitiesone as $activiti)
{
?>
<input type = "checkbox" name = "activity" value = "<?php echo $activiti['activity_id']?>">
<?php echo $activiti['activity_name'];?>
<?php
}
?>
<br>
<?php
}?>
Here is my code for display service and activity
## Recent Output ## :-
all services display same activity ,can I filter data using service_id means display activity related to service id,if service id = 1 then display only activity related to 1 not others
RECENT OUTPUT:
Incometax
Return Filling
Revised Return Filling
Tax Payment
Statutory Audit
TDS
Return Filling
Revised Return Filling
Tax Payment
Statutory Audit
Expected output:-
Incometax
Return Filling
Revised Return Filling
TDS
Tax payment
Statutory Audit
see in mapping Third mapping table, I will display Output from mapping table
Thank you
Using your sample data, I came up with a simpler solution. Your code is trying do to, in two steps, what the database can do for you.
Your first query gets the services. Then each associated activity is listed, service by service. This method, although it works, causes the database to be accessed twice. The database can do this for you, using SQL.
Here is the query:
SELECT s.service_name,
a.activity_name
FROM service AS s
JOIN service_has_activity AS sha ON s.service_id = sha.service_id
JOIN activity AS a ON a.activity_id = sha.activity_id
ORDER BY s.service_name, a.activity_name
The result is:
Incometax Return Filing
Incometax Revised Return Filing
TDS Statutory Audit
TDS Tax Payment
This query uses JOIN to "link" together the service, activity and service_has_activity tables. Then using ORDER BY sorts the data how you want it.
If you want to filter based on certain conditions, you can add WHERE clause(s) in the query. Ex. if you want to see only the data for a particular service, add this line before the ORDER BY line:
WHERE s.service_name = 'IncomeTax'
Then you can code a loop on these results to take care of the display. It is always more efficient to let the database do these, if it can, and only do the display portion in the PHP code.
The end result is 1 loop (for displaying the results), 1 access to the database (for running the query). If you have a large data set, it will speed up your page as well.
Ive been battling away with the following problem
Ive got a page where I pull names from players specific to their positions in a sport squad.
Example: I will display all the Wings in the squad using a dropdown where a coach can then pick his wing for the game.
There are dropdowns for each different position
The aim of the page is to let the coach quickly select his team for a fixture
After the coach selected his team he will, select the opponents for which the selected team will play against.
When he clicks submit the selected oppents and players will get stored in two arrays which will get called to display the team selected and their opponents on a new page. (After which it will get uploaded to the DB.)
I am having trouble getting the values from the select list to display on the new page.
I guess I have to do something like this on the new page:
foreach ($_REQUEST['opponents'] as $opponents){
print $opponents;
echo'<br>';
}
but it is not giving the desired results.
Strangely what gets printed is the variable name from the previous page select menu.
Upon further inspection I did a vardump on the new page and it says that $opponenets gets passed a value of string which is the variable name and not the value thereof?
My page looks like this
My question is how would I go abouts getting the values from the select dropdowns
if(isset($_POST["submit"]))
{
foreach ($_REQUEST['opponents'] as $against){
var_dump($against);
print $against;
echo'<br>';
}
}
else
{
echo'<h1>Select your Team</h1>';
$x = array("THP", "HKR", "LHP", "LH", "FLH"); //players positions gets assigned to x which will be used to query the database
echo '<form name="playerselect" method="post" action="">';
//query database with different query after each loop
for ($i = 0; sizeof($x) > $i; $i++)
{
//query where position field equeals variable x
$result = mysql_query("SELECT `name`, `position` FROM `player_info`
WHERE `position` = '$x[$i]'") or die(mysql_error()) ;
//Gets data from DB and assigns values to arrays below
while($row = mysql_fetch_array($result))
{
$playername[] = $row['name'];
$position[] = $row['position'];
}
//print player position
print $position[0];
echo'<br>';
//unset the array so that it is empty for the next query in the new loop
unset($position);
echo '<select name="players[]" >' ;
foreach ($playername as $name )
{
//Put playernames relevant to the position in the option element
echo'<option value="$name" selected="selected">'.$name;'</option>';
echo'<br>';
}
echo'</select>';
//unset array so that its contents is empty for the next query in the new loop
unset($playername);
echo'<br>';
}
You cannot. Your submit will only transmit select values. This is not a bug, it is a feature. You do not want to send data back and forth from/to the server/client which is known to both of them.
On the server you are free to query your database at any time. You can also cache your select list into the $_SESSION variable in your initial list read. However this is advanced fittling as your cache list may become outdated and also your server memory utilization must leave space for file caching (the SESSION cache goes to files).
If you go for the database query you may need some ID as sort of anchor. Just put the into the $_SESSION variable - eg.:
$_SESSION['positions']=$x;
In your example the $x seems to be static, which obviously reduces the need to cache it into the $_SESSION - however on other occasions you may need this method.
I've an issue, which is about php syntax/mysql in drupal:
Let's say that userA has created a content type called "test" where he filled the field field_example with value "xxx". Afterwards, another user, userB has created another content and filled the same field field_example with the same value "xxx".
I'd like to know how is it possible to display a view only with the node created where the field field_example is the same for the current user ? I don't have (and i don't want) a user reference in the content type "test" i'm using.
I've looked through View PHP Filter, but i'm wondering how to compare values of field ? Here's my attempt [i'm not an expert in PHP as you'll might notice :) ] :
<?php
$a="SELECT uid FROM users WHERE uid=%d";
/* ??? How to create $b which can get value of field_example from content_type_test from current user which is logged in ? */
$b="";
$c="SELECT field_example FROM content_type_test";
if ($b==$c){
echo "Ok, I've what I want :) ";
}
?>
Any help would be greatly appreciated since it's been a while i'm looking for information about this query...
Thanks all :)
I don't have a Views module solution.
One thought that comes to mind is what if User A submits multiple nodes, which example value would you use then? Also, what version of Drupal are you working with?
Assuming that a user will only ever submit one content of this type and you are running Drupal 6 (my guess from code examples), then it might look something like this:
<?php
// current user
global $user;
// select this user's node
$nid = db_result(db_query("SELECT nid FROM {node} WHERE type = 'my_content_type' AND status = 1 AND uid = %d", $user->uid));
// if this node loads fine, then proceed with the rest
if ($node = node_load($nid)) {
// find nodes with the same example value, which do not belong to the current user
$result = db_query("SELECT nid FROM {node}
INNER JOIN {content_type_test} ctt ON n.vid = ctt.vid
WHERE n.status = 1 AND ctt.field_example_value = '%s' AND uid <> %d
ORDER BY n.created DESC", $node->field_example[0]['value'], $user->uid);
// loop through results
while ($row = db_fetch_object($result)) {
$node = node_load($node->nid);
// append the teaser output (if this is what you want to do)
$output .= node_view($node, TRUE);
}
// print the output
print $output;
}
else {
print t('No other content found.');
}
?>
If users submit more than one of those content types, then that would have to be another answer to avoid from writing a novel here. There's a couple ways to approach that.
Also if this was Drupal 7, I'd be using different functions as well.
I assume you want something like this:
function _get_list() {
global $user; // This is global variable, contains information for current logged in user.
$results = db_query("SELECT ctt.field_example FROM {node} n JOIN {content_type_test} ctt ON n.nid = ctt.nid AND n.vid = ctt.vid WHERE n.uid = %d", $user->uid);
while($row = db_fetch_object($results)){
//$row->nid.. etc..
}
}