Jump to content

Arrays - Relate a button to a specific row


murtz

Recommended Posts

Hi.

 

Im really stuck on something! At the moment, Im scripting out an array of current registered members. The code is below...

 

<?php
if ($num > 0) { // If it ran OK, display the records.

echo "Currently, There Are $num Registered Members";
}
else
{
echo "There Are No Registered Members";
}
?></span></p>
  
<table border="1" align="center" cellpadding="10" cellspacing="0" bordercolor="#D6D6D6">
  <tr>
    <td height="30" bordercolor="#D6D6D6" bgcolor="#9BFFFF"><p class="style19" style="text-align: left;"> Student ID</p></td>
    <td height="30" bordercolor="#D6D6D6" bgcolor="#9BFFFF"><p class="style19" style="text-align: left;"> Full Name</p></td>
    <td height="30" bordercolor="#D6D6D6" bgcolor="#9BFFFF"><p class="style19" style="text-align: left;"> Course </p></td>
    <td height="30" bordercolor="#D6D6D6" bgcolor="#9BFFFF"><p class="style19" style="text-align: left;"> Email_Address </p></td>
    <td height="30" bordercolor="#D6D6D6" bgcolor="#9BFFFF"><p class="style19" style="text-align: left;"><span class="style19" style="text-align: left;">Delete Member</span></p></td>
  </tr>
    <?php			
while($row = mysql_fetch_array($result))
		{ 
?>
  <tr>
    <td><span class="style20"><?php echo $row["student_id"]; ?></span></td>
    <td><span class="style20"><?php echo $row["full_name"]; ?></span></td>
    <td><span class="style20"><?php echo $row["course"]; ?></span></td>
    <td><span class="style20"><?php echo $row["email_address"]; ?></span></td>
    <td><p class="style20" style="text-align: left;">
      <input type="submit" name="Deletemember" id="Deletemember" value="Delete Member" />
    </p></td>
  </tr>
<?php
   }
       ?>
</table>
<p align="center"> </p>

 

Here is a pic of the output...

 

420e6fa421.jpg[/img]

 

Basically.. after researching over the net.. I have no idea how to assign the delete button to the specific row that it is on! I dont know how to for example, press the delete button on the first row, and the value that it selects in the DELETE query is the first row.

 

Please help.. a solution for this would help me on other areas of my website aswell (for example.. a button that lets the user buy a book)

 

Thanks.. this site is seriously awesome!

Link to comment
Share on other sites

I would assign each button name uniquely identifiable, e.g.

 

<input type='submit' value='Delete' name='del_$row_id'>

 

where $row_id is the id for that specific row. this can also be used in a loop.

 

    <?php			
while($row = mysql_fetch_array($result))
		{ 
?>
  <tr>
    <td><span class="style20"><?php echo $row["student_id"]; ?></span></td>
    <td><span class="style20"><?php echo $row["full_name"]; ?></span></td>
    <td><span class="style20"><?php echo $row["course"]; ?></span></td>
    <td><span class="style20"><?php echo $row["email_address"]; ?></span></td>
    <td><p class="style20" style="text-align: left;">
      <input type="submit" name="del[<?php echo $row["id"]; ?>]" id="Deletemember" value="Delete Member" />
    </p></td>
  </tr>
<?php
   }
       ?>

 

with the above code you could create the query like so:

 

<?php

// connect to mysql

foreach($_POST['del'] As $id){
$query = "DELETE FROM `tablename` WHERE `id`='".mysql_escape_string($id)."'";
}
?>

 

hope this helps,

Link to comment
Share on other sites

this is achieved using ajax concept....

function del(id){

var url = "cont.php?mode=delete&id="+id;

//alert(url);

var xmlHttp;

if(window.XMLHttpRequest){ // For Mozilla, Safari, ...

var xmlHttp = new XMLHttpRequest();

}

else if(window.ActiveXObject){ // For Internet Explorer

var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

}

 

xmlHttp.open('POST', url, true);

xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xmlHttp.onreadystatechange = function(){

if (xmlHttp.readyState == 4){//alert(xmlHttp.responseText);

document.getElementById('ass').innerHTML = xmlHttp.responseText;

 

}

}

xmlHttp.send(url);

}

 

 

 

