SQL query in MySql_Fetch_Array - php

When I show this PHP on browser I couldn't get any value to table. My table is empty.
<?php
$sql = "select * from worksets where 'groupid'='$targetid'";
$query = mysql_query($sql);
$kadro=$_GET['kadro'];
if((mysql_num_rows($query) > 0)) {
while($result = mysql_fetch_array($query)) {
$groupid = $result[0];
$groupname = $result[2];
$sql2 = "select flag from havestatus where kadroid='$kadro' and yid='$groupid'";
$query2 = mysql_query($sql2);
if((mysql_num_rows($query2) == 0)) {
$sql3 = "insert into havestatus values('$kadro','$yid',0)";
} else {
$select='selected';
}
?>
<tr>
<td width='50%'><?php echo $groupname;?></td>
<td></td>
<td width='20%'><input type="checkbox" name="bev" checked="<?php echo $select; ?>"></td>
</tr>
<?php
}
}
?>
If I change code in simple way like;
It shows some values and unfunctional checkbox.
I need to get some values from database and fill checkboxs according to 0 or 1 from database
and I have to insert all check box values with one form submit button to database as different rows for every check box.
<?php
$sql = "select * from worksets where groupid='$targetid'";
$query = mysql_query($sql);
if((mysql_num_rows($query) > 0)) {
while($result = mysql_fetch_array($query)) {
$groupid = $result[0];
$groupname = $result[2];
?>
<tr>
<td width='50%'><?php echo $groupname;?></td>
<td></td>
<td width='20%'><input type="checkbox" name="bev"></td>
</tr>
<?php
}
}
?>
it is work after 'groupid'='$targetid'" to groupid='$targetid'"

Related

Creating an HTML form basing on information extracted from an SQL database using while loop

