Checkboxes and text doesn't want to show the value - php

<!DOCTYPE html>
<html>
<head>
<title>Talenquiz2</title>
</head>
<body>
<?php
if (isset($_GET["controleer"]))
{
$vraag = $_GET["vraag"];
$juistantwoord = $_GET["juistantwoord"];
$foutantwoord1 = $_GET["foutantwoord1"];
$foutantwoord2 = $_GET["foutantwoord2"];
$con = mysql_connect("localhost","root","");
mysql_select_db("dbproject", $con);
$result = mysql_query("SELECT * FROM tblquizvragen");
while($row = mysql_fetch_array($result))
{
if ($row['vraag'] == $vraag)
{
if ($row['juistantwoord'] == $juistantwoord)
{
echo "Juist!<br />";
}
else
{
echo "Fout!<br />";
}
}
}
mysql_close($con);
echo "\n<hr />\n";
}
$aantalvragen=1;
$con = mysql_connect("localhost","root","");
mysql_select_db("dbproject", $con);
$result = mysql_query("SELECT * FROM tblquizvragen WHERE id='". $aantalvragen . "';");
$row = mysql_fetch_array($result);
The program is a quiz, it asks 5 questions with 3 chckbox 1 is corect and 2 are incorrect.
for ($aantalvragen=1; $aantalvragen<=5; $aantalvragen++)
{
$row = mysql_fetch_array($result);
}
her i lin
$vraag = $row['vraag'];
$juistantwoord = $row['juistantwoord'];
$foutantwoord1 = $row['foutantwoord1'];
$foutantwoord2 = $row['foutantwoord2'];
mysql_close($con);
?>
<form>
It doensn't show the values of the rows in my browser it shows only an open text and an open checkbox.
<input type="text" name="vraag" value="<?php echo $vraag; ?>" /><br />
<input type="checkbox" name="juistantwoord" value="<?php echo $juistantwoord; ?>" /><br />
<input type="checkbox" name="foutantwoord1" value="<?php echo $foutantwoord1; ?>" /><br />
<input type="checkbox" name="foutantwoord2" value="<?php echo $foutantwoord2; ?>" /><br />
<input type="submit" value="Controleer je antwoord" name="controleer" />
</form>
</body>
</html>

Your code is incorrect for fetching from the db
for(...) {
$row = mysql_fetch_array(...);
}
You simply loop over 5 lines of results, regardless of how many there may be, and assign the row array to $row... but do so for EVERY row without ever using them. So you end up trashing the first n-1 rows and come out of the loop with only row n saved.
If you're wrong with how many rows of data you're expecting, your 5-item loop may have only a 4-item result set to deal with, and the final row $row1 value will be the boolean FALSE that msyql_fetch returns when there's no more data.
Try something like this instead:
while($row = mysql_fetch_assoc($result)) {
echo ..... your stuff here ...
}
Far more reliable, doesn't depend on there being a known number of rows available, and will not output anything if there's no data at all.

Related

PHP if/else statement acting weird

