I have a data base 'School'. It has only one table - 'Words'. There are word_id, word_name, word_description in it. I want to pull a random description and display it on a page. Then I want to input a word and see if the word has the same description as the random one that was pulled. What am I doing wrong? Here is the code -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Изпит</title>
</head>
<body>
<?php
$connection = mysqli_connect('localhost', 'root', '', 'school');
if(!$connection){
echo 'NOT OK';
exit;
}
if(isset($_POST['submit_description'])){
$q = mysqli_query($connection, ' SELECT word_description
FROM words ORDER BY rand() LIMIT 1
');
$row=mysqli_fetch_assoc($q);
if($row){
$_POST['word_description'] = $row['word_description'];
echo $_POST['word_description'];
}
}
if(isset($_POST['submit_word'])){
$word_name = $_POST['word_name'];
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
$result=mysqli_query($connection, $q2);
$count=mysqli_num_rows($result);
if($count==1){
echo 'Позна ве.';
}else{
echo 'Не позна ве.';
}
}
?>
<br><br><br>
<form method="POST">
<input type="submit" name="submit_description" value="Искай описание.">
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
</form>
<form method="POST">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
</body>
</html>
I think you have some typos.
This line of code here:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
Should be like this:
$q2="SELECT * FROM words WHERE word_name='".$word_name."' and word_description='".$_POST['word_description']."'";
1) There is a typo in $_POST['word_description'] in your query:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
2) Also, I would recommend using the word_id instead of the word description to make the verification... you would need to write it in a <input name="word_id" type="hidden" value="..." /> in your form to pass it along.
What would be even better, to prevent people from knowing the answer by looking at the code (in case they would know what word matches what id), you could encode the value in the hidden field to be md5($word_id.$word_name) and then in your query you check "WHERE MD5(CONCAT(word_id, word_name))='".$_POST['word_md5']."'" (assuming your hidden input is now called "word_md5).
EDIT:
After looking at the HTML I see what your problem is:
<form method="POST">
<input type="submit" name="submit_description" value="Искай описание.">
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
</form>
<form method="POST">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
This should all be in the same <form> element:
<form method="POST">
The word description is: <?php echo $_POST['word_description']; ?>
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
When the form is submitted, the $_POST array should contain the word_description AND the word_name submitted.
EDIT 2:
If you wish to use the id, you would have to first add it to your SELECT query:
$q = mysqli_query($connection, ' SELECT word_id, word_description
FROM words ORDER BY rand() LIMIT 1
');
Then you'd need to set it to some variable, and then later in your HTML:
<form method="POST">
The word description is: <?php echo $_POST['word_description']; ?>
<input type="hidden" name="word_id" value="<?php echo $word_id?>">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
Your second SQL query should then look like:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_id='".$_POST['word_id']."'";
Note: it is a bad practice to change the $_POST array in your code.
This array is populated by the request sent by the client and things can get confusing if you change the values there.
It is better to create another variable and set it to the value from the $_POST (example: $word_description = $_POST['word_description'];).
This way, you can still use array_key_exists('word_description', $_POST) to verify if the client actually sent something.
Related
I have a simple code (very simple one) that I was using to try something out for a work and I was trying a function to work with the variables of a form radio in post method, to update my SQL table with the output of the form. But when I'm going to try it, it doesn't update and gives me a notice.
It has something to do with the query (because the error says is in that line of the code) but I still don't know what it is.
I tried to change the syntax of the SQL sentence in different ways. I changed the user I was going to use to change the "image_value" column. I even checked the syntax of the query in phpmyadmin, and it worked.
Here is the php code:
<?php
mysql_connect("localhost","root","");
function user_image($value){
print_r($value);
//This is the problem
$query = "UPDATE users SET image_value = '$value' WHERE (ID) = '6'";
mysql_query($query);
}
?>
And here i have the code of the form and how I'm using the function (if there is any mistake that I haven't seen)
<form method="post" action="">
<input type="radio" name="1" value="1">imagen1
<br>
<input type="radio" name="2" value="2">imagen2
<br>
<input type="radio" name="3" value="3">imagen3
<br>
<input type="radio" name="4" value="4">imagen4
<br>
<button type="submit"><span>Submit</span></button>
</form>
<?php
user_image($_POST);
?>
Your problem is you are passing the complete object $_POST.
You don't specify if your radio name is correct (The name of your radio as a number from 1 to 4).
In the case, you are trying to set the value of image_value from a radio button should be.
<form method="post" action="">
<input type="radio" name="image_value" value="1">imagen1
<br>
<input type="radio" name="image_value" value="2">imagen2
<br>
<input type="radio" name="image_value" value="3">imagen3
<br>
<input type="radio" name="image_value" value="4">imagen4
<br>
<button type="submit"><span>Submit</span></button>
</form>
<?php
if (isset($_POST['image_value'])) {
user_image($_POST['image_value']);
}
?>
and your function
function user_image($value) {
mysql_connect("localhost","root","");
print_r($value);
//This is the problem
$query = "UPDATE users SET image_value = '$value' WHERE (ID) = '6'"; //ID should be dynamic base on the user I guess
mysql_query($query);
}
?>
$_POST pass an object value to the server, you need to specify the property you want to use, var_dump $value to understand all what it contains.
I want to pass two variable from POST, one is the text I write and the other one is the result of a query with I already have.But for some reason I am not getting the variable values. Can you help me?
This is my first page:
<form method="post" action="EliminarGrupos.php">
<label for="nomegrupo"><b>Editar nome do grupo 1 :</label</b><br>
<?php
while ($row = mysqli_fetch_array($result66)){
$result = $row['titulogrupo'];
$_POST['nomegrupo'] = $result; //saving first variable
?>
<input type="text" placeholder="<?php echo $result?>" name="grupo1" id="velhas"></td> //saving second variable
<?php } ?>
<input type="submit" name="submit_x" data-inline="true" value="Submeter">
</form>
This is my second page where I want the variables to appear
$variable = $_POST['nomegrupo'];
$variable2 = $_POST['grupo1'];
The placeholder attribute is for display purposes only. You need to set the value attribute to have it sent to the server.
To send a second value, just use a second <input> element. If you don't want it visible, set type attribute to hidden.
In addition, you are expecting an associative array from mysqli_fetch_array() which is not going to happen. Your HTML had a number of errors in it, which I think I've fixed below. You always need to escape output with htmlspecialchars(). You should separate your HTML and your PHP as much as possible.
<?php
$row = mysqli_fetch_assoc($result66);
$titulogrupo = htmlspecialchars($row["titulogrupo"]);
?>
<form method="post" action="EliminarGrupos.php">
<label for="velhas"><b>Editar nome do grupo 1 :</b></label><br/>
<input type="text" placeholder="" name="grupo1" id="velhas"/>
<input type="hidden" name="nomegrupo" value="<?=$titulogrupo?>"/>
<button type="submit" name="submit_x" data-inline="true">Submeter</button>
</form>
You get the $_POST data from the form submission, specfically from the name attributes. This is what gives the $_POST its information, which it retrieves from value, not placeholder, as you have it now.
<input name="grupo1" value="one"> will make $_POST['grupo1'] equal to one.
You also shouldn't set the $_POST variable on page 1 as you are currently doing, and should make the unchanged variable from the database call a hidden field:
Page 1:
<form method="post" action="EliminarGrupos.php">
<label for="nomegrupo"><b>Editar nome do grupo 1 :</label>
<?php
while ($row = mysqli_fetch_array($result66)){
$result = $row['titulogrupo'];
?>
<input type="text" value="<?php echo $result; ?>" name="grupo1" id="grupo1">
<input type="hidden" value="<?php echo $result; ?>" name="titlogrupo" id="titlogrupo">
<?php } ?>
<input type="submit" name="submit_x" data-inline="true" value="Submeter">
</form>
Page 2:
$variable1 = $_POST['titulogrupo']; // $row['titulogrupo']
$variable2 = $_POST['grupo1']; // Form input
Hope this helps! :)
I need to delete a record, in this case a categories from my forum, from the database based on its id.
<?php
if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
{
?>
<td>
<form method="post">
<input type="hidden" value="<?= ['cat_id']; ?>">
<input type="submit" name="submit" value="Remover" />
</form>
<?php
if(isset($_POST['submit']))
{
mysql_query("DELETE FROM categories where cat_id = 'cat_id'");
}
?>
</td>
<?php
}
?>
i cant get a "good" way to do it... :(
EDIT: This is for a programming lesson not a real forum!!
Your HTML Input Field needs a name so it can be identified by your PHP.
Then, in your Code Block where you attempt to delete the category, you need to acces the category id using the $_POST array.
Another thig you want to do is read up onj the dangers of SQL injections.
If you're just playing around with PHP and MySQL at the moment: Go Ahead. But if you actually want to develop, maybe you should read up on a few other things as well, even if it seems like overkill at first: PHP The Right Way.
Nontheless, try this:
<?php
if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
{
?>
<td>
<form method="post">
<input type="hidden" name="hid_catid" id="hid_catid" value="<?php echo $cat_id; ?>">
<input type="submit" name="submit" value="Remover" />
</form>
<?php
if(isset($_POST['submit']))
{
$query = "DELETE FROM categories where cat_id = '".(int)$_POST['hid_catid']."'";
mysql_query($query);
}
?>
</td>
<?php
}
?>
--> hidden field should have name and id to use
--
Thanks
Your hidden input field needs a name to be accessable after the post. Also I am not sure if ['cat_id'] is the correcty way to reference this variable. Where does it come from?
<form method="post">
<input type="hidden" name="cat_id" value="<?= $cat_id ?>">
<input type="submit" name="submit" value="Remover" />
</form>
Then your query has to look like this to correctly grab the id from the post.
mysql_query("DELETE FROM categories where cat_id = " . mysql_real_escape_string($_POST['cat_id']));
I'm working on a PHP dynamic form based on the tutorial found here:
http://blog.calendarscripts.info/dynamically-adding-input-form-fields-with-jquery/
Here is the table layout:
ID | depratecat | MinBalance | InterestRate | APY | suborder
inputted rows
ID is auto-increment.
The form fields for depratecat are visible in my code only for testing; normally the user would not be able to change this value. The value of depratecat would come from a POST value from a previous page and should be the same for all rows inputted or edited in this instance. For testing I'm declaring the value as 14.
My test page is here:
http://www.bentleg.com/fcsbadmin/dynamictest4.php
The problems:
The "Add row" script function does not work and the code won't insert new data thru form; nothing happens. No errors are shown in the Chrome console
Editing or deleting pre-existing rows seems to work.
Below is my complete test code minus the connection, Some print_r added to show the array.:
<?php
error_reporting(E_ALL);
// Connect to the DB
$link = myconnection stuff
$new_depratecat='14'; //for testing
// store in the DB
if(!empty($_POST['ok'])) {
//first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
// you can optimize below into a single query, but let's keep it simple and clear for now:
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM tblRates_balance WHERE id=$id";
$link->query($sql);
}
}
// now, to edit the existing data, we have to select all the records in a variable.
$sql="SELECT * FROM tblRates_balance WHERE depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
// now edit them
while($rates = mysqli_fetch_array($result)) {
// remember how we constructed the field names above? This was with the idea to access the values easy now
$sql = "UPDATE tblRates_balance SET
MinBalance='".$_POST['MinBalance'.$rates['id']]."',
InterestRate='".$_POST['InterestRate'.$rates['id']]."',
APY='".$_POST['APY'.$rates['id']]."',
suborder='".$_POST['suborder'.$rates['id']]."'
WHERE id='$rates[id]'";
$link->query($sql);
}
// (feel free to optimize this so query is executed only when a rate is actually changed)
// adding new
if($_POST['add_MinBalance']!= "") {
//echo ("OKAY");
$sql = "INSERT INTO tblRates_balance (depratecat, MinBalance, InterestRate, APY, suborder) VALUES ('$new_depratecat','".$_POST['add_MinBalance']."', '".$_POST['add_InterestRate']."', '".$_POST['add_APY']."','".$_POST['add_suborder']."' );";
$link->query($sql);
}
}
// select existing rates here
$sql="SELECT * FROM tblRates_balance where depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
?>
<html>
<head>
<title>Example of dynamically adding row and inserting into mySql with jQuery</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<h1>Example of dynamically adding row and inserting into mySql with jQuery </h1>
<form method="POST" id="newrate">
<div id="itemRows">
Minimum Balance: <input type="text" name="add_MinBalance" size="30" />
Interest Rate: <input type="text" name="add_InterestRate" />
APY: <input type="text" name="add_APY" />
Order: <input type="text" name="add_suborder" size="2"/>
<< Add data and click on "Save Changes" to insert into db. <br>
You can add a new row and make changes to existing rows all at one time and click on "Save Changes."
New entry row will appear above after saving.
<?php
// Next section does updating. let's assume you have the rate data from the DB in variable called $rates
while($rates = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$rates['id']?>">
<?php //echo $rates['id']; ?>
Minimum Balance: <input type="text" name="MinBalance<?=$rates['id']?>" value="<?=$rates['MinBalance']?>" />
Interest Rate: <input type="text" name="InterestRate<?=$rates['id']?>" value="<?=$rates['InterestRate']?>" />
APY: <input type="text" name="APY<?=$rates['id']?>" value="<?=$rates['APY']?>" />
Order: <input type="text" name="suborder<?=$rates['id']?>" value="<?=$rates['suborder']?>" />
<input type="checkbox" name="delete_ids[]" value="<?=$rates['id']?>"> Mark to delete</p>
<?php endwhile;?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script language="Javascript" type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Minimum Balance:<input type="text" name="add_MinBalance[]" value="'+frm['add_MinBalance[]'].value+'">Interest Rate:<input type="text" name="add_InterestRate[]" value="'+ frm['add_InterestRate[]'].value +'">APY:<input type="text" name="add_APY[]" value="'+frm['add_APY[]'].value+'">Order:<input type="text" name="add_suborder[]"value="'+ frm['add_suborder[]'].value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+')(this);"></p>';
jQuery('#itemRows').append(row);
frm['add_MinBalance[]'].value = '';
frm['add_InterestRate[]'].value = '';
frm['add_APY[]'].value = '';
frm['add_suborder[]'].value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
//}
</script>
</body>
</html>
The inputs in the initial form have names add_depratecat, add_MinBalance, add_InterestRate, add_APY, and add_suborder. When you add new rows, they have the same names, but with [] appended. So the original row creates single inputs, the added rows create array inputs, but they have the same names, and they conflict.
You should use the array form for the original inputs as well:
<form method="POST" id="newrate">
<div id="itemRows">
Dep_rate_cat:<input type="text" name="add_depratecat[]" size="30"/>
Minimum Balance: <input type="text" name="add_MinBalance[]" size="30" />
Interest Rate: <input type="text" name="add_InterestRate[]" />
APY: <input type="text" name="add_APY[]" />
Order: <input type="text" name="add_suborder[]" size="2"/>
so that they're consistent with the added rows.
Initially you are not adding [] in the form fields,
change <input type="text" name="add_depratecat" size="30"> to <input type="text" name="add_depratecat[]" size="30">, do the same for other fields as well.
And in foreach where you are inserting data to database use array $depratecat[] instead of string $depratecat
if(isset($_POST['add_depratecat'])) {
$depratecat = $_POST['add_depratecat']; ........
For debugging purpose write echo '<pre>'; print_r($_POST); OR var_dump($_POST); Instead of
echo '<pre>',print_r($_POST,true),'</pre>';.
Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.