How to set a maximum where value=$sum - php

I have an option for users to give away point to other users
I would like to make sure that the points they give away don't exceed the points they have.
How do I do this?
maxvalue doesn't work.
<?php
$user=$_SESSION['SESS_USERID'];
if(isset($_REQUEST['user'])){
$user = preg_replace('#[^a-z0-9]#i', '', $_GET['user']);
}
$sql=mysqli_query($conn,"SELECT SUM(sterren) AS total FROM sterren WHERE userid='$user'");
if ($row = mysqli_fetch_assoc ($sql)){
$sum = $row['total'];
if ($row["total"] >= '1') {
echo"
<table>
<some form action>
///Some more code to select the user to give the points to
<input type='text' name='sterren' id='sterren' size='3' maxlength='3' maxvalue=$sum ></td>
</form>
</table>";
}
}
<?

I think you should use the 'number' attribute instead of 'text'.
Your syntax should be something like this:
<input type='number' name='sterren' id='sterren' min='0' max='<?php echo $sum;?>'>

I think the synatx should be like the following
<input type='text' name='sterren' id='sterren' size='3' min="1" max="5">
Try max instead of maxvalue as the input attribute
References: http://www.w3schools.com/tags/att_input_max.asp
Demo: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_max_min

Related

Can't save table information to MySQL

I have been working with this code for a whole day but still can't understand where I made a mistake. So basically I want to edit whole mysql table.
I'm easily fetching it, and I need to change some of the data and save it again to the table. But everytime I'm trying to save it - everywhere getting "Array" and nothing more.
It's look like the code is not seeing that I'm making changes there.
Also sometimes when I'm changing bits, only last raw was saving and duplicating everywhere after.
<form method="POST" action="index.php">
<table><thead><tr><th>ID</th><th>Name</th><th>Live</th><th>AQ</th><th>Up</th><th>Down</th><th>Cptch</th><th>VID</th><th>UpOrDo</th><th>UTool</th><th>STool</th></tr><thead><tbody>
<?php
while ($row = $result->fetch_array()) {
echo "<tr><td><input size='1' name='id[]' value='".$row["ID"]."' readonly></td><td>".$row["Name"]."</td><td>".$row["Live"]."</td><td>".$row["AccQuantity"]."</td><td>".$row["Upvote"]."</td><td>".$row["Downvote"]."</td><td>".$row["Captcha"]."</td><td><input name='VoteID[]' type='text' size='5' value='".$row["VoteID"]."'></td><td><input name='UpOrDown[]' type='text' size='5' value='".$row["UpOrDown"]."'></td><td><input name='UpvoteTool[]' type='text' size='5' value='".$row["UpvoteTool"]."'></td><td><input name='SignupTool[]' type='text' size='5' value='".$row["SignupTool"]."'></td></tr>";
}
?>
</tbody>
</table>
<input type='submit' name='update' value='UPDATE' />
</form>
</body>
</html>
<?php
if(isset($_POST['update'])){
$ID = $_POST['id'];
$VoteID = $_POST['VoteID'];
$UpOrDown = $_POST['UpOrDown'];
$UpvoteTool = $_POST['UpvoteTool'];
$SignupTool = $_POST['SignupTool'];
for($i = 1; $i < 7; $i++) {
$user_id = $ID[$i];
$sql = "UPDATE Servers SET `VoteID`='".$VoteID."', `UpOrDown`='".$UpOrDown."', `UpvoteTool`='".$UpvoteTool."', `SignupTool`='".$SignupTool."' WHERE `ID`=".$user_id."";
echo $sql."<br>";
}
}
It seems you are not running the query. Also you are not picking out the data from the array. I would do this:
for($i = 1; $i < 7; $i++) {
$user_id = $ID[$i];
$_VoteID = $VoteID[$i];
$_UpOrDown= $UpOrDown[$i];
$_UpvoteTool= $UpvoteTool[$i];
$_SignupTool= $SignupTool[$i];
$sql = "UPDATE Servers SET `VoteID`='".$_VoteID."', `UpOrDown`='".$_UpOrDown."', `UpvoteTool`='".$_UpvoteTool."', `SignupTool`='".$_SignupTool."' WHERE `ID`=".$user_id."";
mysqli_query($sql);//or whatever way you are runing your query.
echo $sql."<br>";
}

php - insert multiple rows into mysql from form loop