I'm relativity new to php and just testing out some code. The odd thing is that the code both does/doesn't work. The code should check a MySQLi database to determine the state of the check box and then apply that state to the checkbox. What the code currently does is designate the checkbox state based solely off the value of the if condition, regardless of the MySQLi database values.
Here is the code for the html page, it's the if statement near the bottom that's causing issues;
<?php
include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$sql_1 = "SELECT * FROM test2;";
$results = mysqli_query($conn, $sql_1) or die('Error getting data.');
echo(string) "<table>";
echo "<tr><th>state</th><th>id</th></tr>";
while($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['state'];
echo "</td><td>";
echo $row['id'];
echo "</td></tr>";
}
echo "</table>";
?>
<form action="includes/checkbox.inc.php" method="post">
<input type="hidden" name="checkbox1" value="0">
<input type="checkbox" name="checkbox1" value="1"
<?php
$sql_2 = mysqli_query($conn, "SELECT state FROM test2 WHERE id = '0'") or die('Error getting data.');
if ($sql_2 == "0") {
echo "checked";
} else {
echo " ";
}
mysqli_close($conn);
?>
> Item 1<br>
<input type="hidden" name="checkbox2" value="0">
<input type="checkbox" name="checkbox2" value="1" checked> Item 2<br>
<input type="submit" name="Submit" value="Submit">
</form>
<br>
Reset<br>
</body>
</html>
The odd thing about this code is that the if ($sql_2 == "0") results in the checkbox remaining unchecked, but changing the 0 to a 1, if ($sql_2 == "1") results in the checkbox remaining checked. Both results are regardless of what the database shows.
I know all the other bits of code work, because when I check the checkbox and submit, it updates the database and displays it correctly (the reverse is also true).
If anyone knows why if ($sql_2 == "0") is not working, please let me know. I've even checked other stack overflow postings, and as far as I can tell, everything should be coded properly.
Edit:
I should have stated that in the above question, changing the = to == or reversing the order doesn't fix the problem. The if statement still only returns the else statement.
I've done additional research and think that the issue is related to the use of mysqli_query to retrieve the data, as it should likely be mysqli_fetch_row.
if ($sql_2 = "0") will make the value of $sql2 to '0' and this condition will be always true
change it to
if ($sql_2 == "0")
to prevent the accidental assignment you can do like below
if ("0"==$sql_2)
ISSUE FIXED
The solution was to add a mysqli_data_seek() to the php, below is the working code.
<?php
include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$sql_1 = "SELECT * FROM test2;";
$result_1 = mysqli_query($conn, $sql_1) or die('Error getting data.');
echo(string) "<table>";
echo "<tr><th>state</th><th>id</th></tr>";
while($row = mysqli_fetch_array($result_1, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['state'];
echo "</td><td>";
echo $row['id'];
echo "</td></tr>";
}
echo "</table>";
$query_1 = "SELECT state, id FROM test2 ORDER BY id";
$sql_3 = mysqli_query($conn, $query_1) or die('Error getting data.');
if ($result_2 = $sql_3) {
mysqli_data_seek($result_2, 0);
$row_1 = mysqli_fetch_row($result_2);
}
if ($result_3 = $sql_3) {
mysqli_data_seek($result_3, 1);
$row_2 = mysqli_fetch_row($result_3);
}
?>
<form action="includes/checkbox.inc.php" method="post">
<input type="hidden" name="checkbox1" value="0">
<input type="checkbox" name="checkbox1" value="1"
<?php
if ($row_1[0]=="1") {
echo "checked";
} else {
echo " ";
}
?>
> Item 1<br>
<input type="hidden" name="checkbox2" value="0">
<input type="checkbox" name="checkbox2" value="1"
<?php
if ($row_2[0]=="1") {
echo "checked";
} else {
echo " ";
}
?>
> Item 2<br>
<input type="submit" name="Submit" value="Submit">
</form>
<br>
Reset
<br>
<?php
mysqli_close($conn);
?>
</body>
</html>

Hidden value not posted

I have some Problems with the following code.
The hidden field is not posted to the next page.
I have tried to put it next to the option field, but that creates some different problems like duplicating the dropdownmenue.
can anyone help me please?
<?php
$dbhost = 'localhost';
$dbuser = '-----';
$dbpass = '-----';
$db = '-----';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db);
$query = "SELECT * FROM Eintraege"; $result = mysql_query($query);
?>
<form action="deletescript.php" method="post">
<select name="loeschen">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ID'];?>"><?php echo $line['Titel'];?></option>
<?php
}
?>
</select>
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="hidden" name="titel" value="<?php echo $line['Titel'];?>" />
<?php
}
?>
Vorname <br /><input type="text" name="name" value="" class="text" /><br /><br />
Name <br /><input type="text" name="vorname" value="" class="text" /><br /><br />
Email <br /><input type="text" name="email" value="" class="text" /><br /><br />
<input type="submit" name="submit" />
</form>
You should at least use mysqli, making sure you have the connection on a secure page like:
// connect.php
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
You have a couple of other problems too.
1) Since mysql_fetch_array() always returns the next row of results, when mysql_fetch_array() is called again in your second while loop, $line is falsey, because there are no more rows to fetch, so the loop does not run. You could reset($line) if you're using fetch like that, but I recommend otherwise.
2) You cannot use the same HTML name attribute twice, unless you add [] to the end of it. Then you can access it as an Array in PHP.
// otherpage.php
<?php
include 'connect.php'; $db = db(); $opts = $hdns = '';
if($q = $db->query('SELECT * FROM Eintraege')){
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$t = $r->Titel;
$opts .= "<option value='$t'>$t</option>";
$hdns .= "<input name='titel[]' type='hidden' value='$t' />";
}
// now you can echo $opts and $hdns where you want
}
else{
$errors[] = 'No result rows were found';
}
$q->free();
}
else{
$errors[] = 'database connection failure';
}
$db->close(); if(isset($errors))die(implode(' & ', $errors));
?>
To get the titel named inputs on the page you are submitting to, it's like:
<?php
if(isset($_POST['titel'])){
// get each one
foreach($_POST['titel'] as $t){
// $t is each one
}
}
?>
Note that getting data to put into hidden inputs then sending it back to the server is generally pointless, since you have access to that information anyways. You'll want to learn AJAX if you want something to go to the database based on Client input.

