ON/OFF value status always offline - php

I have this code and when i click button "off"status is always off but in db is on
example
i click on at galery query in db set to value = 1 (on) but status says off
if i click off still say is off
show.php
<?php
$mysqli = new mysqli("localhost", "root", "pass", "strona");
//----------
function topnews()
{
$query="SELECT topnews FROM opcje";
$topnews=$result=mysql_query($query);
if($topnews == 1)
{
echo "<div id='on'>wlączone</div>";
}
else if($topnews == 0)
{
echo "<div id='off'>wyłączone</div>";
}
}
//------------
function galeria()
{
$query2="SELECT galeria FROM opcje";
$galeria=$result=mysql_query($query2);
if($galeria == 1)
{
echo "<div id='on'>wlączone</div>";
}
else
{
echo "<div id='off'>wyłączone</div>";
}
}
//--------------
function logowanie()
{
$query3="SELECT logowanie FROM opcje";
$logowanie=$result=mysql_query($query3);
if($logowanie == 1)
{
echo "<div id='on'>wlączone</div>";
}
else
{
echo "<div id='off'>wyłączone</div>";
}
}
//--------------
function rejestracja()
{
$query4="SELECT rejestracja FROM opcje";
$rejestracja=$result=mysql_query($query4);
if($rejestracja == 1)
{
echo "<div id='on'>wlączone</div>";
}
else
{
echo "<div id='off'>wyłączone</div>";
}
}
$mysqli->close();
?>
<form action="onoff.php" method="post">
<tr>
<td><p><h3>Okienka na głównej</h3></p><hr></td>
</tr>
<tr>
<td>Status<br></td>
<td><?php topnews(); ?><br></td>
<td><input type="submit" value="wlacz" name="on"/></td>
<td><input type="submit" value="wylącz" name="off"/></td>
</tr>
<tr>
<td><p><h3><hr>Galeria</h3></p><hr></td>
</tr>
<tr>
<td>Status<br></td>
<td><?php galeria(); ?><br></td>
<td><input type="submit" value="wlacz" name="on2"/></td>
<td><input type="submit" value="wylącz" name="off2"/></td>
</tr>
<tr>
<td><p><h3><hr>Logowanie</h3></p><hr></td>
</tr>
<tr>
<td>Status<br></td>
<td><?php logowanie(); ?><br></td>
<td><input type="submit" value="wlacz" name="on3"/></td>
<td><input type="submit" value="wylącz" name="off3"/></td>
</tr>
<tr>
<td><p><h3><hr>Rejestracja</h3></p><hr></td>
</tr>
<tr>
<td>Status<br></td>
<td><?php rejestracja(); ?><br></td>
<td><input type="submit" value="wlacz" name="on4"/></td>
<td><input type="submit" value="wylącz" name="off4"/></td>
</tr>
</form>
onoff.php
<?php
$con=mysqli_connect("localhost","root","pass","strona");
// Check connection
if (mysqli_connect_errno()) {
echo "Błąd podczas łączenia z bazą danych: " . mysqli_connect_error();
}
//===========//top news//===============//
if(isset($_POST['on']))
{
$on = $_POST['on'];
$sql = "UPDATE opcje SET topnews = '1'";
echo "<script>alert('Włączono Pomyslnie');</script>";
header("Refresh: 1; url=wlwyl.php");
}
else if(isset($_POST['off']))
{
$off = $_POST['off'];
$sql = "UPDATE opcje SET topnews = '0'";
echo "<script>alert('Wyłączono Pomyslnie');</script>";
header("Refresh: 1; url=wlwyl.php");
}
//===========//galeria//===============//
if(isset($_POST['on2']))
{
$on2 = $_POST['on2'];
$sql = "UPDATE opcje SET galeria = '1'";
echo "<script>alert('Włączono Pomyslnie');</script>";
header("Refresh: 1; url=wlwyl.php");
}
else if(isset($_POST['off2']))
{
$off2 = $_POST['off2'];
$sql = "UPDATE opcje SET galeria = '0'";
echo "<script>alert('Wyłączono Pomyslnie');</script>";
header("Refresh: 1; url=wlwyl.php");
}
//===========//logowanie//===============//
if(isset($_POST['on3']))
{
$on3 = $_POST['on'];
$sql = "UPDATE opcje SET logowanie = '1'";
echo "<script>alert('Włączono Pomyslnie');</script>";
header("Refresh: 1; url=wlwyl.php");
}
else if(isset($_POST['off3']))
{
$off3 = $_POST['off'];
$sql = "UPDATE opcje SET logowanie = '0'";
echo "<script>alert('Wyłączono Pomyslnie');</script>";
header("Refresh: 1; url=wlwyl.php");
}
//===========//rejestracja//===============//
if(isset($_POST['on4']))
{
$on4 = $_POST['on'];
$sql = "UPDATE opcje SET rejestracja = '1'";
echo "<script>alert('Włączono Pomyslnie');</script>";
header("Refresh: 1; url=wlwyl.php");
}
else if(isset($_POST['off4']))
{
$off4 = $_POST['off'];
$sql = "UPDATE opcje SET rejestracja = '0'";
echo "<script>alert('Wyłączono Pomyslnie');</script>";
header("Refresh: 1; url=wlwyl.php");
}
//============//kiedys cos//==============//
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>

