Here my aim to update a book's information with title which I set in the textbox. But in my code I when I run I'm getting the error as $query2 is undefined in $query2['status']=="Available". Can anyone rectify my error?
<?php
$user="root";
$server="localhost";
$password="";
$db="library book";
$query=mysql_connect($server,$user,$password);
$dbRes = mysql_select_db($db,$query);
if(isset($_GET['book_id']))
{
$bookid = $_GET['book_id'];
$str="select * from books where bookid=$bookid";
$query1=mysql_query($str);
//echo $query1;
$query2=mysql_fetch_array($query1);
//print_r ($query2);
}
if(isset($_POST['Update']))
{
$title=mysql_real_escape_string($_POST['title']);
$author=mysql_real_escape_string($_POST['author']);
$publisher=mysql_real_escape_string($_POST['publisher']);
$numcopies=mysql_real_escape_string($_POST['numcopies']);
$shelfno=mysql_real_escape_string($_POST['shelfno']);
$status=mysql_real_escape_string($_POST['status']);
$str1="update books set title=$title where bookid=$bookid";
$query3=mysql_query($str1);
echo $query3;
$query4=mysql_query("select * from books");
$row=mysql_fetch_array($query3);
echo "<table>";
echo "<tr><th>BookID</th><th>Title</th><th>Author</th><th>Publisher</th><th>numcopies</th><th>shelfno</th><th>status</th><th>Action</th></tr>";
echo "<tr>";
echo "<td>".$row['bookid']."</td>";
echo "<td>".$row['title']."</td>";
echo "<td>".$row['author']."</td>";
echo "<td>".$row['publisher']."</td>";
echo "<td>".$row['numcopies']."</td>";
echo "<td>".$row['shelfno']."</td>";
echo "<td>".$row['status']."</td>";
echo "</tr>";
echo "</table>";
if ($query2['status']=="Available")
echo "selected";
if ($query2['status']=="Unavailable")
echo "selected";
}
?>
<html>
<head><title>Editing the fields</title>
<style>
body {
background-color: rgb(255,0,255);
}
</style>
</head>
<body>
<form action="edit1.php" action="post">
EnterTitle:<input type="text" name="title" value="<?php echo $query2['title'];?>">
<br/>
EnterAuthor:<input type="text" name="author" value="<?php echo $query2['author'];?>" >
<br/>
EnterPublisher:<input type="text" name="publisher" value="<?php echo $query2['publisher'];?>">
<br/>
EnterNumCopies:<input type="text" name="numcopies" value="<?php echo $query2['numcopies'];?>">
<br/>
EnterShelfNo:<input type="text" name="shelfno" value="<?php echo $query2['shelfno'];?>">
<br/>
<input type="hidden" name="bookid" value=<?php if(isset($bookid)) echo $bookid; ?>>
<select>
<option value="available" <?php if ($query2['status']=="Available") echo "selected";?>>Available</option>
<option value="unavailable" <?php if ($query2['status']=="Unavailable") echo "selected";?>>Unavailable</option>
</select>
<br>
<input type="submit" name="submit" value="Update">
</form>
</body>
</html>
I think unfortunately, what you have going on here is the beginnings of a "spaghetti code" syndrome so you will want to invest in learning a PHP framework. You will have less chance of security issues, your script will be cleaner from the get-go, more-easily maintained, etc.
For this particular snippet, among other things, you have sql injection issues, you set bookid by $_GET and $_POST but it's hard to determine which is best to use, you have html happening above the <html> tag, but the main problem you are experiencing is that you have variables that are defined in an if scope but are also referenced outside of that if scope so will create the error(s) when the if condition is not satisfied (See this example for more reference).
Some suggestions besides fixing the scope issue:
Use PDO or mysqli_ with parameter binding. My example uses PDO
Use functions or class/method for both usability and readability in your final layout (it looks more complex as I have it below, but only because it's all pasted on one page. Each page should be separate). All of this $query, $query1, $query2, etc. gets confusing. I have used functions, but a class would have been better to pass bookid to all the methods internally.
Standardize your book id key name, either make it book_id or bookid, not both. My example uses bookid.
There are probably some flaws in this, but hopefully it gives you some useful ideas and as I said before, this would be more useful implemented as a class (a few classes actually) but using functions might be a good start to help clean your scripting up.
IMPORTANT NOTE: I have not tested this (there should be no syntax errors though) but you should be able to get the idea about what is happening and what things are for by paralleling your version to this one. If you don't understand it, read up on it first, don't blindly copy and paste or you will get into more trouble. Use at your own risk, as they say.
/functions/getBooks.php
# Create a general function to fetch all books.
function getBooks($con)
{
$result = array();
$query = $con->prepare("SELECT * FROM books");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return $result;
}
/functions/getBookById.php
# Create a function to fetch a specific book by id
function getBookById($id,$con)
{
$query = $con->prepare("SELECT * FROM books WHERE bookid = :id");
$query->execute(array(":id"=>$id));
$row = $query->fetch(PDO::FETCH_ASSOC);
return (!empty($row))? $row : array();
}
/functions/getBook.php
# This should fetch from a global request, that way you can tell if
# a book is currently being accessed
function getBook($con)
{
autoload(array('getBookById','getId'));
$id = getId('req');
if(empty($id))
return false;
return getBookById($id,$con);
}
/functions/updateBookById.php
# Create an update function that can be accessed at anytime. Use binding
# so you don't need to mess with any sort of escaping
function updateBookById($id,$values,$con)
{
foreach($values as $keys => $vals) {
$bKey = ":{$keys}";
$bind[$bKey] = $vals;
$sql[] = '`'.$key.'` = '.$bKey;
}
$bind[":id"] = $id;
$query = $con->prepare("UPDATE books SET ".implode(', ',$sql)." WHERE bookid = :id");
$query->execute($bind);
}
/functions/updateBookTitle.php
# This is is just a specific function to focus on title. Not sure you need
# it since the update book by id function would do the same thing
function updateBookTitle($id,$title,$con)
{
$bind[":id"] = $id;
$bind[":title"] = $title;
$query = $con->prepare("UPDATE books SET title = :title WHERE bookid = :id");
$query->execute($bind);
}
/functions/getId.php
# This will fetch the id value from a global
function getId($type = false)
{
switch($type) {
case('post'):
return (isset($_POST['bookid']))? $_POST['bookid'] : false;
case('req'):
return (isset($_REQUEST['bookid']))? $_REQUEST['bookid'] : false;
default:
return (isset($_GET['bookid']))? $_GET['bookid'] : false;
}
}
/functions/bookObserver.php
# This will sit and just wait for the right globals activate it
function bookObserver($con,&$curr)
{
autoload('getId');
if(getId('req')) {
autoload('getBookById');
$books = getBookById(getId('req'),$con);
if(!empty($books))
$curr = $books;
if(isset($_POST['Update'])) {
$values = array(
'title' => $_POST['title'],
'author' => $_POST['author'],
'publisher' => $_POST['publisher'],
'numcopies' => $_POST['numcopies'],
'shelfno' => $_POST['shelfno'],
'status' => $_POST['status']
);
autoload('updateBookById');
updateBookById(getId('req'),$values,$con);
}
}
}
/functions/bookListObserver.php
# This sits and waits for the update to write the table to the page
function bookListObserver($current,$con)
{
if(isset($_POST['Update'])) {
autoload('bookList');
echo bookList(((!empty($current['status']))? $current['status'] : false),$con);
}
}
/functions/getValue.php
# This will just check if a value is set. Saves on scripting
function getValue($array,$key,$def = false)
{
return (!empty($array[$key]))? $array[$key] : $def;
}
/functions/bookList.php
# Displays your book list. Currently you are only showing the last book,
# which doesn't appear correct. No point in getting all books but only showing
# the last one
function bookList($selected = false,$con)
{
autoload('getBooks');
$books = getBooks($con);
ob_start();
?>
<table>
<tr>
<th>BookID</th>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>numcopies</th>
<th>shelfno</th>
<th>status</th>
<th>Action</th>
</tr>
<?php foreach($books as $row) { ?>
<tr>
<td><?php echo $row['title'] ?></td>
<td><?php echo $row['author'] ?></td>
<td><?php echo $row['publisher'] ?></td>
<td><?php echo $row['numcopies'] ?></td>
<td><?php echo $row['shelfno'] ?></td>
<td><?php echo $row['status'] ?></td>
</tr>
<?php } ?>
</table>
<?php
if($selected == "Available")
echo "selected";
elseif($selected == "Unavailable")
echo "selected";
$data = ob_get_contents();
ob_end_clean();
return $data;
}
/functions/connect.php
# This is your mysql connection, it requires attention to build out
# It's not as useful as it could be, so you will want to research it
function connect()
{
return new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,DB_PASS);
}
/functions/autoload.php
# This is just a handy function to autoload functions when you want
# to use them. If you used classes, you would make an spl_autoload_register()
# function or install something like Composer to autoload
function autoload($name,$run = false)
{
if(is_array($name)) {
foreach($name as $func) {
autoload($func);
}
return;
}
if(!function_exists($name)) {
if(is_file($file = FUNCTIONS.DS.$name.'.php'))
include_once($file);
}
if($run) {
if(function_exists($name))
return $name();
}
}
/config.php
# Make sure errors are on in testing
ini_set('display_errors',1);
error_reporting(E_ALL);
# Creating commonly-used defines will help your scripts be
# more reliable and consistent
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
define('DB_HOST','localhost');
define('DB_NAME','library book');
define('DB_USER','root');
define('DB_PASS','');
# Start session by default
session_start();
require_once(FUNCTIONS.DS.'autoload.php');
# Autoload the connect function and assign it
$con = autoload('connect',true);
/index.php
<?php
# Add config
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Include all our starting page functions
autoload(array('bookObserver','bookListObserver','getBook', 'getValue'));
# Set default array for current selection
$current = array();
# Start observer, pass connection
bookObserver($con,$current);
?>
<html>
<head><title>Editing the fields</title>
<style>
body {
background-color: rgb(255,0,255);
}
</style>
</head>
<body>
<?php
# This writes the table if update is set
# You should not put this html above the <html> tag
bookListObserver($current,$con);
# This gets the book from the page request
$book = getBook($con);
?>
<form action="edit1.php" action="post">
EnterTitle:<input type="text" name="title" value="<?php echo getValue($book,'title') ?>"><br/>
EnterAuthor:<input type="text" name="author" value="<?php echo getValue($book,'author') ?>" ><br/>
EnterPublisher:<input type="text" name="publisher" value="<?php echo getValue($book,'publisher') ?>"><br/>
EnterNumCopies:<input type="text" name="numcopies" value="<?php echo getValue($book,'numcopies') ?>"><br/>
EnterShelfNo:<input type="text" name="shelfno" value="<?php echo getValue($book,'shelfno') ?>"><br/>
<input type="hidden" name="bookid" value="<?php echo getValue($book,'bookid') ?>" />
<select>
<option value="available" <?php if(isset($current['status']) && $current['status'] == "Available") echo "selected";?>>Available</option>
<option value="unavailable" <?php if (isset($current['status']) && $current['status'] == "Unavailable") echo "selected";?>>Unavailable</option>
</select><br>
<input type="submit" name="submit" value="Update">
</form>
</body>
</html>
Related
I have a table named positions. This table has the list of the different positions that the admin has added in the listOfPositions.php like President, Vice-President, etc. After adding different positions, he can now add the different people under that position. And that's where my problem is. How will I have an auto increment input name for the names of the people depending on how many positions it has in the table positions ?
I tried using javascript, but it increments only in the html and not reflecting to the php when I try to save. My current code where the adding of the names of different persons depending on the position is the ff:
<script type="text/javascript" src="http://code.jquery.com/jquery-git.js"></script>
<form action="post_officers.php" method="post"><br>
<center><select name="year">
<?php
for($i=date('Y'); $i>1999; $i=$i-2) {
$selected = '';
$year2 = $i-2;
if ($year == $i) $selected = ' selected="selected"';
echo ('<option value="'.$year2. "-" . $i .'" '.$selected.'> '.$year2.'-'.$i.'</option>'."\n");
}
?>
</select></center>
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name" /></td>
</tr>
</table>
<?php
}
?>
<input type="submit" name="submit" value="SAVE"/>
</form>
<script>
$("input[name='file']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='position']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='name']").each(function(ind) {
$(this).attr(ind + 1);
});
</script>
And this is my php code:
<?php
include ('dbcontroller.php');
date_default_timezone_set('Asia/Manila');
$year = mysqli_real_escape_string($conn,$_POST['year']);
if(isset($_POST['submit'])) {
$result = mysqli_query($conn,"SELECT * FROM officers WHERE year = '$year'");
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
echo "<script type='text/javascript'>alert('Year already exists.'); window.location.href='create_alumni_officers.php';</script>";
}
else {
for ($i = 1; $i <= 8; $i++) {
$name = mysqli_real_escape_string($conn,$_POST['name'.$i]);
$position = mysqli_real_escape_string($conn,$_POST['position'.$i]);
$file=(rand(1000,100000)."-".$_FILES['file'.$i]['name']);
$type=($_FILES['file'.$i]['type']);
$size=$_FILES['file'.$i]['size'];
$loc=($_FILES['file'.$i]['tmp_name']);
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
}
}
?>
And this doesn't work at all. Any help? I hope you guys understood what I'm trying to ask.
This is the best way to do it:
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<table id="options-table">
<tr>
<td><input type="file" name="file[<?php echo $position; ?>]" /></td>
<td><input type="hidden" name="position[<?php echo $position; ?>]" value="<?php echo $position; ?>" /><?php echo $position; ?></td>
<td><input type="text" name="name[<?php echo $position; ?>]" /></td>
</tr>
</table>
<?php
}
?>
You don't need the javascript to change input attributes. Remove it.
In php use foreach loop like:
If you are still getting errors I will need to see the output of print_r($_POST);
<?php
$files = $_FILES['file'];
$positions = $_POST['position']; //use this for the foreach loop because it will always have a value
$names = $_POST['name'];
foreach($positions as $key=>$position){
$file = #$files[$key];
$name= #$names[$key];
//Do your magic for each user here
$name = mysqli_real_escape_string($conn,$name);
$position = mysqli_real_escape_string($conn,$position);
$filename = rand(1000,100000)."-".$file['name'];
$type = $file['type'];
$size = $file['size'];
$loc = $file['tmp_name'];
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($filename);
// make file name in lower case
$final_file = str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
?>
As I indicated in the contents, removing context switches miss fide will greatly increase the readability of your code. I'll illustrate below a bit as well as answer the question.
To get what you're after, you could do this:
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name<?php echo $position; ?>" /></td>
</tr>
</table>
<?php
}
However, to illustrate a small example of removing these contextual switches mid code, see below and pardon but this is air code, if you want a more specific example, just ask.
Let's say you often use the tag thoughout your site in forms. You could drop out of php each time and just write out the straight html. Or, you could create a class, or even a simple function for the html output thusly:
Function opt($int, $parms = '') {
Return '<Option '.$parms.'>'. $int.'</option>';
}
Now your code would look more like this:
While ($r =mysqli_fetch_array ($result)) {
Extract ($r); // learn this, no sense assigning them 1 by 1
$options .= opt($databaseobject, 'name="foo" value="'. $databaseobjectid.'"');
}
Echo $options;
I'm sorry for such a basic question but I'm a bit stumped. I've been trying to build a basic website for a database I created that will graph the data. There are two variable lists that the user selects from and the data from this then is supposed to generate the requested information. However, I'm completely lost as to how to get the data selected from the list to appear in the results page. It will search under the 'country' variable, but not goods. I know that I'm probably doing something stupid, but I'm not sure what it is.
The code I'm using for the dropdown menus on the forms is as follows:
<form id="Country" name="Country" method="get" form action="/database/results_page.php"><table border="1">
<tr>
<td width="68">Name</td>
<td width="48"><span id="sprytextfield4">
<select name="selcountry" id="selcountry" title="<?php echo $row_rsCountrydropdown['']; ?>">
<?php
do {
?>
<option value="<?php echo $row_rsCountrydropdown['country']?>" <?php if($varcountry_rsexportsearch == $row_rsCountrydropdown['country']){echo 'selected';}?>><?php echo $row_rsCountrydropdown['country']?></option>
<?php
} while ($row_rsCountrydropdown = mysql_fetch_assoc($rsCountrydropdown));
$rows = mysql_num_rows($rsCountrydropdown);
if($rows > 0) {
mysql_data_seek($rsCountrydropdown, 0);
$row_rsCountrydropdown = mysql_fetch_assoc($rsCountrydropdown);
}
?>
</select>
<select name="selgoods" id="selgoods" title="<?php echo $row_rsGoodsdropdown['']; ?>">
<?php
do {
?>
<option value="<?php echo $row_rsGoodsdropdown['name']?>" <?php if($vargoods_rsexportsearch == $row_rsGoodsdropdown['name']){echo 'selected';}?>><?php echo $row_rsGoodsdropdown['name']?></option>
<?php
} while ($row_rsGoodsdropdown = mysql_fetch_assoc($rsGoodsdropdown));
$rows = mysql_num_rows($rsGoodsdropdown);
if($rows > 0) {
mysql_data_seek($rsGoodsdropdown, 0);
$row_rsGoodsdropdown = mysql_fetch_assoc($rsGoodsdropdown);
}
?>
</select>
</tr>
</table>
<input type="submit" name="submit" id="submit" value="Submit" onChange="row_rsCountrydropdown.submit()" />
</form>
and my SQL for the results page is as follows:
mysql_select_db($database_cork_normalised, $cork_normalised);
$query_query = "SELECT exports.trade_year, country_id.country, goods.name, exports.Cork FROM country_id, goods, exports WHERE country_id.country_id='varcountry' and goods.goods_id='vargoods'";
$query = mysql_query($query_query, $cork_normalised) or die(mysql_error());
$row_query = mysql_fetch_assoc($query);
$maxRows_query = 10;
$pageNum_query = 0;
if (isset($_GET['pageNum_query'])) {
$pageNum_query = $_GET['pageNum_query'];
}
$startRow_query = $pageNum_query * $maxRows_query;
$vargoods_query = "-1";
if (isset($_POST['selgoods'])) {
$vargoods_query = $_POST['selgoods'];
}
$varcountry_query = "-1";
if (isset($_POST['selcountry'])) {
$varcountry_query = $_POST['selcountry'];
}
If anyone could help I'd be really grateful, this is my first foray into PHP and I'm a bit lost in it.
I am writing a basic CMS system and have come across something which should be seemingly simple -but is beginning to frustrate me.!
I am trying to pass an array through a select option field to populate a list of categories in which I can save a post.
I have a 'posts' form which comprises of 3 fields. Title, content and Category ID (CatID).
When the user creates a post, they can select the category they wish to assign the post assigned to by using a drop down list - (this is populated by using a different form).
So the technical bit; -
MySQL DB:-
categories = catname (char60 PRIMARY), catid (INT10, AI)
posts = id (bigint20 PRIMARY), catid (int10 PRIMARY), title (text), content (varchar255)
Example of categories populates: catname = Home / catid = 1 ...etc
Output.php ;
<?php
function display_post_form($post = '') {
$edit = is_array($post);
?>
<form action="<?php echo $edit ? 'edit.php' : 'add.php' ; ?>" method="post">
<table border="0">
<tr>
<td> Title:</td>
<td> <input type="text" name="title" value="<?php echo $edit ? $post['title'] : '' ; ?>" size="60" /> </td>
</tr><tr>
<td> Content:</td>
<td> <textarea id="editor1" name="content" value="<?php echo $edit ? $post['content'] : '' ; ?>"> </textarea> </td>
</tr><tr>
<td> Category:</td>
<td><select name="catid">
<?php
$cat_array = get_categories($catid, $catname);
foreach($cat_array as $thiscat) {
echo "<option value=\"".$thiscat['catid']."\" ";
if (($edit) && ($thiscat['catid'] == $post['catid'])) {
echo " selected";
}
echo ">".$thiscat['catname']."</option>";
}
?>
</select>
</td>
</tr><tr>
<td> Button:</td>
<td <?php if (!$edit) { echo "colspan=2"; } ?> align="center">
<?php
if ($edit)
echo "<input type=\"hidden\" name=\"_id\" value=\"". $post['id'] ."\" />";
?>
<input type="submit" value="<?php echo $edit ? 'Update' : 'Add' ; ?> Post" />
</form></td>
</td>
</tr>
</table>
</form>
<?php
}
?>
Functions.php ;
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
while($row = mysqli_fetch_assoc($result)) {
printf("\n %s %s |\n",$row["catname"],$row["catid"]);
}
mysqli_close($conn);
}
I am able to call in the 'get_cattegories()' function which generates a flat data of categories and their respective id's. I then combined this with the Select Option Field in the Output.php file and it doesn't generate anything.
Can anyone give some useful tips or advice? Many thanks :)
You are not returning the array but printing a string to the output. Change printf to return:
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
$categories = array();
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}
mysqli_close($conn);
return $categories;
}
Also I agree for the comments to your question. The arguments are useless.
You also may refactor the code, actually... alot. Move the mysql_connect() to the other place, probably at the beginning of your script.
I suggest to use some frameworks. I think KohanaPHP will be a good start. You will learn about architecture and some design patterns. Keep the good work and improve your skills ;-)
i am very novice to php and mysqli and found a great tutorial but am needing some help.
i am wanting a row to be linkable and send it to another page named single.php?id=ROWID so it will show the single entry
this is what i got so far.
<html>
<head>
<title>MySQLi Tutorial</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
$action = isset($_GET['action']) ? $_GET['action'] : "";
if($action=='delete'){ //if the user clicked ok, run our delete query
$query = "DELETE FROM users WHERE id = ".$mysqli->real_escape_string($_GET['id'])."";
if( $mysqli->query($query) ){
echo "User was deleted.";
}else{
echo "Database Error: Unable to delete record.";
}
}
$query = "select * from users";
$result = $mysqli->query( $query );
$num_results = $result->num_rows;
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results ){
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th><a href=\"single.php?id={$id}\">Firstname</></th>";
echo "<th>Lastname</th>";
echo "<th>Username</th>";
echo "<th>Action</th>";
echo "</tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$firstname}</td>";
echo "<td>{$lastname}</td>";
echo "<td>{$username}</td>";
echo "<td>";
echo "<a href='edit.php?id={$id}'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
//if table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
<script type='text/javascript'>
function delete_user( id ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'index.php?action=delete&id=' + id;
}
}
</script>
</body>
</html>
i am right in thinking i would be sending the rows id in the url ?
echo "<th><a href=\"single.php?id={$id}\">Firstname</></th>";
but i am having issues with single.php what code would i have to put to show the single entry?
i have been on this a while and got no were near so i deleted the code and swallowed my pride to seek some help :/
thanks in advance
Thank you for the interesting question.
First, let me inform you that, although you are using a moder-looking database access library, the way you are using it is as ancient as a mammoth fossil.
Several things to consider
Never use mysqli as is, but only in the form of some higher level abstraction library.
Never use real_escape_string in the application code but use prepared statements only.
Never mix your database code with HTML output. Get your data first, then start for output.
Never use GET method to modify the data.
Here goes the example based on the above principles. It does ALL basic CRUD operations:
<?
include 'safemysql.class.php'; // a library
$db = new SafeMysql();
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') {
if (isset($_POST['delete'])) {
$db->query("DELETE FROM ?n WHERE id=?i",$table,$_POST['delete']);
} elseif ($_POST['id']) {
$db->query("UPDATE ?n SET name=?s WHERE id=?i",$table,$_POST['name'],$_POST['id']);
} else {
$db->query("INSERT INTO ?n SET name=?s",$table,$_POST['name']);
}
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) {
$LIST = $db->getAll("SELECT * FROM ?n",$table);
include 'list.php';
} else {
if ($_GET['id']) {
$row = $db->getRow("SELECT * FROM ?n WHERE id=?i", $table, $_GET['id']);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
It is using templates to display the data:
list.php
Add item
<? foreach ($LIST as $row): ?>
<li><?=$row['name']?>
<? endforeach ?>
and form.php
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
Return to the list
</form>
<? if ($row['id']):?>
<div align=right>
<form method="POST">
<input type="hidden" name="delete" value="<?=$row['id']?>">
<input type="submit" value="Удалить"><br>
</form>
</div>
<?endif?>
here goes the part for display.
if ($_GET['id']) {
$row = $db->getRow("SELECT * FROM ?n WHERE id=?i", $table, $_GET['id']);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
if you don't want to show the form - create another template called single.php with whatever markup you wish
Single.php
I Use PDO if u want you can make it with MySQLi too.
<?php
include("db_connect.php"); // database configuration file
if(isset($_GET['id'])
{
$id = (int) $_GET['id'];
$sql = "SELECT * FROM `users` WHERE id=?";
$query = $conn->prepare($sql); // $conn is PDO object yours can be different
$query->bindValue(1,$id);
$query->execute();
if($query){
$row = $query->fetch(); //
}else{
echo "Error with Database";
}
}
else // Error for the Id selection
{
echo("ID is not selected");
}
?>
No while loop because you want just 1 record. $row variable is just for test because i don't know your fields in your DB
<table border="1">
<tr>
<td>ID</td>
<td>Firstname</td>
<td>Lastname</td>
</tr>
<tr>
<td><?php echo $row['id]; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['lastname']; ?></td>
</tr>
</table>
in your single.php
$id=$_GET['id'];
$query="select * from users where id='".$id."'";
I have a table that prints out all available cameras. It uses a form to change these settings. The problem is that the form only updates the last camera in the entry. In other words if I change the form and hit "Apply" for the last camera in the list it will work. If I change the form for any other camera in this list it changes the one to have the same settings as the last camera in the list. There are no issues with any values as far as I can tell.
Sorry for the long dump here, but without being able to narrow down the problem I thought I should include the bulk of it:
// Dont allow direct linking
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
//get current user
$user =& JFactory::getUser();
// get a reference to the database
$db = &JFactory::getDBO();
$query_camera_name = "SELECT camera_id, camera_name, camera_status, camera_quality, camera_hash, camera_type FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
if (isset($_POST['apply_changes'])) {
//process changes to camera options
$camera_id = $_POST['camera_id'];
$camera_status = check_input($_POST['camera_status']);
$camera_name = check_input($_POST['camera_name'], "You entered an empty camera name. Enter another name and apply changes.");
$camera_quality = check_input($_POST['camera_quality']);
$query_insert_camera = 'UPDATE `#__cameras` SET `camera_status` ="'.$camera_status.'", `camera_name` ="'.$camera_name.'", `camera_quality` ="'.$camera_quality.'" WHERE `camera_id`='.$camera_id;
$db->setQuery($query_insert_camera);
$db->query();
header("location: " . $_SERVER['REQUEST_URI']);
}
echo "<html>";
echo "<head>";
<link href="dashboard/webcam_widget.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function oncameraSubmit(camera_id)
{
document.active_cameras.camera_id.value = camera_id;
return confirm('Apply changes?');
}
</script>
<?php
echo "</head>";
echo "<body>";
if (!isset($result_cameras))
{
//TODO
}
else
{
if ($num_rows == 0)
{
echo '<b><i><center>You currently have no cameras setup. Add a Camera below.</center></i></b>';
}
else
{
?>
<form name="active_cameras" action="<?php htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="hidden" name="camera_id" value="" />
<table id="webcam-table">
<thead>
<tr>
<th>Camera Type</th>
<th>Name</th>
<th>Quality</th>
<th>Status</th>
<th>Camera Actions</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_rows;$i++)
{
//camera_status
if ($result_cameras[$i]["camera_status"] == "ENABLED")
{
$enabled_option = "value='ENABLED' selected='selected'";
$disabled_option = "value='DISABLED'";
}
else
{
$enabled_option = "value='ENABLED'";
$disabled_option = "value='DISABLED' selected='selected'";
}
//camera_quality
if ($result_cameras[$i]["camera_quality"] == "HIGH")
{
$high_option = "value='HIGH' selected='selected'";
$medium_option = "value='MEDIUM'";
$mobile_option = "value='MOBILE'";
}
else if ($result_cameras[$i]["camera_quality"] == "MEDIUM")
{
$high_option = "value='HIGH'";
$medium_option = "value='MEDIUM' selected='selected'";
$mobile_option = "value='MOBILE'";
}
else if ($result_cameras[$i]["camera_quality"] == "MOBILE")
{
$high_option = "value='HIGH'";
$medium_option = "value='MEDIUM'";
$mobile_option = "value='MOBILE' selected='selected'";
}
else
{
//TODO proper logging
}
//camera_type
if ($result_cameras[$i]["camera_type"] == "WEBCAM")
{
$webcam = "value='WEBCAM' selected='selected'";
$axis = "value='AXIS'";
$other = "value='IPCAM'";
}
else if ($result_cameras[$i]["camera_type"] == "AXIS")
{
$webcam = "value='WEBCAM'";
$axis = "value='AXIS' selected='selected'";
$other = "value='IPCAM'";
}
else if ($result_cameras[$i]["camera_type"] == "IPCAM")
{
$webcam = "value='WEBCAM'";
$axis = "value='AXIS'";
$other = "value='IPCAM' selected='selected'";
}
else
{
//TODO
}
?>
<tr>
<td>
<select name="camera_type">
<option <?php echo $webcam; ?>>Webcam</option>
<option <?php echo $axis; ?>>AXIS</option>
<option <?php echo $other; ?>>Other</option>
</select>
</td>
<td>
<input type="text" size="32" maxlength="64" name="camera_name" value="<?php echo $result_cameras[$i]["camera_name"]; ?>" />
</td>
<td>
<select name="camera_quality">
<option <?php echo $high_option; ?>>High</option>
<option <?php echo $medium_option; ?>>Medium</option>
<option <?php echo $mobile_option; ?>>Mobile</option>
</select>
</td>
<td>
<select name="camera_status">
<option <?php echo $enabled_option; ?>>Enabled</option>
<option <?php echo $disabled_option; ?>>Disabled</option>
</select>
</td>
<td>
<input type="submit" name="apply_changes" value="Apply" onClick="javascript:return oncameraSubmit(<?php echo $result_cameras[$i]["camera_id"]; ?>);"/>
</td>
</tr>
<?php
}
echo "</tbody>";
echo "</table>";
echo "</form>";
}
}
It looks like you have multiple HTML elements with the same name. As such, you want to get back an array of values when the form is posted.
As such, Get $_POST from multiple checkboxes looks like it might be helpful.
Alternatively, extend oncameraSubmit so that it stores all the data in a hidden input field (not just the id). Then when you update the database, use these hidden fields.
Your form element names are clashing. When you define a form element e.g. 'camera_status' twice, you will only receive the last value in the POST.
Use form array notation, e.g.: "camera_status[]" or even better "camera_status[$id]". Then your PHP code will recieve arrays as POST data and you will be able to update everything at once.