PHP table creation with name and score [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am having some serious trouble for some reason with creating a basic PhpMyAdmin database and making a page with a scoreboard. There will be a game that you play, and when you're done you can input a score and your name using basic form elements. When you press submit the page will reload and you will be able to see the top ten scores, ranked by highest first.
My issue is that I have no idea where to start with this. I have just started Php and don't wish for anything crazy. I have the ~/php/db_connect.php set up correctly already; I just need to make the function work.
How do you recommend I go through with this? Example code is extremely helpful.
I know the first response is "what have you tried?" and I haven't tried much.
This is what I have right now:
// define variables and set to $name = $myArray[0];
$babyinfo = fgets($myfile);
$myfile = scoreboard-dk;
$myArray = explode(',', );
$score = $myArray[1];
$name = $myArray[2];
$insertStmt = "INSERT INTO scoreboard-dk ('score','name') VALUES ('$score','$name')";
// Inserting Babynames into database
$db->query($insertStmt);
?>
<form action=" $db;?>" method="post">
Name: <input type="text" name="name" value=" echo $name;?>" required><br>
Score: <input type="text" name="score-dk" value=" echo $score;?>" required><br>
<input class="btn btn-primary" type="submit">
</form>
<tr> <th scope=row> echo $i;?></th> <td> echo $score;?></td> <td> echo $name;?></td> <td> echo $votes;?></td> </tr>
Thanks in advance.

Ok. First some mistakes you made:
$myfile = scoreboard-dk; isn't working. This way it would be a constant. You need the "$" or quotation marks if it should be a string.
$myArray = explode(',', ); I don't know what you want to do? The second argument is missing. This statement won't work. Second argument has to be a string.
You have to properly escape the query before executing the statement.
You can do this by replacing the following line before building the string:
$score = $db->real_escape_string($myArray[1]);
$name = $db->real_escape_string($myArray[2]);
Furthermore are you sure you use the correct indices for the array access? Counting starts with 0, not with 1.
You can't use PHP code without the opening tags. I thought that you cut that away at the start of the file. You always have to open PHP code blocks with
Perhaps you should search for example code elsewhere. I think stack is more for specific questions. But the code actually shows that you lack of some basic knowledge ... no offense.

The reason people can't help you is that your question is way too broad and everyone will have a different approach about how to implement it.
That being said, here is the pseudo code I would use to implement this. It can be done in a single file. Good luck!
File: score_keeper.php
<?php
error_msg = array
if (form submitted)
$name = name from form
$score = score from form
// Do validation to ensure name and score is as expected.
if name is empty
error_msg[] = 'Name cannot be empty'
if score is not numeric
error_msg[] = 'Score must be numeric'
if empty(error_msg)
// INSERT
// Make sure you use parameterized queries
SQL = INSERT into table (name, score) VALUE (?, ?)
end-if
end-if
// READ top 10
SQL = SELECT name, score FROM table WHERE ...
if !empty(error_msg)
show error_msg
?>
<form method="post">
<input name="name">
<input name="score">
</form>
HTML table
<?php
// output top 10 results

Related

Deleting mysql json data in PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I am sharing my codes below with you. I can save new data as json in my database, but I couldn't figure out how to delete what I want from this data. How should I do?
<?php
include("matta/database.php");
?>
<html>
<meta charset="UTF-8">
<?php
$sorgum = mysql_query("SELECT * FROM birlikler WHERE id = 1", $vtbaglan);
$sorgu = mysql_fetch_array($sorgum);
$uyelerim = $sorgu['uyeler'];
$uyesim = json_decode($uyelerim, true);
foreach($uyesim as $bubirtest){
echo ''.$bubirtest['kullanici'].'<br>';
}
echo ''.$uyebilgileri.'
<form method="post">
<input type="text" name="kullaniciadi" placeholder="kullaniciadi"s>
<input type="text" name="rutbe" placeholder="rutbe">
<input type="text" name="kadi" placeholder="karakteradi">
<button type="submit" name="verigir">verigir</button>
</form>';
if(isset($_POST["verigir"])){
$kullaniciadi = $_POST["kullaniciadi"];
$rutbe = $_POST["rutbe"];
$karakteradi = $_POST["kadi"];
$arr = [
'kullanici' => ''.$kullaniciadi.'',
'rutbe' => ''.$rutbe.'',
'karakteradi' => ''.$karakteradi.''
];
$uyesim[] = $arr;
$arrim = json_encode($uyesim);
//echo '<br>'.$uyeler.','.$arrim.'';
$veriekle = mysql_query("UPDATE birlikler SET uyeler = '$arrim' WHERE id = 1", $vtbaglan);
}
?>
my previous question: PHP MySQL Json data saving
Edit:
I tried the code stated by #gguney but could not reach the result. I leave the "uyeler" column in my database below so that I can clearly explain the way I want.
[{"kullanici":"matta","rutbe":"20","karakteradi":"Vitality_Test"},{"kullanici":"Linuxy","rutbe":"19","karakteradi":"Linuxy_Test"}]
To give an example of the operation I want to do; I want to delete the user whose "kullanici" value is "matta" from this line. In other words, I want the new data that I want to reach as a result of my operation to be as follows;
[{"kullanici":"Linuxy","rutbe":"19","karakteradi":"Linuxy_Test"}]
The PHP version I'm using is a bit old. I'm aware of this, but I have to use this version for my current job. I would be very grateful if you could help.
You can update that json field. Or like any other array field. Just use unset.
For example:
unset($arr['rutbe']);
and use again your update mysql query to delete that field.
Or you can use MySQL JSON_REMOVE function
UPDATE birlikler
SET birlikler.uyeler = JSON_REMOVE(birlikler.uyeler, 'rutbe');

How can we process a dynamic form in php

The newbie is back with another question. Any help would be much appreciated. Suppose we have got a form in which we have written down the name of a user and in front of which there is an input box in which we can allocate a grade to the mentioned user. Within this scenario, everything is clear. We have a form with the name of user (it's 'id' as the value) and another variable, that is the grade' which are posted to the php-action-page. Hence, in the php-action-page, I get two variables, one is the id of the user and the other allocated grade, through POST. Here, everything is clear and the process easy, since I have got just two defined variables. Now, suppose that we are inserting a list of users from our 'Users' table into the form dynamically. We fill our form with for example 10 users grabbed from the database. In front of them there are input boxes for the 'grade' to be inserted into. So far, everything is fine. The problem, though, lies in the next stage. The problem is I don't know how to ask php-action-page to do the insert, that is insert the grade in the database for specific users as long as there are posted variables of users. Here I have tens of users and tens of dynamic variables. And if the question is a little bit vague, please do excuse me; yet, do your best to get me free from this condition of bafflement. Many thanks.
Here comes some bits of the code to make the problem a little more clear.
I start with the following code:
<?php
require_once ('../inc/takein.php');
$pd = new dbase();
$students = $pd->run_a_query('SELECT * from `checking`');
Here I am including the database and other necessary files. Then I run a query to fetch a list of my students from the table. So far, everything is fine. The next line of action which makes me perplexed is the following code.
Before having a look at the code may you please look at the html design in the following picture:
Final Design
I totally have no idea about it being wrong or correct. You might help with this bit as well.
<form action="grades.php" method="post">
<table class="table table-bordered font-label" id="item_table">
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade[]" class="form-control omit-radius-input"></td>';
echo '<input type="hidden" name="id[]" value="'.$student['id'].'">';
echo '<tr>';
}
?>
</table>
<input type="submit" name="dispatched" class="btn btn-green">
</form>
Here, I am putting the information in a table within the form element. As you can see in the above picture, I am getting four students from the database. Now I want to send these students back to the database along with their newly set grades. What I want to be posted here is the student id and their grades.
Then, the following is the last part of the code which is left incomplete because I couldn't make any senses how to do it.
if (isset($_POST['dispatched'])) {
$id[] = $_POST['id'];
$grade[] = $_POST['grade'];
// what to do now???!!!
foreach(...HOW TO DO THE 'FOREACH') {
...
}
}
May you please help me insert my student grades. Many thanks in advance.
Simply name your variables as arrays - if your form looks like this
<form method="POST">
<input type="text" name="grade[12]">
<br>
<input type="text" name="grade[15]">
<br>
<input type="text" name="grade[7]">
<br>
<input type="text" name="grade[21]">
<!-- continue here -->
</form>
then in your PHP code you will access the grades like this
if(is_array($_POST['grade'])) foreach($_POST['grade'] as $id => $value)
{
// REPLACE INTO user_grades(user_id, grade) VALUES($id, $value)
}
UPDATE
You should also put the ID of your students in the name of the INPUT field - otherwise you won't know for which student is the given grade.
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade['.$student['id'].']" class="form-control omit-radius-input" value="'.$student['current_grade'].'"></td>';
echo '<tr>';
}
?>
The foreach is shown above in my original answer.

