Query does not work - php

I made this code:
Acum, bifeaza materiile pe care le studiaza clasa aleasa:<br />
<form name="servForm" action="<?php $PHP_SELF; ?>" method="post" >
<table border="0">
<?php
$a = 0;
$rezultat = "SELECT id, materie
FROM materii
ORDER BY id";
$rezultat1 = mysql_query($rezultat);
while($plm = mysql_fetch_array($rezultat1))
{
if($a++ %5 == 0) echo "<tr>";
?>
<td align="center"><input type="checkbox" name="checkbox2[]" value="<?php echo $plm['id']; ?>" /></td>
<td style="text-align:left"><?php echo $plm["materie"]; ?> </td>
<?php
if($a %5 == 0) echo "</tr>";
}
?>
</table>
</div>
<br/>
<input type="reset" value="Sterge" /> <input type="submit" value="Salveaza" name="savebtn" />
</form>
<?php
if(isset($_POST['savebtn']))
{
foreach($_POST["checkbox2"] as $loc_id)
{
$query = "INSERT INTO materii_pe_clase(id_scoala,id_clasa,id_materie) VALUES('$scoalalui','$clasalui','$loc_id')"; //aici cauta ! :))
$result5 = mysql_query($query)
or die('eroare');
}//sfarsit foreact
}//sfarsit if isset
Why does the last query not work? p.s. its a school project, so mysql is ok, no need for mysqli. p.p.s I defindet the $scoalalui and $clasalui somwhere a little up the page. but they are not the problem, i tried replacing them with values. the query simply does not work. thanks!
thank you all!
EDIT
VARDUMP for $clasalui and $scoalalui
:
string '1' (length=1)
string '1' (length=1)

Your problem here is that, you have error tool turned off, because PHP should have said, something like this.
Notice: Undefined variable $PHP_SELF"
Since you don't see it, I'd assume that, its a root of your "problem".
PHP_SELF is not a variable, that's a constant. Its not even required here, as by default PHP sends data to its target URL.
I improved readability of your code, so that should work for you now,
<?php
// You want to see all errors? Fine:
error_reporting(E_ALL);
$a = 0;
$rezultat = "SELECT id, materie FROM materii ORDER BY id";
$rezultat1 = mysql_query($rezultat);
// If the form is submitted, this will be executed
if (isset($_POST['savebtn'])) {
foreach($_POST["checkbox2"] as $loc_id) {
$query = "INSERT INTO `materii_pe_clase` (`id_scoala`, `id_clasa`, `id_materie`) VALUES('$scoalalui', '$clasalui', '$loc_id')";
$result = mysql_unbuffered_query($query);
if (!$result){
die(mysql_error());
}
}
// And finally
die('Saved. Thanks');
}
?>
Acum, bifeaza materiile pe care le studiaza clasa aleasa: <br />
<form name="servForm" method="POST">
<table border="0">
<?php while($plm = mysql_fetch_array($rezultat1)) : ?>
<?php if ($a++ %5 == 0) :?>
<tr>
<?php endif; ?>
<td align="center">
<input type="checkbox" name="checkbox2[]" value="<?php echo $plm['id']; ?>" />
</td>
<td style="text-align:left"><?php echo $plm["materie"]; ?> </td>
<?php if($a %5 == 0) : ?>
</tr>
<?php endif; ?>
<?php endwhile; ?>
</table>
<br/>
<input type="reset" value="Sterge" />
<input type="submit" value="Salveaza" name="savebtn" />
</form>

Related

database field data not appearing in form textbox in PHP

i have this code in PHP and a database sql.. the situation is .. if i type the 1, 2 or 3 (productID) .. the textbox will be populated and field with database values.. but when i run the program.. fortunately it has no errors.. but when i type the id or 1 and click the submit button.. it doesnt get the neccessary values.. sorry for this im a complete newbie and im practicing PHP for a while now.. any help will do.. thank you..
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user'])){
header("Location: index.php");
}
$res = mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow = mysql_fetch_array($res);
?>
<?php
require('dbconnect.php');
$id = (isset($_REQUEST['productID']));
$result = mysql_query("SELECT * FROM tblstore WHERE productID = '$id'");
$sql = mysql_fetch_array($result);
if(!$result){
die("Error: Data not found");
} else {
$brandname = $sql['brandname'];
$price = $sql['price'];
$stocks = $sql['stocks'];
}
?>
<html>
<body>
<p>
hi' <?php echo $userRow['username']; ?> Sign Out
</p>
<form method="post">
<table align="center">
<tr>
<td>Search Apparel:</td>
<td><input type="text" name="search" name="productID" /></td>
</tr>
<tr>
<td>Brandname:</td>
<td><input type="text" name="brandname" value="<?php echo $brandname; ?>"/ </td>
</tr>
<tr>
<td>Price:</td>
<td><input type="text" name="price" value="<?php echo $price; ?>"/></td>
</tr>
<tr>
<td>Stocks:</td>
<td><input type="text" name="stocks" value="<?php echo $stocks; ?>"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Search" /></td>
</tr>
</table>
</form>
</body>
</html>
your getting the id incorrectly, you have:
<?php
$_REQUEST['productID']=8; //for testing
$id = (isset($_REQUEST['productID']));
if you check it you will find the output is true\false as returned by isset
var_dump($id); //true
what you should use is:
<?php
if(isset($_REQUEST['productID'])){ //maybe also check its a number and or valid range
$id=$_REQUEST['productID'];
}

