how to give a link to execute this - php

$sql=mysql_query("SELECT * FROM feedback.subject WHERE branch='cse'");
$row = mysql_fetch_assoc($sql) or die("error : $sql" .mysql_error());
$data =array();
$n=mysql_num_rows($sql);
while($row = mysql_fetch_array($sql))
{
$query_result_array[]=$row;
}
for($i=0;$i<$n;$i++)
{
$subid=$query_result_array[$i]['subid'];
$bt =$query_result_array[$i]['batch'];
$y =$query_result_array[$i]['year'];
$s = $query_result_array[$i]['semister'];
$subname=$query_result_array[$i]['subname'];
$tid = $query_result_array[$i]['tid'];
$sql2=mysql_query("SELECT * FROM teacher WHERE teacher.tid='$tid'");
$row2 =mysql_fetch_array($sql2);
$tname= $row2['tname'];
echo "<table id='table'>";
echo "<tr>";
echo "<td>".$bt."</td>";
echo "<td>CSE</td>";
echo "<td>".$y."</td>";
echo "<td>".$s."</td>";
echo "<td style='width:150px'>".$subname."</td>";
echo "<td style='width:150px'>".$row2['tname']."</td>";
echo '<form methode="get">
<input type="hidden" name="report">
<input type="submit" value="report">
</form>';
echo "</tr>";
echo "</table>";
}
function handler($x,$y){
session_regenerate_id();
$_SESSION['SUBID']=$x;
$_SESSION['TID']=$y;
echo 'report';
}
if(isset($_GET["report'$i'"]))
{
handler($query_result_array[$i]['subid'], $query_result_array[$i]['tid']);
unset ($_GET["report"]);
}
}
this results a table like
BATCH | BRANCH | YEAR | SEMISTER | SUBJECT NAME | TEACHER NAME | ACTION |
-------------------------------------------------------------------------------
9 CSE 4 1 DBMS ABC REPORT
9 CSE 4 1 WT XYZ REPORT
-------------------------------------------------------------------------------
when i click the report of a row suppose ('ABC' teacher) i want to carry the details ('ABC' and 'DBMS') to further process. but it always carrying the details of last person in the loop(here 'XYZ' and 'WT'). how to get that? is there any alternate process through i can call the handler function for a particular row which carries that particular row details.

just loop through query result array and inside of it place an if which detects when name is what you are looking for, at that moment, fetch current $query_result_array[$i] into a var that you want to carry the data further and break the loop.
If you are fetching by position in the table, you do not even need loop you just go $specific_person_data = $query_result_array[$i]...
So this now contains all of data about the person at position $i in your data table.
Update for links:
Each persons data can be passed to another page through link like this:
linkadress.php*?var1=X&var2=Y&var3=Z...*
and fetched on the other end with $_POST['var1'], $_POST['var2'] etc.
make sure not to echo or return data directly, but on every post var use strip_tags for security precaution.
Also here is article of mine on the subject of sensitive data handling and soem basic security:
http://metaphorical-lab.com/blog/?p=443

Related

Update MySQL-database with array values