So I am displaying multiple html forms on a page - works great because I am just using a simple loop to display it 80 times but the issue I am facing is I would like to take all 80 forms and submit them into multiple rows in my database. It's only submitting the last form (which is 80)
If anyone can help me find the issue... I would really appreciate it! I've done some searching before submitting this question but I can't seem to find a answer.
Here is what my table looks like:
Here is my form builder
<?php
// Counts the number of forms
$counter = 1;
echo '<form action="insert.php" method="post">';
// Loop through forms
for ($i = 1; $i < 81; $i++) {
$username = 'admin';
$title = 'test';
$name = 'a';
$image_src = '<img src="image/'.$i.'.jpg">';
$transition = 'fade';
$group_name = '0';
echo '<hr>' . '('. $counter .')'. '<br>';
echo "
<label>Username:</label>
<input type='text' name='username' id=' required='required' value='".$username."'/>
<br /><br />
<label>Title:</label>
<input type='text' name='title' id=' required='required' value='".$title."'/>
<br/><br />
<label>Name:</label>
<input type='text' name='name' id=' required='required' value='".$name."'/>
<br/><br />
<label>Content:</label>
<input type='text' name='content' id=' required='required' value='".$image_src."'/>
<br/><br />
<label>Image:</label>
<input type='text' name='image' id=' required='required' value='images/".$i.".jpg'/>
<br/><br />
<label>CSS Animate:</label>
<input type='text' name='cssanimate' id=' required='required' value='".$transition."'/>
<br/><br />
<label>Group Name:</label>
<input type='text' name='group_name' id=' value='0'/>
<br/><br />
";
$counter++;
}
echo '<input type="submit" value="Submit" name="submit"/>';
echo '</form>';
?>
Here is my php code: (insert.php)
<?php
$con=mysqli_connect("localhost","admin","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO table_name (username, title, name, content, image, cssanimate, group_name, group_sort) VALUES ('".$_POST["username"]."', '".$_POST["title"]."', '".$_POST["name"]."', '".$_POST["content"]."', '".$_POST["image"]."', '".$_POST["cssanimate"]."', '".$_POST["group_name"]."', '".$_POST["group_sort"]."') ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
} echo "Added!";
mysqli_close($con);
?>
If you have 80 elements with this name:
name='username'
Then how will this code know which one to use?:
$_POST['username']
Essentially, as your browser builds the form submission, each successive element of the same name over-writes the previous one. So you end up with only the last record.
Instead, give them an array-style name:
name='username[]'
(Repeat for all your duplicated form elements.)
Then in the PHP code, this would itself be an array:
$_POST['username']
You could loop over that array:
for ($i = 0; $i < count($_POST['username']); $i++) {
$username = $_POST['username'][$i];
$title = $_POST['title'][$i];
// etc.
}
This assumes that all of your arrays will be the same length. Which, given this HTML, I suppose they should be. But you can add error checking for that just in case. Either way, each iteration of the loop would build variables equating to that "record" which was submitted.
From there you should be able to build your SQL query with those variables. However, please note that your current way of doing that is extremely unsafe and wide open to SQL injection. To correct that, this is a good place to start.
Side note: Your HTML has invalid id attributes. Additionally, if you want to specify id attributes in that loop, you're going to need to ensure that they are somehow different. Duplicated ids in HTML is invalid.

Checked a checkbox on page refresh