in cont.php page call the function ....

 

 

 echo "<td><input type=button value=Delete onclick=\"javascript:del($row[id])\"></td>";

Link to comment
Share on other sites

uniflare.. thanks alot for that mate!

 

Ive tried what u said.. and this is what my query looks like...

 


<?php

ini_set('session.gc_maxlifetime', 10);
session_start();

include('connect.php');

$tbl_name = "student";

mysql_connect("", "", "") or die ("Cannot Connect To The Database");
mysql_select_db("$dbname") or die("Cannot Select Database");

foreach($_POST['del'] As $id){
$query = "DELETE FROM student WHERE `id`='".mysql_escape_string($id)."'";
}

mysql_query($query)
or die ('New Listing was Unsuccessful, Please go back and try again');


?>

 

After I click the delete button.. I get a page saying 'New Listing was Unsuccessful, Please go back and try again'.. which basically says the query failed. Am I doing everything right?

 

Just to understand things.. when you said WHERE `id`='".mysql_escape_string($id)."'";, does `id` come from the button id?.. why is it around the `` quotes?

 

These questions probably really sound silly! sorry  ???

Link to comment
Share on other sites

Basically the `id` is the field name form the mysql table in the Database.

 

WHERE `id`='$id'

 

This is saying only match rows where the field "id" matches the string $id.

 

if you notice, foreach loops takes an array and spits out variables in a loop, iterating through each array value.

 