checked values for the SELECT: WHERE clause

I am trying to create a compare option between selected cars.
<?php
if(isset($_POST['compares'])) {
$id_nums = array($_POST['cBox']);
//$id_nums = array(1,6,12,18,24);
$id_nums1 = implode(", ", $id_nums);
$query = "SELECT * FROM wp_cars WHERE id in ($id_nums1)";
$cCars = mysql_query($query) or mysql_error();
while($car = mysql_fetch_array($cCars)) {
echo $car['cartitle']."<br/>";
echo $car['saleprice']."<br/>";
}
} else {
$query1 = "SELECT * FROM wp_cars";
$allcars = mysql_query($query1) or die(mysql_error()); `
while($car1 = mysql_fetch_array($allcars)) {
echo "<input type='checkbox' value=".$car1['id']." name='cBox[]' />";
echo $car1['cartitle']."<br/>";
echo $car1['saleprice']."<br/>";
}
}
?>
How to pass the checkbox name(cBox[]) array based on checkboxes selection.
<form action="compares.php" method="post">
<button name="compares">Select Cars to Compare</button>
</form>
$id_nums = array($_POST['cBox']);
$_POST['cBox'] is already an array, you are making a 2d array. Doing
$id_nums1 = implode(", ", $_POST['cBox']);
would do what you want. Although it is wide open to SQL injection.
From your HTML part, send inputs this way:
<form action="compares.php" method="post">
<?php foreach (mysql_fetch_array($allcars) as $car: ?>
<input type="checkbox" value="<?php echo $car['id']; ?>" name="cBox[]" />
<?php echo $car['cartitle']; ?><br />
<?php echo $car['saleprice']; ?><br />
<?php endforeach; ?>
</form>
And in your PHP part, receive inputs this way:
$id_nums = implode(",", $_POST['cBox']);

How to read/send post data with php and hold a variable in it

I have this code in a loop in my code, The loop makes one submit button for every member found. I need each button to have the members name stored in it, in a way it can be sent though post when that button is clicked. Im not sure if this is possible with post but i was trying a way i do it with URLS. Does anyone know how to do this?
<input type="submit" value="Attack" name="Attack?name=<?php echo $Member_name; ?>" />
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
}
Here is the whole code i was trying to store it in a hidden form but it only grabs the last member found and wont get others.
<?php
$sql = "SELECT name, rank FROM users ORDER BY rank DESC"; // Searches the database for every one who has being last active in the last 5 minute
$query = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($query);
$i = 1;
while($row = mysql_fetch_object($query)) {
$Member_name = htmlspecialchars($row->name);
$Member_level = htmlspecialchars($row->rank);
?>
<td><?php echo $i; ?></td>
<td><?php echo $Member_name; ?></td><td><?php echo $Member_level; ?></td><td>
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</td>
<?
if($i != $count) { // this counts the amount of people that are online and display the results.
echo "</tr><tr>";
}
$i++;
}
?>
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST['thename'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$profile_id = htmlspecialchars($row->id);
$profile_userip = htmlspecialchars($row->userip);
$profile_name = htmlspecialchars($row->name);
$profile_money = htmlspecialchars($row->money);
$profile_gang = htmlspecialchars($row->gang);
$profile_exp = htmlspecialchars($row->exp);
$profile_profile = htmlspecialchars($row->profile);
$profile_rank = htmlspecialchars($row->rank);
$profile_health = htmlspecialchars($row->health);
$profile_defence = htmlspecialchars($row->defence);
$profile_stanima = htmlspecialchars($row->stanima);
?>
OK, assuming everything else is working ok, and you are retrieving data.
Change this:
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
To this:
<form method="POST" action="">
<input type="hidden" name="name" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</form>
And also in your PHP, change this line:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
To:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST ['name'])."'";
This isn't the best way to do this, you will be generating loads of HTML elements depending how many users you have, but it should solve you problem (providing everything else is working and receiving data).
HTML 5 & Javascript would be perfect for this and is something you should look into.

PHP IF ELSE - If seems to be ignored?

i'm a bit of PHP noob, so sorry if this is a daft question, but I just can't figure this out by myself so any help would be greatly appreciated!
I am trying to create a modify page for an events web application. It seems to be working except when I try to validate the final if/else statement.
This statement returns the value of $row[0] and checks if its == NULL. If NULL, it should return an echo 'this event does not exist' to the user, if there is a value, it presents the user with a matrix of text boxes that they can change the data in.
Currently it works fine for the else statement when there is data found, but doesnt recognise the original if when there is no data. Coupled with that, the footer at the bottom of the page disappears!
Here is the main body of the code, i have highlighted the problem area. I understand that there is probably a more effective and efficient way of doing it all, but please keep it simple as I'm still learning. Thanks again. Dan
<div class="round">
<div id="main" class="round">
<span class="bold">MODIFY EVENT</span><br /><br />
On this page you can modify or delete the events that are stored on the database.<br />
Be aware that you cannot undo the DELETE function.<br />
<br />
Find Event:<br />
<table>
<form name="form1" id="form1" method="post" action="
<?php echo $_SERVER["PHP_SELF"]; ?>" >
<tr><th>By Date:</td><td><input type="text" name="modifyDate"
id="modifyDate" value="dd/mm/yy" /></td></tr>
<tr><th>By Name:</td><td><input type="text" name="modifyName" id="modifyName"
value="" /></td></tr>
<tr><th>Find All:</th><td><input type="checkbox" name="modifyAll"
id="modifyAll" /><td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Search" /></td></tr>
</form>
</table>
<?PHP
if(!isset($_POST['modify'])){
if(isset($_POST['submit'])){
$moddate = $_POST['modifyDate'];
If($moddate == "dd/mm/yy"){
$date = "";
}
else{
$newDate = str_replace("/",".",$moddate);
$wholeDate = $newDate;
$dateArray = explode('.', $wholeDate);
$date = mktime(0,0,0,$dateArray[1],$dateArray[0],$dateArray[2]);
}
$name = $_POST['modifyName'];
$all = $_POST['modifyAll'];
$host = "localhost";
$user = "user";
$password = "password";
$db = "database";
$con = mysql_connect($host,$user,$password) or die('Could not connect to Server');
$dbc = mysql_select_db($db, $con) or die('Could not connect to Database');
if($all != 'on'){
$q = "SELECT * FROM events WHERE date = '$date' || title = '$name' ";
}
else{
$q = "SELECT * FROM events";
}
$result = mysql_query($q);
$row = mysql_fetch_array($result) or die(mysql_error());
//THIS IS THE PROBLEM HERE!!!!
if($row[0]==NULL){
echo 'This event does not exist';
}
else{
?>
<form name="form1" id="form1" method="post" action="
<?phpecho $_SERVER['PHP_SELF']; ?>" >
<?PHP
$result = mysql_query($q) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$initialDate = date('d/m/y', $row['date']);
$ID = $row['ID'];
echo '<input type="text" name="inputEmail" id="inputEmail" value="'.$initialDate.'" />';
echo '<input type="checkbox" value=$ID name="toModify[]" style = "visibility: hidden;" /><br /><br />';
}
echo '<input type="submit" name="modify" value="Modify" />
<br /><br />';
}
}
}
else{
//modify database and return echo to user
}
?>
</div>
<div id="clear"></div>
</div>
</div>
</div>
<div id="footer" class="round shadow"></div>
</body>
</html>
mysql_fetch_array($result) returns false if there are no rows, so it's possible that even if there is nothing in the result, it's still returning a false and your if($row[0] == null) is evaluating to false, also.
In other words, you should be doing a more robust test on the return results from your query to catch fringe cases.
As others have mentioned or implied, here are some things you could / should be doing:
test for rows returned, not values in rows
test for existence of variable, not content of variable
check the database for errors returned
Is the field in the table it's pulling $row[0] from set to NOT NULL? If it is, it will never be a null value. Try instead something like (if empty($row[0]))
You could check the number of result rows to see if there are any events:
$result = mysql_query($q);
$numrows = mysql_num_rows ($result);
if($numrows === 0){
...

Categories