How to name an array after content from a string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I've a form tag which sends the name for an array to a function but how can I name my array after this? Ok, code says more than thousand words:
<?php
function dynamic($id, $name, ... ){
...
echo "<select id='$id' name='$name' size='...' multiple>";
...
echo "<select id='$id' name='$name'>";
...
}
?>
<form ... method="post">
<p>
<?php
echo dynamic("dynamic1", "choice1", ...);
?>
</p>
<p>
<?php
echo dynamic("dynamic2", "choice2", ...);
?>
</p>
<p>
<?php
echo dynamic("dynamic3", "choice3", ...);
?>
</p>
<input type="submit" value="send"/>
</form>
I want to create a list where you can select multiple items but for this $name needs ot be an array. The array should named like the second variable. In one case it should be named choice1 in another choice2
Like how do I get from $name = "choice1"; to choice1[]
#edit Added a new line in function to show my problem. somtimes $name needs to be and array and sometimes not
Any ideas?
You are looking to use dynamic variable names, which is possible in PHP, but you need to be careful with this. Production code using this can be difficult to maintain and throw errors quite easily.
Anyway, lets say you have a value in the form $_POST that you want to use as a variable name. You would do so like this.
$id = "gettheidsomewhere";
${$id}[] = "whatever";
Like i said, use this carefully. Dynamic variable names are dangerous and very hard to debug when things break.
If you do not know the value used for $id, then you will need to loop through your post variables and assign them accordingly. I would assume you want to add some extra logic, but here is a basic example.
Using a key value loop you can obtain the name of the post variable, stored as $key and the value. So for $_POST["something"] = "test", when this line is looped over, $key will be "something" and $value will be "test".
foreach ($_POST as $key => $value)
{
${$key}[] = $value;
}