Your code has a ton of these in them:
if($topnews = 1)
This isn't what you want to do - It's assigning the value of 1 to $topnews, so this if statement is always true and is always executed. You're looking for:
if($topnews == 1)
Now, onto your code:
$topnews=$result=mysql_query($query);
You shouldn't be using mysql_* functions anymore. But, the value of $topnews is a MySQL result object, and doesn't have the value from the database. You need to fetch it, something similar to:
$result = mysql_query( $query);
$row = mysql_fetch_array($result);
$topnews = $row['topnews'];

You're using the wrong comparison operators.
Use == or === in the if statement.
To make it even safer, swap the constant and the variable!
if (1 == $galeria)
is safer than
if ($galeria == 1)

Related

How do I $_GET id and true before updating database

I don't really know how to explain my question, but I am in need. Of how to display warning before update into database.
example:
<?php
#Get id and yes before update waring code
if (isset($_GET["acept"])) {
$acept = $_GET["acept"];
} else {
$acept = " ";
}
if ($acept == "update") {
if (isset($_GET["yes"]) & $_GET["yes"] == true) {
$id = (int)$_GET["id"];
$query = mysqli_query($conn, "update users set balance='$redut' where id='$id'");
if ($query) {
echo " Successfull";
} else {
echo "retry";
}
exit();
}
$id = (int)$_GET["id"];
echo "<div class='topnav'>System Warning</div><div class='msg'>Are You Sure ?</div><div class='gap'></div><div class='button'><a href='?acept=update&yes=true&id=$idd'><font color='red'>Yes</font></a> | <a href='user.php'>No</a></div>";
}
here is my full code where I am trying to display the warning before updating into database
<?php
include_once 'init.php';
$error = false;
// check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if (preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if (isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username = $_SESSION["user_name"];
$result = mysqli_query($conn, "select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$idd = $row["id"];
$username = $row["username"];
$id = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"];
$qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
if ($show < $balance) {
echo "you cant buy here";
exit();
} elseif ($show > $balance) {
$redut = $balance - $show;
#display the warning before updating into daase if (isset($_GET["acept"])) {
$acept = $_GET["acept"];
} else {
$acept = " ";
}
if ($acept == "update") {
if (isset($_GET["yes"]) & $_GET["yes"] == true) {
$id = (int)$_GET["id"];
$query = mysqli_query($conn, "update users set balance='$redut' where id='$id'");
if ($query) {
echo " Successfull";
} else {
echo mysql_error();
}
exit();
}
$idd = (int)$_GET["id"];
echo "<div class='topnav'>System Warning</div><div class='msg'>Are You Sure ?</div><div class='gap'></div><div class='button'><a href='?acept=update&yes=true&id=$idd'><font color='red'>Yes</font></a> | <a href='user.php'>No</a></div>";
}
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table><input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div></table>
I don't really know where am wrong with the code, but the expected warning before update do not display and the database is not updated. big thanks in advance.
if (isset($_GET["yes"]) & $_GET["yes"] == true) {
change this to
if (isset($_GET["yes"]) && $_GET["yes"] == 'true') {
servers take the GET method as a string. not boolean
I don't really get what kind of warning you are trying to display. If it is for a user you can use the print or echo function. It is possible to echo a block of html so:
echo '<div class=”warning-msg”><p>MY WARNING</p></div>'
will display the block. Only thing is the warning may not be in de correct place or time.
Or in js
echo ‘<script type="text/javascript">’
echo ‘alert(“message successfully sent”)’
echo ’</script>’
If the waring is for jou personal use the build in php error handeling handeling.
Here is a snippet for a query function using php.
Use:
$query = query("SELECT ... (SQL)", $variable);

Counter increasing in refresh and in reload in php

I have set a counter in php code to increment the id value in mysql on every next click but when I refresh or reload the page the value is increasing automatically is there any solution for this problem or any other substitute.
<?php
$db = mysqli_connect('localhost','root','root','rahul');
$questions ="";
$msg2 ="";
$o1 ="" ;
$o2 ="" ;
$o3 ="" ;
$o4 ="" ;
$disable = "";
$disable2 = "";
session_start();
if(empty($_SESSION['count']))
$_SESSION['count'] = 0;
if(isset($_POST['sub1'])){
$ans = $_POST['ans'];
$email = "rahul#gmail.com";
$order = $_SESSION['count']+1;
echo $order;
$_SESSION['count'] = $order;
$sql = (" SELECT * FROM qna WHERE id = $order ");
$query = mysqli_query($db, $sql);
$row=mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
$disable="";
if($_SESSION['count']>5)
{
$disable = "disabled";
}
$disable2 = "";
if($_SESSION['count']<=1)
{
$disable2 = "disabled";
}
//$sql2 = "INSERT INTO result (id, answer, email) VALUES ('', '$ans', '$email') ".mysqli_error();
/*
$sql3 = mysqli_query($db, "INSERT INTO result (answer, email) VALUES ('$ans', '$email')");
if(mysqli_affected_rows($sql3)== true)
{
echo "inserted";
}
else
{
echo "not inserted";
}
*/
echo $ans. $email;
}
$sql4 = mysqli_query("select * from result");
$row = mysqli_fetch_array($db, $sql4);
// while()
echo $row['id'];
for($i=1;$i<=5;$i++)
{
}
?>
<?php
if(isset($_POST['sub2'])){
$result2 = $_SESSION['count']-1;
$_SESSION['count'] = $result2;
$sql = (" SELECT * FROM qna WHERE id = $result2 ");
$query = mysqli_query($db, $sql);
$row=mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
if($_SESSION['count']<=1){
$disable2 = "disabled";
}
}
session_write_close();
?>
<?php
if(isset($_POST['start'])){
$order = $_SESSION['count']+1;
echo $order;
$_SESSION['count'] = $order;
$sql = (" SELECT * FROM qna WHERE id = 1 ");
$query = mysqli_query($db, $sql);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
$disable="";
if($_SESSION['count']>=5)
{
$disable = "disabled";
}
$disable2 = "";
if($_SESSION['count']<=1){
$disable2 = "disabled";
}
session_write_close();
}
?>
<center><br><br><br>
<form method="post">
<input type="submit" name="start" value="start">
</form>
Log out
<form action="" method="post" >
<table border="1" height="300px" width="500px">
<tr>
<th colspan="2"><?php echo $questions; ?></th>
</tr>
<tr>
<td><input type="radio" name="ans" id="ans" value="<?php echo $o1; ?>"><?php echo $o1; ?></td>
<td><input type="radio" name="ans" value="<?php echo $o2; ?>"><?php echo $o2; ?></td>
</tr>
<tr>
<td><input type="radio" name="ans" value="<?php echo $o3; ?>"><?php echo $o3; ?></td>
<td><input type="radio" name="ans" value="<?php echo $o4; ?>"><?php echo $o4; ?></td>
</tr>
<tr colspan="2">
<td><center><input type="submit" name="sub1" value="next" <?php echo $disable ?>> </td>
<td><center><input type="submit" name="sub2" value="previous" <?php echo $disable2 ?>>
<input type="submit" name="submit3" value="submit" > </td>
</tr>
</form>
</table>
<?php
if(isset($_POST['submit3']))
{
$ans = $_POST['ans'];
$email = "dummy";
//$sql2 = "INSERT INTO result (id, answer, email) VALUES ('', '$ans', '$email') ".mysqli_error();
$sql3 = mysqli_query($db, "INSERT INTO result (answer, email) VALUES ('$ans', '$email')");
if(mysqli_affected_rows($sql3)== true)
{
echo "inserted";
}
else
{
echo "not inserted";
}
echo $ans. $email;
}
?>
when you are reloading a web-page, you are reloading its POST (and also GET) data as well if it's there. if you are submitting a form then the target page contains POST data in its header. so if you reload this page it's like you would have clicked the button again.
since you are already using a session there is a workaround:
add a hidden field with a micro-timestamp in your form. this micro-timestamp will be different every time your page gets loaded (per user) - but this "new" timestamp only get's posted when you use the button. when you just refresh the page, you are reloading with the old timestamp.
so you just need to save compare the last timestamp (saved in a session variable) with the currently posted timestamp. if they are equal - the page just got refreshed - if they are not equal, then you got a new timestamp which was sent by your form:
<?php
session_start();
if(!isset($_SESSION["timestamp"]))
$_SESSION["timestamp"] = 0;
if(!isset($_POST["timestamp"]))
$_POST["timestamp"] = 0;
// previous timestamp - saved in session variable:
$prev_ts = $_SESSION["timestamp"];
// currently posted timestamp:
$post_ts = $_POST["timestamp"];
if($prev_ts != $post_ts)
{
// code to increase your counter goes here.
$feedback = "button pressed";
}
else
{
// do nothing when the page just got refreshed
$feedback = "refreshed";
}
$_SESSION["timestamp"] = $post_ts;
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php echo $feedback; ?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
<input type="hidden" name="timestamp" value="<?php echo microtime(); ?>">
<input type="submit" name="go" value="count">
</form>
</body>
</html>

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[...]
[...] => [...]
));

Using combobox on a edit page with PHP

I have two tables, tblPlayer(PlayerID, PlayerName,PlayerTeam(int) ) and tblTeams (TeamID, TeamName)
On a PHP page I have a function to find the selected player, function is as follows,
function find_selected_player() {
global $sel_player;
if (isset($_GET['id'])) {
$sel_player = get_player_by_id($_GET['id']);
} else {
$sel_player = NULL;
}
}
my other function as follows,
function get_player_by_id($player_id) {
global $conn;
$query = "SELECT * ";
$query .= "FROM tblPlayer ";
$query .= "WHERE PlayerID =" . $player_id ." ";
$query .= "LIMIT 1";
$result_set = mysql_query($query, $conn);
confirm_query($result_set);
if ($player = mysql_fetch_array($result_set)) {
return $player;
} else {
return NULL;
}
}
So on the form to edit I can get all values like
<input type="text" name="PlayerName" value="<?php echo $sel_player['PlayerName']; ?>" />
But...:) when I try to fill up a combo box with the reverse way I am stuck there. When adding something this works like a charm but $sel_player['PlayerTeam'] is giving me only ID :(
<?php include "conn.php" ?>
<?php include "function.php" ?>
<?php find_selected_player() ?>
<h2>Edit: <?php echo $sel_player['PlayerName'] ." ". $sel_player['PlayerLname']; ?></h2>
<form action="player.php" method="post">
<table>
<tr>
<td>Name: </td>
<td><input type="text" name="PlayerName" value="<?php echo $sel_player['PlayerName']; ?>" /></td>
</tr>
<tr>
<td>Lastname:</td>
<td><input type="text" name="PlayerLname" value="<?php echo $sel_player['PlayerLname']; ?>" /></td>
</tr>
<tr>
<td>Team:</td>
<td>
<?php
$sql = "SELECT TeamName, TeamID FROM tblTeam";
$result = mysql_query($sql);
echo '<select name="TeamName"><option>';
echo "Choose a team.</option>";
echo '<option selected>' . $sel_player['PlayerTeam'] . '</option>';
while ($row = mysql_fetch_array($result)) {
$team_name= $row["TeamName"];
$team_id = $row["TeamID"];
echo "<option value=\"$team_id\">$team_name</option>";
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Save" /></td>
<td align="right"> </td>
</tr>
</table>
</form>
<?php ob_end_flush() ?>
<?php include ("footer.php") ?>
You should update your code to use MySQLi_*, or PDO. I've gotten you started here. Try this out and see how it works for you.
function getPlayerByID($pid = '')
{
global $conn;
if($pid == '')
return false;
$sql = mysql_query("SELECT * FROM tblPlayer WHERE PlayerID = '$pid'", $conn);
$row = mysql_fetch_array($sql);
if(mysql_num_rows($sql) == 1)
return $row;
else
return false;
}
$id = isset($_GET['id']) ? $_GET['id'] : '';
$sel_player = getPlayerByID($id);
$sql = mysql_query("SELECT TeamName, TeamID FROM tblTeam");
$select = '<select name=""><option>Choose a Team</option>';
while($row = mysql_fetch_array($sql))
{
$team_id = $row['TeamID'];
$team_name = $row['TeamName'];
$selected = $team_id == $sel_player['PlayerTeam'] ? 'selected' : '';
$select .= '<option ' . $selected . ' value="' . $team_id . '">' . $team_name . '</option>';
}
$select .= '</select>';
echo $select;
$team_adi should be $team_name
Change:
echo "<option value=\"$team_id\">$team_adi</option>";
to:
echo "<option value=\"$team_id\">$team_name</option>";
<?php
$sql = "SELECT TeamName, TeamID FROM tblTeam";
$result = mysql_query($sql);
$player_id = $_GET['id'];
$current_team = mysql_query("SELECT
tblteam.TeamID,
tblteam.TeamName,
tblplayer.PlayerID,
tblplayer.PlayerTeam,
tblplayer.PlayerName
FROM
tblplayer
INNER JOIN tblteam ON tblplayer.PlayerTeam = tblteam.TeamID
WHERE PlayerID = $player_id LIMIT 1 ");
$my_row = mysql_fetch_array($current_team);
?>
<select name="TeamName">
<option selected value="<?php echo $my_row['TeamID']; ?>"> <?php echo $my_row['TeamName']; ?> </option>
<?php
while ($row = mysql_fetch_array($result)) {
$team_name= $row["TeamName"];
$team_id = $row["TeamID"];
echo "<option value=\"$team_id\">$team_name</option>";
}
echo "</select>";
?>

PHP image upload in admin section only allowing client to upload 19 images

I've been working on a client's admin panel (A photography company uploading images to a client's gallery), when I took on the role as web developer, it only allowed him to upload 30 images, even though there was 100 file upload boxes. This was fixed simply by changing the for loop to run 100 times. This fixed this problem.
But recently, without even touching the code, my client can only upload 19 images.. I haven't changed this form, he has previously uploaded 40+ images, so I don't quite understand what could have happened.. I've checked the code over and over, and can't quite seem to pinpoint the issue. Could this be server side, as I've recently moved from his old developer's host to my hostgator account. Maybe something in the htaccess? I add this because the image label's update, but not the image itself (I can't find it uploaded either, after it has been posted, but my browser shows it uploading)
Here is the edit gallery code itself, if it gives any assistance to the problem:
<?php
require_once("../conn.php");
require_once("access.php");
require_once("GalleryNavigation.php");
require_once("dThumbMaker.inc.php");
/////////////common varilable
$__table = "devbg_gallery";
$__page = $_SERVER['PHP_SELF'];
$__page2 = "AddGallery.php";
$__id = "ItemID";
$__pagetitle = "GALLERY";
$__uploadfolder = "../myimages/";
$__thumbuploadfolder = "../myimages/thumbs/";
$__imageprefix = "Gallery";
$Thumb_Imgwidth = 200;
$Thumb_Imgheight = 77;
/////////////
if(isset($_POST[ds]))
{
if(count($_POST['DelItem']) > '0')
{
while(list(, $value) = each($_POST['DelItem']))
{
$DelInfo = $value;
$r2 = mysql_query("select * from ".$__table." where ".$__id." = '$DelInfo' ") or die(mysql_error());
$a2 = mysql_fetch_array($r2);
for($i=1;$i<=100;$i++)
{
if(file_exists($__uploadfolder.$a2['ItemImage'.$i]))
{
unlink($__uploadfolder.$a2['ItemImage'.$i]);
unlink($__thumbuploadfolder.$a2['ItemImage'.$i]);
}
}
//delete the product
mysql_query("delete from ".$__table." where ".$__id." = '".$DelInfo."' ") or die(mysql_error());
}
}
}
if(isset($_POST[s100]))
{
$MyProductName = mysql_escape_string(trim(stripslashes(strip_tags($_POST[ProductName]))));
$Description = mysql_escape_string(trim(strip_tags(stripslashes($_POST['Description']))));
$Link = trim(strip_tags(stripslashes($_POST['Link'])));
$TopLabel = cleaninput($_POST['TopLabel'],"mres|he|tr");
$status = $_POST['status'];
$NewTopLabelName = $TopLabel;
if(!empty($_FILES['TopImage']['name']))
{
$NewTopImageName = $__imageprefix.$t.$_FILES['TopImage']['name'];
if(is_uploaded_file($_FILES['TopImage']['tmp_name']))
{
move_uploaded_file($_FILES['TopImage']['tmp_name'], $__uploadfolder.$NewTopImageName);
$NewTopImageName = $NewTopImageName;
$NewTopLabelName = $TopLabel;
//lets make the thumb
$tm = new dThumbMaker;
$load = $tm->loadFile($__uploadfolder.$NewTopImageName);
if($load === true)
{ // Note three '='
$tm->cropCenter($Thumb_Imgwidth, $Thumb_Imgheight);
$tm->build($__thumbuploadfolder.$NewTopImageName);
}
else
{
// Error returned.
$error .= "Could not open the file '".$NewTopImageName."'.\n";
$error .= "The error returned was: ";
$error .= $load;
}
}
}
else
{
$NewTopImageName = $_POST['OldTopImage'];
$NewTopLabelName = $NewTopLabelName;
}
for($i=1;$i<=100;$i++) //This is where I believe the problem is --------------------------------------------------------------------
{
${'NewsItemLabel'.$i} = cleaninput($_POST['ItemLabel'.$i],"mres|he|tr");
$ItemLabels .= "ItemLabel".$i ." = '". cleaninput($_POST['ItemLabel'.$i],"mres|he|tr") ."',";
if(!empty($_FILES['ItemImage'.$i]['name']))
{
${'NewImageName'.$i} = $__imageprefix.$t.$_FILES['ItemImage'.$i]['name'];
if(is_uploaded_file($_FILES['ItemImage'.$i]['tmp_name']))
{
move_uploaded_file($_FILES['ItemImage'.$i]['tmp_name'], $__uploadfolder.${'NewImageName'.$i});
//lets make the thumb
$tm = new dThumbMaker;
$load = $tm->loadFile($__uploadfolder.${'NewImageName'.$i});
if($load === true)
{ // Note three '='
$tm->cropCenter($Thumb_Imgwidth, $Thumb_Imgheight);
$tm->build($__thumbuploadfolder.${'NewImageName'.$i});
$ItemImages .= "ItemImage".$i ." = '". ${'NewImageName'.$i} ."',";
}
else
{
// Error returned.
$error .= "Could not open the file '".${'NewImageName'.$i}."'.\n";
$error .= "The error returned was: ";
$error .= $load;
}
} else { }
}
else
{
${'NewImageName'.$i} = $_POST['OldItemImage'.$i];
}
}
if(empty($error))
{
//update the database
$q1 = "update ".$__table." set
ItemName = '".$MyProductName."',
Description = '".$Description."',
Link = '".$Link."',
TopImage = '$NewTopImageName',
Toplabel = '$NewTopLabelName',
".$ItemImages.$ItemLabels."
status = '".$status."'
where ".$__id." = '".$_POST[$__id]."' ";
mysql_query($q1) or die(mysql_error());
echo "<br><br><center>Gallery Updated</center>";
}
}
if(!empty($_GET[$__id]))
{
$_POST[$__id] = $_GET[$__id];
}
if(!empty($_POST[$__id]))
{
//get the product info
$r1 = mysql_query("select * from devbg_gallery where ".$__id." = '".$_POST[$__id]."' ") or die(mysql_error());
$a1 = mysql_fetch_array($r1);
echo $error;
?>
<form method=post action=EditGallery.php enctype="multipart/form-data">
<table align=center width=740>
<caption align=center><b>Gallery Name:</b></caption>
<tr>
<td align='right'>Event Name:</td>
<td><input type=text class=input name="ProductName" value="<?php echo $a1['ItemName'];?>"></td>
</tr>
<TR>
<td align='right'>Description:</td>
<td><textarea name="Description"cols=60 rows=10><?php echo $a1['Description'];?></textarea></td>
</TR>
<?php
if(!empty($a1['TopImage']))
{
$v = $a1['TopImage'];
echo "<tr>";
echo "<td></td><td><img src='".$__uploadfolder.$v."' width='72' border='0'><br><a href='DeleteImage.php?".$__id."=".$a1[$__id]."&Type=gallery&file=".$v."&img=top'>Delete Image</a></td>";
echo "</tr>";
}
?>
<tr>
<td align='right'>Top Image:</td>
<td><input type=file name=TopImage></td>
</tr>
<tr>
<td align='right'>Top Image Label:</td>
<td><input type=text name=TopLabel value="<?php echo $a1['TopLabel'];?>"></td>
</tr>
<?php
for($i = 1; $i <= 100; $i++)
{
if($a1['ItemImage'.$i] != "")
{
echo "<tr>";
echo "<td></td><td><img src='".$__uploadfolder.$a1['ItemImage'.$i]."' width='72' border='0'><br><a href='DeleteImage.php?".$__id."=".$a1[$__id]."&Type=gallery&file=".$a1['ItemImage'.$i]."&id=".$i."'>Delete Image</a></td>";
echo "</tr>";
}
echo "<TR><TD align='right'>Image $i: </TD><TD><input type=file name='ItemImage$i'></TD></TR>\n\t";
echo "<TR><TD align='right'>Label $i: </td><TD><input type=text name='ItemLabel".$i."' value='".cleaninput($a1['ItemLabel'.$i],"ss|hd|tr")."' size='79'></TD></TR>\n\t";
echo "<input type='hidden' name='OldImage$i' value='".$a1['ItemImage'.$i]."'>";
echo "<input type='hidden' name='OldLabel$i' value='".cleaninput($a1['ItemLabel'.$i],"ss|hd|tr")."'>";
}
?>
<tr>
<td></td>
<td>
<input type="hidden" name="OldTopImage" value="<?php echo $a1['TopImage'];?>">
<input type="hidden" name="OldTopLabel" value="<?php echo $a1['TopLabel'];?>">
<input type="hidden" name=<?php echo $__id;?> value="<?php echo $_POST[$__id];?>">
<input type="submit" name="s100" value="Edit Gallery">
</td>
</tr>
</form>
<?php
exit();
}
if(!empty($_GET[Start]))
{
$Start = $_GET[Start];
}
else
{
$Start = '0';
}
$ByPage = "10";
//get the products list
$r1 = mysql_query("select * from devbg_gallery order by ordering_id ASC limit $Start,$ByPage") or die(mysql_error());
if(mysql_num_rows($r1) == '0')
{
echo "<center>You have no items at the database!</center>";
exit();
}
?>
<form method=post>
<table align=center width=500 cellspacing="0" cellpadding="3">
<tr style="background-color:#b5c3ce; color:white; font-family:verdana; font-size:11; font-weight:bold">
<td>Title</td>
<td>User</td>
<td align='center'>Edit</td>
<td align='center'>Delete</td>
</tr>
<?php
$col = "white";
$i=0;
while($a1 = mysql_fetch_array($r1))
{
$r2 = mysql_query("select * from tbl_register where GID = '".$a1['ItemID']."'") or die(mysql_error());
$a2 = mysql_fetch_array($r2);
$name = $a2['firstname'] . " " . $a2['lastname'];
$i++;
if($col == "white" )
{
$col = "#f3f6f8";
}
else
{
$col = "white";
}
echo "<tr bgcolor=$col>
<td>".$a1['ItemName']."</td>
<td>".$name."</td>";
echo "<td align=center><input type=radio name='".$__id."' value='".$a1[$__id]."'></td>
<td align='center'><input type='checkbox' name='DelItem[]' value='".$a1[$__id]."'></td>
</tr>\n\n";
}
echo "<tr>
<td colspan=4 align=right><br>\n\t<input class=input type=submit name=ds value='Edit Selected'> <input type='submit' class='input' name='ds' value='Delete Selected'></td>
</tr>
</table>
</form>\n\n";
//build the "next" - "prev" navigatioin
$qnav = "select * from ".$__table." order by ItemName ";
$rnav = mysql_query($qnav) or die(mysql_error());
$rows = mysql_num_rows($rnav);
echo "<br><table align=center width=600>";
echo "<td align=center><font face=verdana size=2> | ";
$pages = ceil($rows/$ByPage);
for($i = 0; $i <= ($pages); $i++)
{
$PageStart = $ByPage*$i;
$i2 = $i + 1;
if($PageStart == $Start)
{
$links[] = " <span class=bodybold>$i2</span>\n\t ";
}
elseif($PageStart < $rows)
{
$links[] = " <a class=bodybold href=EditGallery.php?Start=$PageStart>$i2</a>\n\t ";
}
}
$links2 = implode(" | ", $links);
echo $links2;
echo "| </td>";
echo "</table><br>\n";
?>
<?php include("footer.php");?>
If there's any other information I could provide that would help find a solution, I can post it straight up. This problem has really messed with my head, and my client needs his gallery running! Makes me wish I could have coded this myself and got there before his previous developer. Thanks everybody!
A friend of mine figured out that when I moved host, my max_file_uploads setting in my php.ini was set to 20, and that the code you see above loops each image and tries to upload it, even if there is no image, which explains why even if I only tried to upload 1 by itself, it wouldn't upload any after 19. Just a simple setting overlooked.
Changed this to max_file_uploads = 100 in my ini, everything works fine now, client happy!

Categories