getElementById() returns Null

I need to show result on the end of the page. When I try to add the feedback using getElementById(), it always returns null, I guess it is out of the scope. Do you have any ideas how to fix that?
This is my JavaScript function.
function handler(var1,quizId,isCorrect,score,name,email) {
alert(var1);
//var id = parseInt(quizId);
quizId++;
var points=10;
if(isCorrect=='true'){
score=score+points;
document.getElementById("result").innerHTML="Correct<br/>";
var string_url="quiz.php?qusId="+quizId+"&score="+score+"&name="+name+"&email="+email;
setTimeout(function() {
window.location = string_url
}, 5000);
}
else{
document.getElementById("result").innerHTML="Wrong<br/>";
var string_url="quiz.php?qusId="+quizId+"&score="+score+"&name="+name+"&email="+email;
setTimeout(function() {
window.location = string_url
}, 5000);
}
}
This is My PHP Code.
<body >
<?php
$qusId=$_GET['qusId'];
$passscore=70;
if(isset($_GET['score'])){
$score=$_GET['score'];
}
else{
$score=0;
}
if(isset($_POST['name'])){
$name=$_POST['name'];
}
else{
$name=$_GET['name'];
}
if(isset($_POST['email'])){
$email=$_POST['email'];
}
else{
$email=$_GET['email'];
}
?>
<form action="email.php?name=<?php echo $name; ?>&email=<?php echo $email;?>&score=<?php echo $score;?>" method="POST">
<?php
$result = select("SELECT * FROM questions WHERE question_id='$qusId'");
//$row = mysql_fetch_array($result);
?>
<?php
$i=$_GET['qusId'];
if($qusId<11){
while($row = mysql_fetch_array($result))
{
?>
<table width="581" height="175" border="0" align="center">
<tr>
<td><h4><?php echo $i.'.' .$row['questions']; ?></h4>
<?php $i++; ?>
</td>
</tr>
<tr>
<td>
<?php $qId=$row['question_id'];?>
<?php
$result1=select("SELECT * FROM answers WHERE questionId='$qId' ORDER BY RAND()");
while($row1=mysql_fetch_array($result1)){
?><input type="radio" name="answers" value="<?php echo $row1['answers'];?>" onclick="handler('<?php echo $row1["feedback"]; ?>',<?php echo $qusId;?>,'<?php echo $row1["isCorrect"]; ?>',<?php echo $score;?>,'<?php echo $name; ?>', '<?php echo $email; ?>')
"/ ><?php echo $row1['answers']; ?><br/>
<?php
} ?>
</td>
</tr>
</table>
</form>
<p>
<?php
}
}
else{
?>
</p>
<p>
<table>
<tr><td>
Your Name:<?php echo $name;?><br /><br/>
Your Email:<?php echo $email;?><br /><br/>
Pass Score:<?php echo $passscore;?><br /><br/>
Your Score:<?php echo $score;?><br/><br/>
<?php if($score>=$passscore){?>
Result:Congratulation! You Have passed the questionnaire.<br/><br/
<?php }else{ ?>
Result:Sorry! Please Try again<br/>
<?php } ?>
</p>
</td></tr>
<tr><td><input class="submit" type="submit" value="Send Result" /></td></tr>
</table>
</form>
<table id="feedback">
<tr>
<td id="questions">1. What is Union Assurance brand pay off line<br/>
2. What does the Union Assurance brand colour orange signify<br/>
3. What does the Union Assurance brand colour grey signify<br/>
4. Union Assurance is baked by <br/>
5. Union Assurance Brand is built on the platform of <br/>
6. Union Assurance brand promise trust is delivered through <br/>
7. Union Assurance Symbol depicts<br/>
8. What’s Union Assurance brand ranked in the LMD Brands.<br/>
9. What’s Union Assurance brand value?<br/>
10. What is the best way to build your brand <br/> </td>
<td id="result">aaa</td>
</tr></table>
<?php
}
?>
</body>
getElementById() will always return null. because there in no "result" id available.
because of php script condition
if($qusId<11){}else{}
you need to put this line
<td id="result">aaa</td>
at the end of php script or you can add this line inside the if condition not in the else part.