The backticks ( ` ) are used around tablenames and fieldnames, this is to show mysql exactly what we mean, it is cleaner code.

------------------

 

as for the unsuccessful query try adding mysql_error() to the or die() you already have, eg:

 

<?php

ini_set('session.gc_maxlifetime', 10);
session_start();

include('connect.php');

$tbl_name = "student";

mysql_connect("", "", "") or die ("Cannot Connect To The Database");
mysql_select_db($dbname) or die("Cannot Select Database ".$dbname);

foreach($_POST['del'] As $id => $value){
$query = "DELETE FROM `".$tbl_name."` WHERE `id`='".mysql_escape_string($id)."'";

mysql_query($query)
	or die ('Query Failed: <br>'.$query.'<br><br>MySQL Said:<br>'.mysql_error());
}

?>

 

Also take note of sasa' suggestion, i got my logic incorrect.

 

Good luck!

Link to comment
Share on other sites

Ignore this post if you've already read it! It works now! that error message from Uniflare did the trick. The problem I was having was that the student I was trying to delete existed as a friggin foreign key elsewhere!! ARGH! THATS ALL IT WAS  ;D

 

Uniflare and sasa you really are lifesavers I cant thank you enough!!

 

So.. it does delete the row.. however.. instead of going to my members page after its deleted.. it just goes to a blank page.. which makes me think that this isnt working..

 

if (mysql_affected_rows() ==1) 
header("location:members.php")

any ideas?.. I swear.. this place is heaven!

Link to comment
Share on other sites

Ignore my last post.. I finally managed to get it working! I might come back if I get stuck with my buy a book button.. basically this is what Im trying to do. As soon as a user clicks BUY BOOK.. the book ID, Buyer ID and Seller Id get posted into a transaction table.. and the book from the LISTINGS table (where it existed in the first place) gets deleted.. hopefully it should be straight forward!

 

Thanks once again for all the help! Cant tell you how much Ive appreciated it.

Link to comment
Share on other sites

Ok so i have come across a problem!

 

Everything above works. Now Im trying to apply the same type of logic for my BUY BOOK page.

 

Heres what the page looks like...

 

th.917f1902d9.jpg

 

Basically.. the first box is the first row in the search results.. and the second box is the second result.

 

when the user clicks BUY BOOK.. i want the p number in the SELLER field to get posted into a table called SALES.. aswell as the book title to be posted into sales table.

 

The sales table looks like this;

 

SALES (book-title, seller_id)

 

I dont know how I can incorporate the WHERE `id`='".mysql_escape_string($id)."'"; into an INSERT INTO statement!??

 

my PHP code that scripts out the seller id for the page above looks like this...

 

<?php echo $row["student_id"];?>

 

how can I fetch the value that the above code produces and put it in a variable so i can insert it into a table?

 

and also.. how can I make sure that the details i get are for the box where the buy book button is located?.. Ive tried doing INSERT INTO VALUES WHERE etc.. but that doesnt work.

 

Please help!  :(

 

Link to comment
Share on other sites

FYI - INSERT queries ADD a row, they dont change rows and they dont delete them.

UPDATE queries update specific fields of specific rows.

 

anything you want passed to another script from a form needs to be either a _GET or a _POST.

 

i cant see your image, have you got a url instead?

Link to comment
Share on other sites

buyhs7.th.jpg

 

hopefully the image above works.

 

ive managed to get bits of it working. Ive put some hidden fields next to the fields that I want outputting. Im managing to post the details I want into the SALES table.. but no matter which rows button i press.. it always uses the information from the LAST result.

 

Heres the code Ive got for the buy book button..

 

<input type="submit" name="buy[<?php echo $row["book_id"]; ?>]" id="Buybook" value="Buy Book" />

 

and heres the php page where my insert statement is..

 

$buyer=$_SESSION['session_name'];
$title=mysql_real_escape_string(trim($_POST['title']));
$author=mysql_real_escape_string(trim($_POST['author']));
$ISBN=mysql_real_escape_string(trim($_POST['ISBN']));
$seller=mysql_real_escape_string(trim($_POST['seller_id']));
$price=mysql_real_escape_string(trim($_POST['price']));

foreach($_POST['buy'] As $id => $value){
$query = "INSERT INTO sales(book_title, book_author, ISBN, price, buyer_id, seller_id, sale_date)
VALUES ('$title', '$author', '$ISBN', '$price', '$buyer', '$seller', NOW())";
}

 

Ive added the foreach line in there.. obviously at the moment its not doing anything.

 

thanks again Uniflare.

Link to comment
Share on other sites

Ill be honest.. I didnt understand any of that!

 

You want me to put each row in a different form?.. How will that work? is there no way to do this using similar logic to what I used when deleting a member?

 

(if your head hurts.. imagine what Im going through lol.. Im going mental!)

 

(ps.. thanks again!)

Link to comment
Share on other sites

ok what i mean is instead of this:

 

<form action="" method="post">
<input type="submit" value="Delete Row 1">
<input type="submit" value="Delete Row 2">
<input type="submit" value="Delete Row 3">
</form>

 

you would have this:

 

<form action="" method="post">
<input type="submit" value="Delete Row 1">
</form>
<form action="" method="post">
<input type="submit" value="Delete Row 2">
</form>
<form action="" method="post">
<input type="submit" value="Delete Row 3">
</form>

 

php can be quite annoying, but my headache is from cold air/running/tired etc :P

Link to comment
Share on other sites

Please mate that would really help! Its funny because Im actually starting to get my head round it all.. but this one is just confusing!.. what makes it worse is that I cant think of the right words to type in google to find tutorials!

 

Looking forward to your reply!

 

(take some vodka for that headache of yours!)

Link to comment
Share on other sites

Sorry for the long reply ;).

 

Also upon fully reading your post (instead of glancing over a very bright screen ;)) i think i see your problem,

 

try changing:

foreach($_POST['buy'] As $id => $value){
$query = "INSERT INTO sales(book_title, book_author, ISBN, price, buyer_id, seller_id, sale_date)
VALUES ('$title', '$author', '$ISBN', '$price', '$buyer', '$seller', NOW())";
}

 

to:

 

foreach($_POST['buy'] As $id => $value){
$query = "INSERT INTO sales(book_id, ISBN, price, buyer_id, seller_id, sale_date)
VALUES ('$id', '$ISBN', '$price', '$buyer', '$seller', NOW())";
}

 

This way when you look up the the invoice or w/e you can grab the book using the book_id located in the sales table row. This should also save a little space :)

 

Hope this helps :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.