I have two Mysql tables "addcoupons" with one column(couponvalue) and two rows with values 50 and 100. Another table "paytoget" with one column(usercouponinhand).
I been trying to get all the rows in table-1 to a html page and pass the particular id of the row when user click on its value to anther php page where it inserts it in table-2. But unfortunately i have missed something which causing it to print id of first row irrespective of which value user clicks.
My code goes as:
Page 1 (user interaction page)
<br>
<?php
$sql2 = "SELECT * FROM addcoupons WHERE customernumber = '$mobile' ";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
$index = 0;
while($row2 = $result2->fetch_assoc()) {
$index++;
?>
<form action='usercouponadd.php?id=<?php echo $row2['id'];?>' method="post" id="usercouponadd">
<div>
<h4 class="amount" form="usercouponadd"> <strong>Rs. <?php echo ($row2["couponvalue"]); ?></strong></h4>
<button class="addbutton" form="usercouponadd" type="submit"><span> <strong>Add</strong> </span></button>
</div>
<hr class="line" align="left">
<?php }
} else {
echo "None";
}
?>
</div>
The second php page (insert into table-2)
$mobile = $_SESSION['mobile'];
$date = date('M-d,Y H:i:s');
$date2 = date('M-d,Y');
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT * FROM addcoupons WHERE id = " .$_GET["id"];
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
$index = 0;
while($row2 = $result2->fetch_assoc()) {
$index++;
$usercouponinhand = $row2["couponvalue"];
$sql = "INSERT INTO userpaytoget (usercouponinhand, mobile, date, date2)
VALUES ('$usercouponinhand', '$mobile', '$date', '$date2')";
if ($conn->query($sql) === TRUE) {
echo '<script language="javascript">';
echo 'alert("coupon has been successfully added")';
echo '</script>';
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
}
} else {
echo " ";
}
$conn->close();
Table-1 "addcoupons"
couponvalue
50
100
Table-2 "paytoget"
usercouponinhand
xx
xx
Any Help is Appreciated....
I guess i figured out the answer for "my" problem.
I just removed the form tag since i m not submitting any data from user, and added that addcoupon.php link to anchor link. it worked talking the particular id which user clicks..
Code goes like this::
<div>
<h4 class="amount" form="usercouponadd"> <strong>Rs. <?php echo ($row2["couponvalue"]); ?></strong></h4>
<a href="usercouponadd.php?id=<?php echo $row2['id'];?>" class="addbutton" >Add</a>
</div>
Thanks to all who took their time to give this problem a glance...
Related
My dropdown menu is loading from the database, I can select multiple options from the list. When I click my 'Add' button everything appears to be behaving as expected, apart from the fact that nothing is saving back to the database. Unfortunately I've done so many tweaks now, having looked at stack overflow and others, I'm in the realm of confusion rather than progress.
I have set up a logger file to show when a page is reached. So I can confirm that I do get to the insert_rooms.inc.php page.
<?php
session_start(); // gets current session data for user // this function sends headers so it cannot be called after any output.
require_once '../dbconfig.php';
$date = new DateTime();
$date = $date->format("y:m:d h:i:s");
$id = $_SESSION['u_nickname'];
$u_id = $_SESSION['u_id'];
$file = "../ips.txt";
$text = file_get_contents($file);
$text .= $date ." " . $id . " visited insert_rooms.inc.php"."\n"; ///////// this text must be changed for each page
file_put_contents($file, $text);
$conn = OpenCon();
if ($conn)
{
if(isset($_POST['room[]']))
{
$room = mysqli_real_escape_string($conn, $_POST['room']);
if($room) // if a room exists insert into db with users id.
{
foreach($_POST['room'] as $r)
{
//here we need to take for example the word kitchen and find the id belonging to kitchen from the master_rooms table use it to find the master_room_id for kitchen and insert that into the table called user_room_list - along with the user id taken from the session u_id
$room_id = mysqli_query($conn, "SELECT master_room_id FROM master_rooms WHERE master_room_name = '$r'");
$sql = "INSERT INTO user_room_list(user_info_id, master_room_id)
VALUES(' ".$u_id." ', ' " .$room_id. " ') ";
mysqli_query($conn, $sql);
}
}
}
//session_unset();
//session_destroy();
header("Location: ../room_choice.php");
exit();
CloseCon($conn);
}
?>
extract from other file:
<div class="dropdown">
<form action="includes/insert_rooms.inc.php" method="POST">
"Hold down the Ctrl (windows) / Command (Mac) button to select multiple options."
<br/>
<br/>
<select name="room[]" multiple>
<?php
$conn = OpenCon();
if ($conn)
{
$query = "SELECT master_room_name FROM master_rooms";
mysqli_query($conn, $query) or die('Error querying database.');
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
for ($i = 0; $i < count($row); $i++)
{
echo "<option value=". $row[$i] . ">" . $row[$i] ."</option>";
}
}
CloseCon($conn);
echo "</select>";
echo " <input type="."submit"." value="." Add "." name="."send"."> ";
echo " </form> ";
}
?>
Below is the solution I found. Code is corrected accordingly.
foreach($room as $r) {
$result = mysqli_query($conn, "SELECT master_room_id FROM master_rooms WHERE master_room_name = '$r' ;");
$room_id_array = mysqli_fetch_array($result);
$room_id = $room_id_array[0]; // required as room_id goes into an array of length 1
$stmt = $conn->prepare("INSERT INTO user_room_list(user_info_id, master_room_id) VALUES (?, ?)");
$stmt->bind_param("si", $u_id, $room_id);
$stmt->execute();
Hi I am trying to do a Registration that the users will put their name password and their answers to some questions and then an admin will manually answer to it if it's accepted.I did the system that loads their name password and answers in the database,and I also ran the things that will show the answers to the admin,but I can't figure a way to change a value just for one user not for all of them,I will leave you my codes and everything over here.
Here is my admin.viewapplications.php code
(Here,it shows everything fine,but I can't figure a way that the button to act just for one id not for all)
<?php
//include(__DIR__ . "/signup.php");
include("../resources/config.php");
//$name = $_POST['Name'];
//$mg = $_POST['MG'];
//$pg = $_POST['PG'];
//$rk = $_POST['RK'];
$sql = "SELECT id, name, tutorial, MG, PG, RK FROM rp_users WHERE tutorial = 2";
//$tutorial = "SELECT tutorial FROM rp_users";
$result = mysql_query($sql);
//$result2 = mysql_query($tutorial);
//$value = mysql_fetch_object($result2)
/*if($result)
{
echo "Succes";
}
else
{
die(mysql_error());
}*/
//if($value > 1)
//
while($row = mysql_fetch_array($result))
{
//$tutorial = row["tutorial"];
//f($tutorial == 2)
//}
$id = $row["id"];
$name = $row["name"];
$mg = $row["MG"];
$pg = $row["PG"];
$rk = $row["RK"];
echo "ID: " . $id."<br> <br>";
echo "Nume: " . $name."<br> <br>";
echo "MG: " . $mg."<br> <br>";
echo "PG: " . $pg."<br> <br>";
echo "RK: " . $rk."<br> <br>";
echo '<form action="./?p=applicationaccept" method="POST">';
echo '<input type="submit" name="accept" value="Accepta">';
echo '</form><br>';
echo '<form action="./?p=applicationdeny" method="POST">';
echo '<input type="submit" name="deny" value="Respinge">';
echo '</form><br> <br> <br>';
}
//}
//
?>
And here is my applicationaccept.php
<?php
include("../admin/admin.viewapplications.php");
include("../resources/config.php");
$iduser = $id;
$sql = "UPDATE rp_users SET tutorial=0";
$result = mysql_query($sql);
if($result)
{
echo "Succes";
}
else
{
die(mysql_error());
}
/*while($row = mysql_fetch_array($result))
{
}*/
?>
I think what you want to do is a simple UPDATE to your MySQL database..
but make sure you format the PHP code you're using otherwise it'll give you an ERROR!
Also you have to use 'mysqli' now in PHP!
<?php
$someID = '1';
$sql = "UPDATE `rp_users` SET `tutorial`= '0' WHERE `id` = $someID";
$result = mysqli_query($link, $sql);
if($result)
{
echo "Success";
}
else
{
echo ("Error");
}
?>
BTW I forgot to mntion the '$link' is the connection to your database!
As of my understanding of your question if your form action is applicationaccept.php and you are trying to update for one user in applicationaccept.php file, try this:
<?php
include("../admin/admin.viewapplications.php");
include("../resources/config.php");
$iduser = $_POST["id"]; // pass id as parameter in form
$sql = "UPDATE rp_users SET tutorial=0";// change this line to following line
$sql = "UPDATE rp_users SET tutorial=0 where id=$iduser";
$result = mysql_query($sql);
if($result)
{
echo "Succes";
}
else
{
die(mysql_error());
}
?>
Be aware your code is vulnerable
I have the following code to load users in a table: register.php here I want to delete users from. Only the second script deleteUsers.php doesn't work.
Can any body help me out?
register.php`
<?php
$edit = 'edit:';
$account = 'Username:';
$account = '<font size="4">'.$account.'</font>';
$password1 = 'Password:';
$password1 = '<font size="4">'.$password1.'</font>';
$id = 'id:';
$id = '<font size="4">'.$id.'</font>';
//check db connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Take everything from table and fill in $result
$sql = "SELECT * FROM login";
$result = $conn->query($sql);
echo"<table border=4><tr><td>$account</td><td>$password1</td><td>$id</td><td>edit</td><td>delete</td></tr>";
if ($result->num_rows > 0) {
// Take all data
while($row = $result->fetch_assoc()) {
echo"<tr><td>".$row['username']."</td><td>".$row['password']."</td><td>".$row['id']."</td><td><a href='/editUser.php'> edit </a> </td><td> <a href='/deleteUser.php'> delete</a> </td></tr>";
}
} else {
// nothing in DB is 0 results
echo "0 results";
}
echo"</table>";
$conn->close();
?>
You see there is an delete button who redirect to deleteUser.php
This is the page you find here below, unfortunately the delete function doesn't work:
<?php
require_once("/db_conn.php");
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get id value
(isset($_GET['id'])
// delete the entry
$result = mysql_query("DELETE FROM login WHERE id =$id")
or die(mysql_error());
// redirect back to the view page
header("Location: register.php");
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
echo "doesn'twork";
}
?>
You need to pass the id variable :
while($row = $result->fetch_assoc())
{
echo"<tr><td>".$row['username']."</td><td>".$row['password']."</td><td>".$row['id']."</td><td><a href='/editUser.php'> edit </a> </td><td> <a href='/deleteUser.php?id=" . $row['id'] . "'> delete</a> </td></tr>";
}
you need to pass the id
while($row = $result->fetch_assoc()) {
echo"<tr><td>".$row['username']."</td><td>".$row['password']."</td><td>".$row['id']."</td><td><a href='/editUser.php'> edit </a> </td><td> <a href='/deleteUser.php?id=". $row['id']."'> delete</a> </td></tr>";
}
on deleteuser.php
$id=$_GET['id'];
$result = mysql_query("DELETE FROM login WHERE id =$id")
or die(mysql_error());
$id=$_GET['id']; must put after query
EDIT: I have successfully been able to calculate the value I was trying to get, but instead of calculating that value for each row, it is just calculating it once and posting that value everywhere. How do I make it recalculate for each row using the code I have?
Picture: http://img515.imageshack.us/img515/9064/example2w.png
New Code:
<html>
<head>
<title>PHP-MySQL Project 4</title>
<div align="center">
<p>
PHP-MySQL Project 4
<br/>
By: Ryan Strouse
</p>
</div>
</head>
<body bgcolor="#99FFFF">
<?php
$DBName = "surveys";
$DBConnect = #mysqli_connect("localhost", "students", "password")
Or die("<p>Unable to connect to the database server.</p>"
. "<p>Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error()) . "</p>";
if (!$DBConnect)
{
echo "<p> The database server is not available.</p>";
}
else
{
echo "<p> Successfully connected to the database $DBName</p>";
}
mysqli_select_db($DBConnect, $DBName);
echo "<p>Database -'$DBName'- found</p>";
$SQLstring = "SELECT * FROM surveys WHERE surveyCode = 'GEI001'";
$QueryResult = #mysqli_query($DBConnect, $SQLstring);
echo $SQLstring;
$row = mysqli_fetch_assoc($QueryResult);
$count_surveys = $row['surveyResponses'];
echo "<p>Total Responses: $count_surveys</p>";
$SQLstring2 = "SELECT * FROM results WHERE surveyCode = 'GEI001'";
$QueryResult2 = #mysqli_query($DBConnect, $SQLstring2);
echo $SQLstring2;
echo "<br/>";
$Row = mysqli_fetch_assoc($QueryResult2);
$SQLstring3 = "SELECT * FROM surveys, results";
$QueryResult3 = #mysqli_query($DBConnect, $SQLstring3);
$fetchrow = mysqli_fetch_assoc($QueryResult3);
$result_amount = (($fetchrow['resultResponses'] / $fetchrow['surveyResponses']) * 100);
echo "<table>";
echo "<tr><th>Commercial</th> <th>Views</th> <th>Percentage</th></tr>";
do {
echo "<tr><td>{$Row['resultDescription']}</td>";
echo "<td>{$Row['resultResponses']}</td>";
echo "<td>$result_amount</td></tr>";
$Row = mysqli_fetch_assoc($QueryResult3);
} while ($Row);
echo "</table>";
?>
<center>
<h3>Return To Main Page</h3>
<h3>Return to Menu</h3>
</center>
</body>
<footer>
<div align="center">
© Copyright Ryan Strouse ©
</div>
</footer>
</html>
I have two database tables and I am successfully pulling in column data into a table. The third cell of the table I would like to calculate a percentage out of some of the columns from the database. I'm not sure how to code this... I've tried to come up with something in the SELECT statement from another thread I found with no luck.
Here is a picture of the query I'm trying to get to work: http://img696.imageshack.us/img696/3862/examplegw.png
<html>
<head>
<title>PHP-MySQL Project 4</title>
</head>
<body bgcolor="#99FFFF">
<?php
$DBName = "surveys";
$DBConnect = #mysqli_connect("localhost", "students", "password")
Or die("<p>Unable to connect to the database server.</p>"
. "<p>Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error()) . "</p>";
if (!$DBConnect)
{
echo "<p> The database server is not available.</p>";
}
else
{
echo "<p> Successfully connected to the database $DBName</p>";
}
mysqli_select_db($DBConnect, $DBName);
echo "<p>Database -'$DBName'- found</p>";
$SQLstring = "SELECT * FROM surveys WHERE surveyCode = 'GEI001'";
$QueryResult = #mysqli_query($DBConnect, $SQLstring);
echo $SQLstring;
$row = mysqli_fetch_assoc($QueryResult);
$count_surveys = $row['surveyResponses'];
echo "<p>Total Responses: $count_surveys</p>";
$SQLstring2 = "SELECT * FROM results WHERE surveyCode = 'GEI001'";
$QueryResult2 = #mysqli_query($DBConnect, $SQLstring2);
echo $SQLstring2;
echo "<br/>";
$Row = mysqli_fetch_assoc($QueryResult2);
//this is where I am trying to calculate the value and then below it display in table
//cell # 3
$SQLstring3 = "SELECT *,((resultResponses/surveyResponses)*100) AS AMOUNT FROM surveys, results";
$QueryResult3 = #mysqli_query($DBConnect, $SQLstring3);
do {
echo "<table>";
echo "<tr><th>Commercial</th> <th>Views</th> <th>Percentage</th></tr>";
echo "<tr><td>{$Row['resultDescription']}</td>";
echo "<td>{$Row['resultResponses']}</td>";
echo "<td>$QueryResult3</td></tr>";
$Row = mysqli_fetch_assoc($QueryResult);
} while ($Row);
echo "</table>";
?>
<center>
<h3>Return To Main Page</h3>
<h3>Return to Menu</h3>
</center>
</body>
<footer>
</footer>
</html>
IF I understand what you are asking, you're trying probably to calculate the percentage of a value that you can find in a MySQL query's results. If that is so, then I'd use the function mysql_num_rows to get the total of the records and then in a while and if I'd have a counter of how many times I meet that value.
Then you just do simple math, for example:
result = (100 * counter) / mysql_num_rows
and have a percentage. Then you just echo the result wherever you want! :)
I hope I have understood your question correctly!
$result = mysql_query("SELECT yourRow FROM yourTable");
$aArray = array();
$cont=0;
while($col = mysql_fetch_assoc($result){
$aArray[$cont] = $col['yourRow'];
cont++;
}
That should give you a workable array for you to make your math with it and then echo it. Cheers
I am having a big issue.
This is the first time I sue a foreach and I do not even know if it's the right thing to use.
I have a textarea where my members can add some text.
They also have all the accounts where to send the posted text.
Accounts are of two types F and T.
They are shown as checkboxes.
So when a member types "submit" the text should be INSERTED in a specific table for EACH of the selected accounts. I thought php foreach was the right thing. But I am not sure anymore.
Please take in mind I do not know anything about foreach and arrays. So please when helping me, consider to provide the modded code =D . Thank you so much!
<?php
require_once('dbconnection.php');
$MembID = (int)$_COOKIE['Loggedin'];
?>
<form action="" method="post">
<p align="center"><textarea id="countable1" name="addit" cols="48" rows="10" style="border-color: #ccc; border-style: solid;"></textarea>
<br>
<?
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$on="on";
$queryF ="SELECT * FROM `TableF` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryF) or die("Errore select from TableF: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "F" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="f[<?php echo $rowid?>]" <?php echo $checkit;?>>
</div>
<?
}//END WHILE MYSQL
}else{
echo "you do not have any Active account";
}
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$queryTW ="SELECT * FROM `TableT` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryTW) or die("Errore select TableT: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "T" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="t[<?php echo $rowid?>]" <?php echo $checkit;?> >
</div>
<?
}//END 2° WHILE MYSQL
}else{
echo "you do not have any Active account";
}
?>
<input type="submit" value="submit">
</form>
<?
//WHEN CHECKBOXES "F" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "F" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['f'])){
$thispostF = $_POST['f'];
$f="F";
foreach ($thispostF as $valF)
//THE MOST IMPORTANT FIELD HERE IS "Type". THE ARRAY INSERT "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddF="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$f."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
//WHEN CHECKBOXES "T" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "T" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['t'])){
$thispostT = $_POST['t'];
$t="T";
foreach ($thispostT as $valF)
//THE MOST IMPORTANT VALUE HERE IS "Type". THE ARRAY GIVES "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
?>
foreach ($thispostT as $valF)
{
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
please put start and ending bracket to your foreach loop and try i have not read the whole code but just found you missing the brackets. hope that helps you.
I think I know what you're doing...
You're going to need to do:
foreach($_POST as $key => $value) {
$type = substr($key,0,1);
$id = substr($key,1);
if($type == 't') {
// do insert for t table here
} else if($type == 'f') {
// do insert for f table here
}
}
I didn't test it but it should be something like this.
My suggestion is
create field name as t[] (array)
onchecked value will be passed on the next page
the form checkbox field should be like that
<input type="checkbox" name="t[]" value="< ?php echo $rowid?>" <?php echo $checkit;? > >
and when you Submit the form
GET THE VALUE and insert in to database;
< ?
if($_POST['t'])
{
foreach($_POST['t'] as $v)
{
queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
}
? >