arrange checkbox values in two columns

I have a form with check box values i want to arrange the checkbox in two columns instead of
one single long column.
How can i split it to two columns ?
Here is the code :
<form id="form" name="form" method="post" action="">
<table width="502" border="0">
<tr>
<td>
Name :
<input type="textbox" name="rcv_group_name" value="">
<input type="hidden" name="add" value="add" />
</td>
</tr>
<tr>
<td align="left">
<strong>HEADING</strong>
<?php
$q = "select * from Config_RCV";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) > 0)
{
$k=0;
while ($row = mysqli_fetch_array($r,MYSQLI_NUM))
{
?>
<br> <input type="checkbox" name ="rcv_val[]" value ="<? echo $row[0];?>" /> <? echo $row[1];?>
<?
$k++;
}
}
?>
</td>
</tr>
<tr>
<td align="right"><input type="submit" name="Submit" id="Submit" value="Submit" style="background-color:#999" />
< /td>
<td height="26" align="left"> </td>
<td> </td>
</tr>
</table>
<form>
add another table and make 2 columns by splitting 2'nd result:
if (mysqli_num_rows($r) > 0) {
$k=0;
echo '<table><tr>';
while ($row = mysqli_fetch_array($r,MYSQLI_NUM)) {
?>
<td><input type="checkbox" name ="rcv_val[]" value ="<?php echo $row[0];?>" /> <?php echo $row[1];?> </td>
<?php
$k++;
if($k%2 == 0){
echo '</tr><tr>';
}
}
echo '</table>';
}
use your $k
if ($k%2==0){
echo "<br />";
}
instead of the lone now
Using tables like above will probably be better for looks
You could just add a second column to your table:
echo "<tr>";
$i = 0;
while ($row = mysqli_fetch_array($r,MYSQLI_NUM)) {
if ($i++%2==0) {
echo "</tr><tr>";
}
echo "<td>".$CELL_CONTENT_HERE."</td>";
}
echo "</tr>";

Records not getting inserted in ascending order