I'm trying to keep a checkbox checked, but after I refresh the page, database is update with satus '1' but on front-end checkboxes is unchecked, hope somebody can help.
Here is my code
<td>
<span>
<input type='checkbox' name='Id' value='".$checkSubRow['Checklist_Id']."' class='check' id='Completed-".$checkSubRow['Checklist_Id']."' onClick='Completed(".$checkSubRow['Checklist_Id'].")'
/>
echo (isset($_POST['checkbox']))? "checked='checked'": "";
</span>
</td>
the name=Id is what you will need to check. So change the $_POST['checkbox'] to $_POST['Id']
I think there one issue that the echo (isset($_POST['checkbox']))? "checked='checked'": ""; is not inside the input tag. So, it wont apply to the tag. Also, the name should be used in the $_POST['checkbox'] like $_POST['Id']
e.g.
<td>
<span>
<input type='checkbox' name='Id' value='".$checkSubRow['Checklist_Id']."' class='check' id='Completed-".$checkSubRow['Checklist_Id']."' onClick='Completed(".$checkSubRow['Checklist_Id'].")' <php echo (isset($_POST['Id']))? "checked='checked'": ""; ?>/>
</span>
</td>
Try it out.
I didn't find solution for that so i changed it littile bit. here is revised code.
while ($checkSubRow = $checkSub->fetch(PDO::FETCH_ASSOC))
{
if($checkSubRow['Status'])
{
$checked = "checked";
}
else
{
$checked = "";
}
echo "<tr>
<td>
<span><input type='checkbox' name='Id' class='check' id='Completed-".$checkSubRow['Checklist_Id']."' $checked onClick='Completed(".$checkSubRow['Checklist_Id'].")' /></span>
</td>

php checkbox from mysql

I've managed to pull records from a mysql database using php with a checkbox to select. I'm struggling to make the selected records (with the checkboxes) appear on a new page. Here is my code so far:
<?php
include('connect.php');
$query = 'SELECT * FROM grades';
if ($r = mysql_query($query)) {
print "<form>
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['InstitutionName']}</td>
<td>{$row['InstitutionAddress']}</td>
<td>{$row['SubjectArea']}</td>
<td><input type='checkbox' name='check[$row{['GradeID']}] value='check' /></td>
</tr>";
}
print "</table>
</form>";
$checkbox[] = isset($_POST['checkbox']) ? true : false;
} else {
print '<p style="color: blue">Error!</p>';
}
?>
<html>
<form action="check2.php" method="POST">
<input type='submit' name='Submit' value='Submit'>
</html>
And on the page where I want the selected records to display, I have:
<?php
if(isset($checkbox))
{
foreach($checkbox as $value)
{
echo $value."<br>"; //it will print the value of your checkbox that you checked
}
}
?>
Any assistance would be appreciated!
Put checked="checked" just like you have put value="check":
<td><input type='checkbox' name='check[$row{['GradeID']}] value='check' checked="checked" /></td>
Edit:
Probably I misunderstood you. What do you expect to see?
First, you should make the form to perform POST request instead of GET (default):
print "<form method='POST' action='THE_FILE_YOU_PRINT_RESULTS.php'>"
Then in "THE_FILE_YOU_PRINT_RESULTS.php" do a print_r($_POST); to see what you get and how to display it.
A better way to do this would be to name your checkboxes check[]. Each checkbox value should then be the ID (rather than check).
Then on your results page, just loop through each instance of check[] and print the value out.
check[$row{['GradeID']}]
Seems incorrect to me, should it be:
check[{$row['GradeID']}]
Notice the moved opening curly bracket to before the $
Sorry if this is wrong haven't used PHP in long time but it stood out for me
The are a couple of error in the form print function.
You have to put the action on the first form, not on the second, you have to change the way how you print the checkbox as well.
Try to print the form in this way:
<?php
include('connect.php');
$query = 'SELECT * FROM grades';
if ($r = mysql_query($query)) {
print "
<form action=\"check2.php\" method=\"POST\">
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['InstitutionName']}</td>
<td>{$row['InstitutionAddress']}</td>
<td>{$row['SubjectArea']}</td>
<td><input type='checkbox' name='check[".$row['GradeID']."] value='".$row['GradeID']."' /></td>
</tr>";
}
print "</table>
<input type='submit' name='Submit' value='Submit'>
</form>";
$checkbox[] = isset($_POST['checkbox']) ? true : false;
} else {
print '<p style="color: blue">Error!</p>';
}
?>
And print the checked box reading the _REQUEST array:
<?php
if(isset($_REQUEST["check"]))
{
foreach($_REQUEST["check"] as $key=>$value)
{
echo $key."<br>"; //it will print the value of your checkbox that you checked
}
}
?>
This should work.

how to assign different name for each textbox in a loop in php

Can anyone let me know how to assign different names for each textbox in loop in php for the following code..
while($data=mysql_fetch_array( $sql )){
print "<tr><td>".$data['idno']." </td><td>".$data['name'] . " </td><td> <input type=text name=obtmarks</td></tr>";
}
You can use a counter nice and simple:
$i=0;
while($data=mysql_fetch_array( $sql ))
{
echo "<tr><td>".$data['idno']." </td>
<td>".$data['name'] . " </td>
<td> <input type='text' name='obtmarks_".$i."'></td></tr>";
$i++;
}
Note: I also corrected your open/close brackets and put quotes where they needed to go inside the elements.
$i = 0;
while($data=mysql_fetch_array( $sql ))
{
Print "<tr><td>{$data['idno']}</td><td>{$data['name']}</td><td> <input type=\"text\" name=\"obtmarks{$i++}\"/></td></tr>";
}
Keep your code clean and readable. Make proper use of "",{} and ''.
Edit:
while($data=mysql_fetch_array( $sql ))
{
Print "<tr><td>{$data['idno']}</td><td>{$data['name']}</td><td> <input type=\"text\" name=\"obtmarks[]\"/><input type=\"hidden\" name=\"obtmarks_id[]\" value=\"{$data['idno']}\"/></td></tr>";
}
And then on second page you will have 2 arrays waiting in $_POST, obtmarks[] containing user input and obtmarks_id[] containing corresponding ID's
$obtmarks = $_POST['obtmarks[]'];
$obtmarks_id = $_POST['obtmarks_id[]'];
foreach($obtmarks as $k => $v) {
// PSEUDO SQL: INSERT $v .... WHERE id=$obtmarks_id[$k]
}
The easiest way to do this is to create form elements that are in an array.
This is documented at php.net.
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
Thus, you could perhaps use:
$fmt = "<tr><td>%s</td><td>%s</td><td>input type='text' name='obtmarks[]'></td></tr>\n";
?><table><tr><th>ID</td><th>Name</th></tr><?php
while ( $data=mysql_fetch_array( $sql ) ) {
printf($fmt, $data['idno'], $data['name']);
}
?></table>
If it doesn't matter what the name is, you can do something as simple as this:
$counter = 0;
while($data=mysql_fetch_array( $sql ))
{
print "<tr><td>".$data['idno']." </td><td>".$data['name'] . " </td><td> <input type='text' name='obtmarks{$counter}' /></td></tr>";
$counter += 1;
}
<input type=text name=" .$variable." /></td></tr>" $variable could come from the mysql TABLE, field having different values or you may use a counter as the answers below.

Categories