Update a row that was selected randomly

I am building a code that shows up a random question everytime you refresh the page or answer the question on screen. This is the code I have on my conexao.php file to select a random question:
$research = mysqli_query ($connection, "SELECT * FROM enquete ORDER BY RAND() LIMIT 1");
$result = mysqli_fetch_array($research);
$info = $result;
The code above is working fine to select a random question from my "enquete" table.
The problem I have is when the question is answered. This is the code I have that displays the question and presents 2 submit buttons (YES/NO):
<?php
include 'conexao.php';
$contador = 0;
do{
echo $info['pergunta'];
if(isset($_POST['sim'])){
mysqli_query($connection,"UPDATE enquete SET sim = sim + 1 WHERE pergunta = '".$info['pergunta']."'") ;
echo "<br/>".$info['sim']."people who answered YES <br/>";
echo $info['nao']." people who answered NO <br/>";
}
$contador++;
} while ($contador < 1);
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="estilo.css">
<link async href="http://fonts.googleapis.com/css?family=Aclonica"
rel="stylesheet" type="text/css"/>
</head>
<div class="wrapper">
<form action="" method="post">
<input type="submit" class="botao-css" value="Sim" name="sim"/><br/>
<input type="submit" class="botao-css" value="Não" name="votarnao"/><br/>
</form>
</div>
</html>
The problem I have is the following: The code above seems to be ok to add 1 to an answered question (YES in the example above), however instead of adding 1 to the current random question shown on screen it adds 1 to the next question which will be shown.
For example:
Question 1: The sky is blue? (if YES is hit then it adds 1 to the next question "sim" row instead of adding to this one. )
Question 2: Do you drink water? (it has already gotten 1 because of the previous question and if I think yes to this one the it adds 1 to the next question "yes" row)
Of course what I intend to do is to have the system to add 1 to "yes" row of the current question and not to the one that is next.
If someone could help me giving tips on this I would be really glad.
First I think you need to add a field in your form to identify which question is relevant for the submission:
<form action="" method="post">
<input type="hidden" name="pergunta" value="<?= $info['pergunta'] ?>" />
<input type="submit" class="botao-css" value="Sim" name="sim"/><br/>
<input type="submit" class="botao-css" value="Não" name="votarnao"/><br/>
</form>
Then you need to use this instead, but to prevent SQL injections, you should make sure it can only be an integer:
mysqli_query($connection,"UPDATE enquete SET sim = sim + 1 WHERE pergunta = ".(int) $_POST['pergunta']) ;
$info will be the information about the next question obtained from conexao.php. $_POST will be the data from the last submission. So it makes sense to not use $info at all if you're referring to the last question.
Note: if pergunta isn't an integer, you should use a prepared statement to protect against SQL injections. (maybe replace pergunta with id in this case)
Thank you it worked. I used post and an int value (the ID of the rows as suggested). Here is how I put the code to work.
Updated form adding this line as suggested:
`<input type="hidden" name="pergunta" value="<?= $info['id'] ?>" />`
And updated the query to this:
`mysqli_query($connection,"UPDATE enquete SET sim = sim + 1 WHERE id = ".(int) $_POST['pergunta']) ;`
Now it updates the question on screen. Thank you.