How can I update a database with the values from an array? For example, let’s say we got a database with three tables:
Meals:
mealnr(PK), name, sort
Ingredients: ingredientnr(PK), name, stock
Structure: mealnr(FK), ingredientnr(FK), amount
I filled the database with some meals and ingredients. Every meal consists of multiple ingredients. The chef decides you only need 75g of ingredient x instead of 100g for meal y, so it needs to be changed in the database. Of course it can be done with SQL-commands, but I want to do it using a form in PHP.
First I made a page where all the meals are displayed. A meal can be edited using the edit-button next to it and based on the mealnr, you can change the amount of one or multiple ingredients for that particular meal. On the edit-page all the ingredient names and amounts are displayed in a table. The amount fields are textfields, those can be edited.
I made this script, but I don’t know exactly how I can update my database with the values of an array. I tried it with a foreach-loop, but it doesn't work.. yet. Can somebody help me?
<?php
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db("eatit", $conn);
$id = $_REQUEST['mealnr'];
$result = mysql_query("SELECT meals.name AS mealname, structure.amount, ingredients.name AS ingredientname
FROM Meals, Structure, Ingredients
WHERE meals.mealnr = structure.mealnr
AND structure.ingredientnr = ingredients.ingredientnr
AND meals.mealnr = '$id'");
if(isset($_POST['save']))
{
$new_amount = $_POST['amount[]'];
foreach ($new_amount as $value) {
mysql_query("UPDATE structure SET amount ='$value', WHERE mealnr = '$id'")
or die(mysql_error());
}
}
mysql_close($conn);
?>
<p><strong>Ingredients:</strong></p>
<?php
echo "<table>";
echo "<tr>";
echo "<th>Ingredient</th>";
echo "<th>Amount (gr)</th>";
echo "</tr>";
while($ingredient = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>";
echo $ingredient['ingredientname'];
echo "</td>";
echo "<td>";
echo '<input type="text" formmethod="post" name ="amount[]" value="' . $ingredient['amount'] . '" />';
echo "</td>";
echo "</tr>";
}
?>
<input type="submit" name="save" value="save" />
In your HTML markup you have declared the elements holding the name amount as an array by using amount[].
So, in your php code that receives the data it's enough to just refer to the amounts this way:
$new_amount = $_POST['amount'];
instead of:
$new_amount = $_POST['amount[]']; // in fact, this is wrong
Your foreach is fine, you should add some checks so that the $value actually contains a value that you expect, for example an int, float or not less than zero (or whatever checks you find necessary).
foreach($new_amount as $value){
if($value != '' && $value >= 1){
//sql statements goes here.
}
}
Receiving form data this way and then directly injecting the result to your SQL statement is always dangerous:
$id = $_REQUEST['mealnr'];
If you declare that you expect an integer (as the id's should be) before you directly inject the code to your SQL statement you have already written safer code.
$id = (int)$_REQUEST['mealnr'];
Also, just for the record - the mysql_* library is deprecated. As pointed out in the comments, try using PDO or mysqli instead - really!

Retrieving Mysql data and print in specific order

I got a problem that driving me crazy for last 4 or 5 days.I'm building a facebook style posting system,where users can post on their timeline and friends of that user can comment on every specific post.I'm actually having problem to print that correctly in php.Your help would be greatly appreciated.Thanks a lot in advance for your time.
The 'status' table that I created for all the post contain following values
id osid author type data postdate
1 1 helal a Hi... 2014-08-20
2 1 Abdul b Hey.. 2014-08-20
3 1 helal b Good.. "
4 4 helal a Hello.. "
5 4 Irin b Hi... "
so,basically,all new posts are having type 'a' and all replies are having type 'b'.And also,all separate conversation(post and replies) is having same 'osid',so that user can see separate conversation on separate div with a comment box attached to each post(followed by conversation)
I coded the following code,but it's not giving me expected result.
$sql="SELECT * FROM status WHERE type='a'";
$query=mysqli_query($connect_dude,$sql);
$numrow=mysqli_num_rows($query);
if($numrow>0){
while($row=mysqli_fetch_assoc($query)){
$id=$row["id"];
$osid=$row["osid"];
$name=$row["author"];
$data=$row["data"];
$date=$row["postdate"];
$query_replies = mysqli_query($connect_dude, "SELECT * FROM status WHERE type='b' AND osid='$id' ");
$replynumrows = mysqli_num_rows($query_replies);
if($replynumrows > 0){
while ($row2 = mysqli_fetch_assoc($query_replies) ) {
$statusreplyid = $row2["id"];
$statusreplyosid = $row2["osid"];
$replyauthor = $row2["author"];
$replydata = $row2["data"];
$replydata = nl2br($replydata);
$replypostdate = $row2["postdate"];
$replydata = str_replace("&","&",$replydata);
$replydata = stripslashes($replydata);
$status_replies .= '<div id="reply_'.$statusreplyid.'" class="reply_boxes"><div><b>Reply by '.$replyauthor.' '.$replypostdate.':</b><br />'.$replydata.'</div></div>';
}
}
$statuslist .= '<div id="status_'.$id.'" class="status_boxes"><div><b>Posted by '.$name.' '.$date.':</b> '.$statusDeleteButton.' <br />'.$data.'</div>'.$status_replies.'</div>';
if($logged == $username){
$statuslist .= '<form id="posting1" action="user.php?u='.$logged.'" method="post" enctype="multipart/form-data"><textarea id="replytext" name="replytext" class="replytext" placeholder="write a comment here '.$osid.'"></textarea><input id="hel1" name="hel1" type="hidden" value="'.$osid.'"><input type="submit" id="replyBtn" name="replyBtn" value="reply"></form>';
}
}
$postbox="<form id='posting' action='user.php?u=$logged' method='post' enctype='multipart/form-data'><input id='hid' name='hid' type='hidden' value='<?php echo $iid;?>' ><textarea id='taxi' name='taxi' rows='15' cols='40' placeholder='Say something to your Buddies'></textarea></br><input id='hel' name='hel' type='submit' value='post'></form>";
}
}
and I have used echoed '$statuslist' on html part.
It keeps compounding all replies within all the post.
Desired form of result,let say
For post no 1
helal:Hi...
Abdul:hello...
helal:Good....
"then the comment box(reply text area)"
For post no 2
helal:Hello...
Irin:Hi...
"then the comment box(reply text area)"
so on and so forth within separate divs for separate conversation
I'd say you need to reset $status_replies in the outer loop. Add:
$status_replies = '';
anywhere between the two while lines.

Same output in in MySQL update with foreach statement

I am trying to figure out how to update MySQL table with array.
The Tables has 4 fields. REGNO, BATCHNO, NAMES and ATTEN_SUM. The REGNO has the unique value.
$i = 0;
while($row_recordset = mysql_fetch_array($query_run)) {
echo "<tr>";
echo " <td>{$row_recordset['REGNO']}</td>
<td>{$row_recordset['NAME']}</td>
<td><input type='text' name='atten_ave".$i."'></td>
";
echo "</tr>";
$i++;
Here's my html code for the previous page after the update page.
foreach($_POST as $textbox => $values) {
$query_update = "UPDATE `grades` SET `ATTEN_SUM` = '$values' WHERE `BATCHNO` = '$sessionbatch'";
if(mysql_query($query_update)) {
echo 'SUCCESS';
} else{
die(mysql_error());
}
}
$_POST is a array from dynamic inputs from the previous page.
Here's the example of my output in the table.
REGNO | BATCHNO | NAME | ATTEN_SUM
====================================================
1 | ARPA 00-055 | Jason | 99
2 | ARPA 00-055 | Mark | 99
3 | ARPA 00-055 | Edgar | 99
It updates all the rows with the last value that I input.
html
//<input type='text' name='atten_ave".$i."'
<input type='text' name='atten_ave[]'...
php
//foreach($_POST as $textbox => $values) {
foreach($_POST['atten_ave'] as $textbox => $values) {
BUT this update is useless. it just update all record use last textbox.
i think you need to pass name or id to php,
then sql query add something like 'where id="$_POST['ID']"...
*CHECK mysql injections.
Well as you said, REGNO is the unique key, but you are updating on BATCHNO, which is not unique, according to your output.
If you look at the WHERE clause carefully, (WHERE BATCHNO = '$sessionbatch') you'll understand that it DOES update the SAME row each time and thus you see the last update.
Print the query statement, It'll be much clear to you.
if(mysql_query($query_update)) {
echo $query_update.'</br>';
1)
You should not use mysql_* functions anymore. They're deprecated and may potentially leave holes for mysql injections. You should learn to use either Mysqli or PDO.
2)
Your code is totally open to any possible mysql injection. You should use mysql_real_escape_string or see 1) above.
3)
With foreach($_POST) you're iterating through every $_POST item. I'm assuming (maybe I'm wrong) that you're submitting data from an HTML form. Try var_dump($_POST) and you'll see there are many values that are not related to what you want to do. For example:
<input type=”submit” value=”Some value” name="update">
will result in PHP
echo $_POST["update"];
// result: Some value
if you could post the output of var_dump($_POST) we could all see what you're passing inside of the foreach loop and perhaps give more detailed solution.

Text Injection In Display

Ok, so I'm given a list of parts like so:
PartID CatID PartName
0 1 Part 1
1 2 Part 2
2 1 Part 3
3 3 Part 4
4 2 Part 5
5 2 Part 6
I'm using PHP to pull. How can I inject a blurb of text at each change in CatID, without having to run multiple loops?
So on page, I can display it like:
"BLURB OF TEXT"
Part 1
Part 3
"BLURB OF TEXT"
Part 2
Part 5
Part 6
"BLURB OF TEXT"
Part 4
Here's the code so far. I thought about putting in an assignment to = $row["CatID"], and checking to see if the variable == CatID, but it was always ==...
while($row = sqlsrv_fetch_array($qry, SQLSRV_FETCH_ASSOC)) {
echo $row["PartName"]
}
Put the ID in a variable that is outside the loop. That way you can check the previous ID and the current one. If the current one is not the same as the last one, echo some text:
$LastID = 0;
while($row = sqlsrv_fetch_array($qry, SQLSRV_FETCH_ASSOC)) {
echo $row["PartName"];
if($row["CatID"] > $LastID)
{
// ID changed!
echo "Insert Text!";
}
$LastID = $row["CatID"];
}
This, ofcourse, is assuming that the data is sorted ascending on CatID as your result that you want is showing.
I had my logic backwards.... grr, figures I get it figured out right after I ask for help...
if($cCat == $row["catID"]){
//echo 'nothing here';
}else{
echo '<a name="' . $row["PartCategory"] . '"></a>';
echo $this->GetPartCategories();
$cCat = $row["catID"];
}
is what works, , and above the while statement is a $cCat = '';
I was trying
if(!$cCat == $row["catID"]){
echo '<a name="' . $row["PartCategory"] . '"></a>';
echo $this->GetPartCategories();
$cCat = $row["catID"];
}
which for some reason did not work.
p.s. Already have an order by in my query. It orders by the catID, partSortOrder, then partName

Divs according to mysql result in a loop

First off, sorry if the title is confusing! I'm working on a part of a blog that determines how lists of recent posts (sometimes determined by a date) in a category are to be displayed. In the database, each category has a "type" set that determines whether the div it goes in is small or large.
I can get the results to display but each link in the list has its own div, instead of being contained in one "main" category div.
Shorter explanation:
The database pulls results from the categories table and the posts table, as you can see in the query. The loop then runs so that the category boxes and the links in them can be created dynamically.
The problem is that the divs, which are supposed to house a list of links, are instead wrapping around each individual link and not the set that is desired.
While the code below shows only two "types", I had planned on adding more in the future.
Here is the code
<?
require("classes/Database.class.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$time = $_REQUEST['time'];
$db->connect();
$sql = "SELECT
cm.id,
cm.title AS cmtitle,
cm.sectionid,
cm.type AS cmtype,
cd.id,
cd.time,
cd.link,
cd.title,
cd.description,
cd.sectionid AS sectionid
FROM c_main AS cm
JOIN c_data AS cd ON cd.sectionid=cm.sectionid
WHERE cd.sectionid=cm.sectionid AND time = '".$time."' ORDER by id ASC";
$rows = $db->query($sql);
while($record = $db->fetch_array($rows)){
//determine what div to use by checking "type"
if ($record['cmtype'] == 'large') {
?>
<div class="large" >
<?
} elseif ($record['cmtype'] == 'small') {
?>
<div class="small">
<?
}
for($x =0; $x <= $db->affected_rows; ++$x)
{
if ($record['cmtype'] == 'small') {
echo $record['title'].'<br/>';
} else {
echo $record['title'].'<br/>'.$record['description'];
}
break;
}
echo '</div>';
}
$db->close();
?>
Basically I am trying to have it like this:
/-------------------\
| Category Title |
| -relevant link |
| -relevant link |
\____________________/
/-------------------\
| Category Title |
| -relevant link |
| -relevant link |
\____________________/
.... and so on for each subsequent category
And not this (which is how it's being outputted)
/-------------\
\relevant link/
-------------
/-------------\
\relevant link/
-------------
etc.
Here is the mysql wrapper I'm currently using, if that's of any significance http://ricocheting.com/scripts/php_mysql_wrapper.php
If you only want 2 divs, one large and one small, you should do ORDER BY cmtype, and then you will only need to create a div when the type changes or it is the first type.
your code will echo a div for every row, that is your problem/question.
my suggestion is to create two queries: one selecting all links of type A and the second query selecting all links of type B (WHERE type = '…')
then you'll have to print the starting tag of your first div:
echo '<div class="large">';
after that, loop your result and output your links:
while(($record = $db->fetch_assoc($rows)) !== FALSE){
echo htmlspecialchars($record['title']),'<br/>';
}
close your div:
echo '</div>';
now you can start your second category, same game, same rules:
open div
loop results
close div
~~~
another way like others said to order your result by type, then by id (ORDER BY type, id) and then check for a change in the row’s type:
$currenttype = '';
while(($record = $db->fetch_assoc($rows)) !== FALSE) {
$currenttype = $record['cmtype'];
echo '<div class="',htmlspecialchars($record['cmtype']),'">';
while($record['cmtype'] == $currenttype
&& ($record = $db->fetch_assoc($rows)) !== FALSE) {
// output link according to your type:
echo htmlspecialchars($record['title']);
}
echo '</div>';
}
i assume this is what you wanted to achieve in the first place
Maybe I get this completely wrong, but if you want to display the elements grouped by their type I think you should order them by type straight away, so that order of elements is correct when you start outputting HTML code?
If you are certain about your table contents you can use:
echo "<div class='" . $record['cmtype'] . "'>";
Maybe i am wrong in understanding your question, but you try to add all relevant link in a single DIV, then check your php result html (browser->view source)

Categories