I am trying to create a form, basing on information picked from the database using a while loop. I need some guidance on how to go about this. When form is supposed to return multiple values (of students) and then a text field for inputting marks is assigned to the students returned, which should allow the user input the marks and then submit the form.
Here is the code i have sofar
<form method="post">
<?php
//picking student details
$sql = mysql_query("SELECT *
FROM student, class, subject, assesment
WHERE
student.class_id = '$assesment_class'
AND subject.idsubject = '$assesment_subject'
AND subject.subject_option = 'Major'
AND class.idclass = student.class_id
AND class.idclass = subject.class_id
AND assesment.subject_idsubject = subject.idsubject
AND assesment.idassesment = '$ass'
");
$Count = mysql_num_rows($sql); //counting the the selected rows
if($Count > 0){
while($row = mysql_fetch_array($sql)){
//picking database values
$student_id = $row["idstudent"];
$student_names = $row["student_names"];
//Query for checking results
$sql1 = mysql_query("SELECT *
FROM result, student_has_result, grade, student, assesment
WHERE
student_has_result.student_id = '$student_id'
AND student_has_result.student_class_id = '$assesment_class'
AND student_has_result.assesment_id = '$ass'
AND student_has_result.result_id = result.idresult
AND result.grade_idgrade = grade.idgrade
AND student_has_result.assesment_id = assesment.idassesment
AND student_has_result.student_id = student.idstudent
AND student_has_result.result_id = result.idresult");
$Count1 = mysql_num_rows($sql1); //counting the the selected rows
if($Count1 > 0){
while($row = mysql_fetch_array($sql1)){
//picking database values
$mark = $row["mark"];
//echo $mark;
}
}else{
$mark = "";
}
?>
<tr>
<td><?php echo $student_names; ?></td>
<td>
<input type="text" name="result" placeholder="<?php echo $mark; ?>"/>
<input type="hidden" name="student" value="<?php echo $student_id; ?>"/>
<input type="hidden" name="assesment" value="<?php echo $ass; ?>"/>
</td>
</tr>
<?php
}
?>
<tr>
<td></td>
<td><button name="submit-results-button" type="submit" class="btn btn-success">-Submit Students Results Now-</button><br><br></td>
</tr>
</form>
Any guidance will be highly appreciated.

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, string given

When I click on search button without entering any text in textbox it gives me "Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, string given" this error, how can I sort out this issue,here is my code any help will be appreciated
<?php
$title ="Manage Page";
include "includes/home_page_header.php";
?>
<?php
$error_array = array();
$count =1;
$firstName = $lastName = $email = $status =$res_users = $checkbox ="";
if(isset($_POST['Search']))
{
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$status = $_POST['status'];
if($firstName !="")
{
$sql_users ="SELECT * FROM `users` WHERE `firstName` LIKE '$firstName'";
}
else if($lastName !="")
{
$sql_users ="SELECT * FROM `users` WHERE `lastName` LIKE '$lastName'";
}
else if($email !="")
{
$sql_users ="SELECT * FROM `users` WHERE `email` LIKE '$email'";
}
else if($firstName !="" && $lastName !="")
{
$sql_users ="SELECT * FROM `users` WHERE `firstName` LIKE '$firstName' AND `lastName` LIKE '$lastName'";
}
else
{
$sql_users = "SELECT * FROM `users`";
}
if(isset($_GET['user_id']))
{
$user_id = $_GET['user_id'];
$sql_users = "DELETE from `users` WHERE user_id=".$user_id;
if ($link->query($sql_users) == TRUE)
{
$error ="Record deleted successfully";
array_push($error_array,$error);
}
if ($link->query($sql_users) == FALSE)
{
$error = "Your Abort Delete operation";
array_push($error_array,$error);
}
}
if($status == "Active")
{
$sql_users= "SELECT * FROM `users` WHERE `status` LIKE 'Active'";
$res_users = mysqli_query($link,$sql_users);
if($res_users && mysqli_num_rows($res_users) > 0)
{
while($log_row_users = mysqli_fetch_assoc($res_users))
{
$status = $log_row_users["status"];
}
}
}
if($status == "Inactive")
{
$sql_users= "SELECT * FROM `users` WHERE `status` LIKE 'Inactive'";
$res_users = mysqli_query($link,$sql_users);
if($res_users && mysqli_num_rows($res_users) > 0)
{
while($log_row_users = mysqli_fetch_assoc($res_users))
{
$status = $log_row_users["status"];
}
}
}
$res_users = mysqli_query($link ,$sql_users);
}
if(isset($_POST['delete_all']))
{
}
?>
<script>
$(document).ready(function()
{
$(".delete_button").on('click',function()
{
var result =confirm("Are you sure you want to delete ?");
if(result)
{
return true;
}
else
{
return false;
}
});
});
//function wantTodelete(user_id)
//{
// return confirm("Are you sure you want to delete ?");
//}
$(document).ready(function()
{
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
});
</script>
<table border="1px" class="manage_table">
<form name="listingForm" action="" method="post">
<tr>
<?php
if($error_array !=0)
{
foreach($error_array as $value)
{
echo "<tr style='color:green;'><td></td><td> ". $value. "</td></tr>";
}
}
?>
</tr>
<tr>
<td></td>
<td><input type="text" name="firstName"></td>
<td><input type="text" name="lastName"></td>
<td><input type="text" name="email"></td>
<td>
<select name="status">
<option>Select Status </option>
<option value="Active" <?php echo $status;?>>Active </option>
<option value="Inactive" <?php echo $status;?>>Inactive </option>
</select>
</td>
<td><input style="width:135px" type="submit" name="Search" value="Search"></td>
<td><input type="submit" id="delete_all" name="delete_all" value="Delete All" onclick="return deleteAll();" /></td>
</tr>
<tr>
<th>Sr.No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Status</th>
<th>Action</th>
<th><input type="checkbox" id="checkAll" name="check_all[]"/></th>
</tr>
<?php
if($log_row_users = mysqli_fetch_assoc($res_users))
{
$user_id = $log_row_users['user_id'];
$firstName = $log_row_users['firstName'];
$lastName = $log_row_users['lastName'];
$email = $log_row_users['email'];
$status = $log_row_users['status'];
?>
<tr>
<td><?php echo $count++ ;?></td>
<td><?php echo $firstName;?></td>
<td><?php echo $lastName ;?></td>
<td><?php echo $email ;?></td>
<td>
<?php
if($status == "Active")
{
echo "<b style='color:#3CF'>".$status."</b>";
}
if($status == "Inactive")
{
echo "<b style='color:#F00'>".$status."</b>";
};
?>
</td>
<td>
<a style="margin-left:25px" href="http://localhost/sample/home_page_edit.php?user_id=<?php echo $user_id;?>" onclick="redirectMe();" name="redirect" id="redirect"><img src="images/pencil.png" /></a>
<a style="margin-left:35px" href="http://localhost/sample/home_page_manage.php?user_id=<?php echo $user_id;?>" name="delete_button" class="delete_button" ><img src="images/delete.png" /></a>
</td>
<th>
<input name="checkbox[]" type="checkbox" id="checkbox[]" class="checkbox">
</th>
</tr>
</form>
<?php
}
?>
</table>
<?php
include "includes/home_page_footer.php";
?>
Try this one it will help you
if(isset($_REQUEST['Search']))
{
$q = "SELECT * FROM users WHERE user_id!='' ";
$firstName = $_REQUEST['firstName'];
$lastName = $_REQUEST['lastName'];
$email = $_REQUEST['email'];
$status = $_REQUEST['status'];
$temp='';
if(!empty($firstName))
{
$temp.=" AND ";
$temp.="firstName LIKE '%$firstName%'";
}
if(!empty($lastName))
{
$temp.=" AND ";
$temp.="lastName LIKE '%$lastName%'";
}
if(!empty($email))
{
$temp.=" AND ";
$temp.="email LIKE '%$email%'";
}
if(!empty($status))
{
$temp.=" AND ";
$temp.="status LIKE '$status'";
}
$qry = $q. $temp. " order by user_id ASC";
}
else
{
$qry = "SELECT * FROM users order by user_id DESC";
}
At start of your script you init $res_users with an empty string ("").
If $_POST['Search'] is not set, you never execute $res_users = mysqli_query( ... );, so $res_users still remains an empty string when you call
if($log_row_users = mysqli_fetch_assoc($res_users))
I suggest you to normalize your code performing all operations concerning queries before HTML output. Otherwise you can repeat the $_POST check:
if(isset($_POST['Search']) && $log_row_users = mysqli_fetch_assoc($res_users))
Fast querying with a more Object orientated method:
[...]
$sql_users= "SELECT * FROM `users` WHERE `status` LIKE 'Inactive'";
foreach($link->query($sql_users) as $row)
{
$status = $row["status"];
}
[...]
You can also use it as a boolean to check queries ran:
[...]
if($db->query($sql)): [...] endif;
[...]
I'd also suggest that you're checking that your result is not null before looping through its data:
[...]
$result = mysqli_query($link, $sql);
if($result != null): [...] endif;
[...]
Also, take a look at #fusion3k 's answer. Your infrastructure is causing you limitations. You'll need to re-evaluate how you're approaching this and also check how to prevent SQLi injections.
Edit: You could manage your data flow more simply using an Object-orientated approach (OOP).
class Handler
{
public function __construct( $args )
{
if(is_array( $args ))
{
switch($args['type'])
{
case "Insert":
break;
default:
break;
}
[...]
Then work with it like so:
new Handler(array(
'type' => $_POST[...]
[...] => [...]
));

Database won't stay updated after switching script

I'm trying to update this database, and I've verified within this script that the update is completed, and that the $nw and $p variables are correct.
<?php
session_start();
$num = (int) $_SESSION["cart"];
$cart = $num + 1;
$_SESSION["cart"] = (string) $cart;
$nme = $_POST['nameofitem'];
$pst = $_SESSION["user"];
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
$query = "select * from Items where Items.Id = '$nme'";
$result = $db->query($query) or die ($db->error);
$item = $result->fetch_array();
$nw = $item[5] - 1;
$p = (int) $pst;
echo $p;
$query3 = "update Items set Quantity = '$nw' where Id = '$p'";
$db->query($query3) or die ("Invalid insert " . $db->error);
$query2 = "insert into Bought (Name, Cost, BuyerID) values ('$item[1]', '$item[4]', '$pst')";
$db->query($query2) or die ("Invalid insert " . $db->error);
header("Location: store.php");
?>
However, when it redirects to this script, it echoes the information as if it weren't updated. What is the problem?
<?php
session_start();
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
$user = $_SESSION["user"];
$pw = $_SESSION["pw"];
# determines number of items in cart to display
if (!isset($_SESSION["category"]))
$_SESSION["category"] = "Book";
if (isset($_POST["Ccategory"])) {
$cat = $_POST["Ccategory"];
$_SESSION["category"] = $cat;
}
if (!isset($_SESSION["cart"]))
$_SESSION["cart"] = "0";
$cart = $_SESSION["cart"];
?>
<!DOCTYPE html>
<html>
<?php # setting up table with items to buy ?>
<table border = "1" border-spacing = "5px" >
<caption><h2> UVA Bookstore 2.0</h2>
<p align=right> Items in cart: <?php echo $cart?> </p> <br />
<b><i>Welcome to the new and improved bookstore with a better selection than ever</i></b>
<br/><br/>
</caption>
<tr align = "center">
<th>Item</th>
<th>Description</th>
<th>Price</th>
<th>Number left</th>
<th>Buy</th>
</tr>
<?php
$category = $_SESSION["category"];
$query = "select * from Items where Items.Category = '$category'";
$result = $db->query($query) or die ($db->error);
$rows = $result->num_rows;
for ($i = 0; $i < $rows; $i++)
{
$row = $result->fetch_array();
?>
<form action="addtocart.php"
method="POST">
<tr align = "center">
<td>
<?php
echo $row[1];
?>
</td>
<td> <?php echo $row[3];?> </td>
<td> <?php echo $row[4];?> </td>
<td> <?php echo $row[5];?> </td>
<?php # sets up add to cart button that adds item to cart ?>
<td> <input type = "hidden" name ='nameofitem'
value= "<?php echo $row[0]?>">
<input type='submit' value='Add to Cart'> </input> </td>
</tr>
</form>
<?php
}
# form to check out and go to summary page ?>
<form action = "store.php"
method = "POST">
<tr align = "center"> <td>
<select name = "Ccategory">
<option value = "Book">Books</option>
<option value = "Music">Music</option>
<option value = "Car">Cars</option>
</select>
<input type = "hidden" name = "cat"> </td>
<td> <input type = "submit" value = "Switch Category"> </td>
</form>
<form action="summary.php"
method="POST">
<td> <input type = "submit" value = "Check out"> </td> </tr>
</table><br/>
</form>
</html>
Have you tried changing
$query3 = "update Items set Quantity = '$nw' where Id = '$p'";
to
$query3 = "update Items set Quantity = '$nw' where Id = $p";
The best way to determine if an UPDATE should work is to replace it with a SELECT containing the same WHERE clause. This way you can see what rows would be changed if you were to run the original query.
Otherwise, it seems to be the case that your changes in the current transaction are never committed. Is this the only script that has an issue with updates to the database? Please see the PHP manual for more information:
//mysqli::commit -- mysqli_commit — Commits the current transaction
bool mysqli::commit ([ int $flags [, string $name ]] )
A commit should be issued when you are done doing all updates that have dependencies (or for those that are atomic), however, you don't always have to commit depending on the configuration of your server. Also, it looks like your script has SQL injection vulnerabilities as other have mentioned. It would probably be best to use prepared statements or sanitize your inputs.

How to edit, delete and add in php mysql without jquery or java script?

I am trying to delete , edit and add new recodes on the same page but it seems am failing to make it work .And I do not want to do it using ajax jquery or java script but only php .I need some help please below are my code :
<?php
include_once('con.php');
$strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL);
echo "<table border='1' ><tr bgcolor='#eeeeee'><td>Name</td> <td colspan='2'>Action</td></tr>";
while($row = mysql_fetch_assoc($rs))
{
$film_id = $row['film_id'];
$name = $row['name'];
$hometeam= mysql_real_escape_string($name);
echo "<tr bgcolor='#eeeee'><td>$name</td> <td><a href='index.php?film_id=$film_id' name ='edit'>Edit</a></td><td><a href='index.php?film_id=$film_id' name ='delete'>Delete</a></td></tr>";
}
?>
<?php
$strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL);
$row = mysql_fetch_assoc($rs);
$film_id= $row['film_id'];
$name = $row['name'];
$name = mysql_real_escape_string($name);
$film_id= $_GET['film_id'];
?>
<?php
if(isset($_POST['edit'])){
?>
<table>
<form action="index.php" method="post">
<tr>
<td>
Name
</td>
<td>
<input type = "text" name = "name" value="<?php echo $name;?>">
</td>
</tr>
<input name="film_id" type="hidden" id="film_id" value="<?php echo $film_id; ?>">
<tr>
<td>
<input type = "submit" name = "submit" value="update">
</td>
</tr>
<?php
$name = (isset($_POST['name']))? trim($_POST['name']): '';
$film_id = $_POST['film_id'];
$sql = "UPDATE filmsbox SET name='$name'
WHERE film_id ='$film_id'";
$result = mysql_query($sql);
if($result)
{
echo "Success";
}
else
{
echo "Error";
}
}
?>
<?php
/*Delete section*/
if(isset($_POST['delete']))
{
$film_id = $_GET['film_id'];
$delete = "DELETE FROM filmsbox WHERE film_id = '$film_id'";
$result = mysql_query($delete);
if($result)
{
echo "Record deleted successfuly ";
}
else
{
echo "No data deleted";
}
}
?>
Couple of pointers:
You only need to escape values before they go into the database, not when they come out and are used in HTML i.e $hometeam = mysql_real_escape_string($name);
You are pulling the same query from the database twice in quick succession which is not needed. You can remove one of the 2 $strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL); sections from the top of your code
You need to run any update/delete queries on the data before you then do your select query to pull out the records for the page, otherwise your changes will not be shown
You should be escaping the values for your update and delete queries to prevent SQL injection
Edit:
To reload the page in an edit mode, you need to change the link URL in the table to something like
<a href='index.php?film_id=$film_id&edit=1' name ='edit'>Edit</a>
Then your edit block needs to be
if ($_GET['edit']) {
I want to be clear this is not in any way a secure method of editing values, as anyone can put ?edit=1 on the url and get to the form

Echo inside and Echo

I'm using echo to sum up the results form a Table. Inside this echo, I place another echo to show all the results form another table. On this page I have an array, I want every item in that array, that is also in the result from the table, to be checked. I use the code below (remember: this code is inside another echo!), it's not functioning, why not?
<?php
$query = "SELECT * FROM profilestemp";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$merkenarray = unserialize($row[merken]);
echo "
A VERY BIG OTHER PART OF THE FORM....
<tr>
<td style=\width:150px;background-color:#a8c11f;padding:2px;\"><p style=\"color:White;font-weight:bold\"><b>Merken</b></p></td>
<td><div id=\"rubrieken\">
<?php
$sql = \"SELECT merknaam FROM merken\";
$result = mysql_query($sql);
while ($row2 = mysql_fetch_array($result)) {
if (isset($merkenarray) && is_array($merkenarray) && in_array($row2[merknaam], $merkenarray)) {
$checked = \"checked='checked'\";
}
else $checked = \"\";
echo \" <input \".$checked.\" type=\"checkbox\" name=\"merken[]\" value='\" . $row2[merknaam] . \"'> \" . $row2[merknaam] . \" <Br /> \";
}
?>
</div></td>
</tr>
}
?>
Instead of using echo in your function, have it return the string to be output. An example:
function functionName() {
return 'Some content to be output';
}
echo functionName();
Additionally, this will give your function more flexibility, as you might not want to echo the result every time, e.g:
function functionName() {
return 'Some content to be output';
}
// Write the result of functionName to a file
file_put_contents('content.txt', functionName());
Your code should look like this
<?php
$query = "SELECT * FROM profilestemp";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$merkenarray = unserialize($row[merken]);
?>
A VERY BIG OTHER PART OF THE FORM....
<tr>
<td style="width:150px;background-color:#a8c11f;padding:2px;"><p style="color:White;font-weight:bold"><b>Merken</b></p></td>
<td><div id="rubrieken">
<?php
$sql = "SELECT merknaam FROM merken";
$result = mysql_query($sql);
while ($row2 = mysql_fetch_array($result)) {
if (isset($merkenarray) && is_array($merkenarray) && in_array($row2[merknaam], $merkenarray)) {
$checked = "checked='checked'";
}
else $checked = "";
echo " <input ".$checked." type="checkbox" name="merken[]" value='" . $row2[merknaam] . "'> " . $row2[merknaam] . " <Br /> ";
}
?>
</div></td>
</tr>
<?php }?>

Categories