How to make a volunteering calculator in my html [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm currently coding a website in html and CSS. I have learned, php well at least enough for the thing i'm currenly trying to make. So I basically have the following,
How do you accomplish getting a number/constant 40 and subtracting that from a user inputted number. In a html document
<form action="welcome.php" method="post">
$string = "cool";
Hours:<input type ="text" name ="name"<br>
$string = "cool"
Hours: <input type="text" name="name"><br>
<input type="submit">
echo 40-"$cool";
</form>
this is wrong and will return the echo and original php code. If i wrap it in php it will display an error
The $cool should not be quoted. Also, why are you setting the $string two times with same value?
<form action="welcome.php" method="post">
<?php $string = "cool"; ?>
Hours:<input type ="text" name ="name"><br>
Hours: <input type="text" name="name"><br>
<input type="submit">
<?php echo 40-$cool; ?>
</form>
Also, the file itself has to be php, not html.
Firstly, you're injecting PHP inside HTML, you can't do that. It will produce a parse error, if your file is indeed a .php extension.
Edit: As noted in comments, you can inject PHP inside HTML, just as long as you include PHP tags and enclosed using <?php ?> or <?= ?>; the latter being short open tag syntax.
Now, as I understand it, you want another field where a user will enter a number, then substract (from user input) your number 40 being a constant, and add on the word "cool" after the result.
Here's how and with the user's name echo'd also if filled and checking if it's a number using is_numeric().
Sidenote: Using the number 2 in the input and with the name John, will output "38 cool John".
<?php
if(isset($_POST['submit'])){
if(isset($_POST['number']) && is_numeric($_POST['number'])){
$string = "cool";
$name = $_POST['name'];
$number = $_POST['number'];
$constant = 40;
$total = $constant - $number;
echo "$total $string $name";
} // brace for if(isset($_POST['number'])...
else{
echo "It's not a number";
}
} // brace for if(isset($_POST['submit']))
?>
<form action="" method="post">
Name:<input type ="text" name ="name"<br>
Number: <input type="text" name="number"><br>
<input type="submit" name="submit" value="Submit">
</form>
Footnotes:
You can also use an alternate method to echo the variables, such as:
echo "$total $string $name"; with a space between
echo "$total-$string-$name"; with a hyphen seperator
as noted in comments
The dot concatenation is just force of habit on my part.
Sidenote: You must use double quotes for this, since variables only get parsed inside double quotes.
Otherwise, you would get the following parse error using echo $total $string $name;:
Parse error: syntax error, unexpected '$string' (T_VARIABLE), expecting ',' or ';'...
Using echo $total-$string-$name; would work, but it will only echo the value from the substraction, instead of the intended echo'd string(s).
You don't need PHP for this at all. You can just use some basic java script. To use php, you need to set this whole page up differently.

Categories