I'm having a strange problem. I have a HTML page with PHP code which inserts data to a MySQL database. The data gets saved to the DB without any errors but in an incorrect order.
Here's a screenshot. The table on the right side displays the existing records. The first 2 records are shown correctly.
But when I save more records, it displays like this.
Even in the MySQL table, the records are inserted that way.
I'm not sure where exactly the problem is so I've shown the whole code for the page below. I've commented what each code block does. Please comment if you need me to clarify something.
The Location ID is an auto-generated code.
<html>
<head>
<script language="javascript">
function SelectAll(source)
{ //The code for the 'Select All' checkbox
checkboxes = document.getElementsByTagName("input");
for(var i in checkboxes)
{
if(checkboxes[i].type == 'checkbox')
{
checkboxes[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<?php
//Database connection initialization
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new Location ID */
$query = "SELECT LID FROM locations ORDER BY LID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row['LID'];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
//$id_num = sprintf("%03d", $id_num);
$new_id = $id_letter . $id_num;
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<! The table which displays the existing records >
<div id="display">
<b>Locations</b><br/><br/>
<form name="displayLocs" action="<?php echo $PHP_SELF; ?>" method="post" >
<table border="1">
<tr>
<th>Location ID</th>
<th>Code</th>
<th>Location</th>
<th><i>Delete</i></th>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><? echo $row["LID"]; ?></td>
<td align="center"><? echo $row["Code"]; ?></td>
<td><? echo $row["Location"]; ?></td>
<td align="center"><input type="checkbox" name="checkbox[]" value="<? echo $row["LID"]; ?>" /></td>
</tr>
<?php
}
?>
</table>
<br/>
<div id="buttons2">
<input type="checkbox" onclick="SelectAll(this)" />Select All <input type="reset" value="Clear" /> <input type="submit" value="Delete" name="deletebtn" />
</div>
</form>
</div>
<! New record saving area >
<b id="loc_caption_1">Enter a new location</b>
<div id="loca">
<form name="locForm" action="<?php echo $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Location ID</td>
<td><input type="text" name="lid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" name="code" style="text-align:right" /></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="loc" style="text-align:right" /></td>
</tr>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</div>
</form>
<?php
//Saving record
if(isset($_POST["savebtn"]))
{
$id = $_POST["lid"];
$code = $_POST["code"];
$location = $_POST["loc"];
$query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')";
$result = mysql_query($query, $conn);
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<br/><br/>";
echo "<strong>1 record added successfully!</strong>";
echo "<meta http-equiv=\"refresh\" content=\"3;URL=locations.php\">";
}
mysql_close($conn);
}
//Deleting selected records
if(isset($_POST["deletebtn"]))
{
for($i = 0; $i < $count; $i++)
{
$del_id = $_POST["checkbox"][$i];
$query = "DELETE FROM locations WHERE LID = '$del_id' ";
$result = mysql_query($query, $conn);
}
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=locations.php\">";
}
mysql_close($conn);
}
?>
</body>
</html>
Can anyone please tell me what is causing this and how to rectify it.
Thank you.
The records in the database are stored in the database in no particular order (well, there's some order to it, but it's up to the engine to determine it). If you want to get the results in a particular order, then you need to explicitly specify it when querying the data. In your case, make this change:
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations ORDER BY lid";
$result = mysql_query($query, $conn);

Updating a table with PHP and MYSQL

<?php require("inc_connect.php"); ?>
<h1 align="center">Farris Website</h1>
<hr width="1000">
<p align="center">
<table align="center" width="1000" border="3" bordercolor="#0066FF" >
<tr>
<td align="left" valign="top">
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_POST['id']); ?>">
<p><strong>Enter Name:</strong>
<input type="text" name="name">
<br />
ID:
<label for="select"></label>
<select name="id">
<?php
$query = "SELECT * FROM test";
$run = mysql_query($query);
while($output = mysql_fetch_array($run)){
echo "<option value=\"{$output['id']}\">{$output['id']}</option>";}
?>
</select>
</p>
<p>
<input type="submit" name="submit" value="Update!">
</p>
</form></td>
<td width="300" align="left" valign="top"><?php include("inc_output.php"); ?></td>
</tr>
</table>
</p>
The above is the index page ...
<?php
$connect = mysql_connect("localhost","root","");
$sel_database = mysql_select_db("test");
$name = mysql_real_escape_string( $_POST["name"] );
$id = (int) $_GET['id'];
$query = "UPDATE test SET name='{$name}'";
if($run = mysql_query($query)){
header("location: index.php");
exit;
}else{mysql_error();}
?>
And this is the page that processes the form.
The problem is that the record won't update if i set the id={$_GET['id']}
and if I remove that part it updates all the rows.
So updating according to id ...
Thanks in Advance
FarrisFahad
Try changing your form action to
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_GET['id']); ?>">
Also, doing an echo of $query might help debug your problem.
First, just be aware of SQL Injection - your code is wide open to it. See http://bobby-tables.com/
PHP Code
<?php
$connect = mysql_connect("localhost","root","");
$sel_database = mysql_select_db("test");
$name = mysql_real_escape_string( $_POST["name"] );
$id = (int) $_GET['id'];
$query = "UPDATE test SET name='{$name}' WHERE id = {$id}";
if($run = mysql_query($query)){
header("location: index.php");
exit;
}else{
# In production, don't show raw errors to users - log them to a file and
# present the user with a generic "There was a problem with the database"
# error. Or people can start sniffing for vulnerabilities in your site.
echo mysql_error();
}
?>
Page
<?php
require("inc_connect.php");
?>
<h1 align="center">Farris Website</h1>
<hr width="1000">
<p align="center">
<table align="center" width="1000" border="3" bordercolor="#0066FF" >
<tr>
<td><form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_GET['id']); ?>">
<p><strong>Enter Name:</strong>
<input type="text" name="name"><br />
<label for="select">ID:</label>
<select name="id" id="select">
<?php
$query = "SELECT * FROM test";
$run = mysql_query($query);
while( $r = mysql_fetch_array($run) ){
# I always use short, single character, variables when in loops.
# Saves alot of characters and potential confusion.
echo " <option value='{$r['id']}'>{$r['id']}</option>\n";
}
?>
</select>
</p>
<p>
<input type="submit" name="submit" value="Update!">
</p>
</form></td>
<td><?php include("inc_output.php"); ?></td>
</tr>
</table>
</p>
As you want to update that record which is selected from your dropdown. Moreover u have set your form method to POST. So you should try following:
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_POST['id']); ?>">

Categories