editing mysql table with html form - php

My aim is to have a simple, form based CMS so the client can log in and edit the MySQL table data via an html form. The login is working, but the edit page isn't returning the values from the MySQL table, nor am I getting any errors.
I'm still amateur, and I first started the following code for a class project, but now plan to implement it for a live site. From what I understand I shouldn't have to declare the next/previous/etc. variables at the top, which I tried unsuccessfully to do so anyway. Does anything stand out to any of you?:
<?php
echo "<h2>Edit Special Offer</h2><hr>";
if (isset($_COOKIE["username"]))
{
echo "Welcome " . $_COOKIE["username"] . "!<br />";
include "login.php";
}
else
echo "You need to log in to access this page.<br />";
if(isset($previous))
{
$query = "SELECT id, specialtitle, specialinfo
FROM special WHERE id < $id ORDER BY id DESC";
$result = mysql_query($query);
check_mysql();
$row = mysql_fetch_row($result);
check_mysql();
if ($row[0] > 0)
{
$id = $row[0];
$specialtitle = $row[1];
$specialinfo = $row[2];
}
}
elseif (isset($next))
{
$query = "SELECT id, specialtitle, specialinfo
FROM special WHERE id > $id ORDER BY id ASC";
$result = mysql_query($query);
check_mysql();
$row = mysql_fetch_row($result);
check_mysql();
if ($row[0] > 0)
{
$id = $row[0];
$specialtitle = $row[1];
$specialinfo = $row[2];
}
}
elseif (isset($add))
{
$query = "INSERT INTO special (specialtitle, specialinfo)
VALUES ('$specialtitle', '$specialinfo')";
$result = mysql_query($query);
check_mysql();
$id = mysql_insert_id();
$message = "Special Offer Added";
}
elseif (isset($update))
{
$query = "UPDATE special
SET specialtitle='$specialtitle', specialinfo='$specialinfo'
WHERE id = $id";
$result = mysql_query($query);
check_mysql();
$id = mysql_insert_id();
$message = "Monthly Special Updated";
}
elseif (isset($delete))
{
$query = "DELETE FROM special WHERE id = $id";
$result = mysql_query($query);
check_mysql();
$specialtitle = "";
$specialinfo = "";
$message = "Special Offer Deleted";
}
$specialtitle = trim($specialtitle);
$specialinfo = trim($specialinfo);
?>
<form method="post" action="editspecial.php">
<p><b>Special Offer</b>
<br><input type="text" name="specialtitle" <?php echo "VALUE=\"$specialtitle\"" ?>> </p>
<p><b>Special Info/Description</b>
<br><textarea name="specialinfo" rows="8" cols="70" >
<?php echo $specialinfo ?>
</textarea> </p>
<br>
<input type="submit" name="previous" value="previous">
<input type="submit" name="next" value="next">
<br><br>
<input type="submit" name="add" value="Add">
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
<input type="hidden" name="id" <?php echo "VALUE=\"$id\"" ?>>
</form>
<?php
if (isset($message))
{
echo "<br>$message";
}
?>
Login.php:
<?php
function check_mysql()
{
if(mysql_errno()>0)
{
die ("<br>" . mysql_errno().": ".mysql_error()."<br>");
}
}
$dbh=mysql_connect ("xxxxxxxxxxxxxxxxx","xxxxxxxx","xxxxxxxx");
if (!$dbh)
{
die ("Failed to open the Database");
}
mysql_select_db("xxxxxx");
check_mysql();
if(!isset($id))
{
$id=0;
}
?>

Please please please do a little bit more learning before attempting to build this thing.
You can do it the way you are doing it, but with just a small amount of extra knowledge about OO programming, and maybe about the Pear db classes you will have 3x cleaner code.
If you really choose not to, at the very least, pull each of your save, update, delete, etc procedures out into functions instead of just inlining them in your code. put them in a separate file, and include it in that page.
It may not be useful to you, but I am going to dump a generic table access class here in the page for you. It requires a simple db class API, but if you use this or something like it your life will be 5x easier.
If you don't understand this code when you look at it, that's ok, but please just come back and ask questions about the stuff you don't understand. That is what stackoverflow is for.
This is an older class that should just do basic stuff. Sorry it's not better I just wanted to dig something out of the archives for you that was simple.
<?php
// Subclass this class and implement the abstract functions to give access to your table
class ActiveRecordOrder
{
function ActiveRecordOrder()
{
}
//Abstract function should return the table column names excluding PK
function getDataFields()
{}
//Abstract function should return the primary key column (usually an int)
function getKeyField()
{}
//abstract function just return the table name from the DB table
function getTableName()
{}
/*
This function takes an array of fieldName indexed values, and loads only the
ones specified by the object as valid dataFields.
*/
function loadRecordWithDataFields($dataRecord)
{
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
foreach($dataFields as $fieldName)
{
$this->$fieldName = $dataRecord[$fieldName];
}
}
function getRecordsByKey($keyID, &$dbHandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
$results = $dbHandle->select($tableName, $dataFields, array($keyField => $keyID));
return $results;
}
function search($whereArray, &$dbHandle)
{
$tableName = $this->getTableName();
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
return $dbHandle->select($tableName, $dataFields, $whereArray);
}
/**
* Since it is *hard* to serialize classes and make sure a class def shows up
* on the other end. this function can just return the class data.
*/
function getDataFieldsInArray()
{
$dataFields = $this->getDataFields();
foreach($dataFields as $dataField)
{
$returnArray[$dataField] = $this->$dataField;
}
return $returnArray;
}
/**
* Added update support to allow to update the status
*
* #deprecated - use new function saveObject as of 8-10-2006 zak
*/
function updateObject(&$dbHandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataArray = $this->getDataFieldsInArray();
$updatedRows = $dbHandle->updateRow(
$tableName,
$dataArray,
array( $keyField => $this->$keyField )
);
return $updatedRows;
}
/**
* Allows the object to be saved to the database, even if it didn't exist in the DB before.
*
* #param mixed $dbhandle
*/
function saveObject(&$dbhandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataArray = $this->getDataFieldsInArray();
$updatedRows = $dbHandle->updateOrInsert(
$tableName,
$dataArray,
array( $keyField => $this->$keyField )
);
return $updatedRows;
}
}

"Welcome " . $_COOKIE["username"] . "!<br />"; [and many other places]
HTML-injection leading to cross-site security holes. You need to use htmlspecialchars every time you output a text value to HTML.
"INSERT INTO special (specialtitle, specialinfo) VALUES ('$specialtitle' [and many other places]
SQL-injection leading to database vandalism. You need to use mysql_real_escape_string every time you output a text value to an SQL string literal.
if (isset($_COOKIE["username"]))
Cookies are not secure, anyone can set a username cookie on the client-side. Don't use it for access control, only as a key to a stored or session user identifier.
You also appear to be using register_globals to access $_REQUEST values as direct variables. This is another extreme no-no.
Between all these security snafus you are a sitting duck for Russian hackers who will take over your site to push viruses and spam.

Be careful with your code there. Your not filtering your cookie value and you shouldn't be storing a username directly in there as it can be easily changed by the visitor. You should look into filter_input for filtering cookie data and eany form data that is being submitted - especially your $_POST['id']
this will save you a lot of heartache further down the line from attacks.
Your if else statements are checking if variables are set but you dont set next, previous, add etc
You are using submit buttons with those values so you would need to check for
if(isset($_POST['previous']))
instead of yours which is
if(isset($previous))
I can't see where you set your database details either unless you have an included file somewhere that you haven't posted. (don't post the real ones of course but i can't see anything)

I don´t know what's happening in login.php, but you're using $id before it is set. That´s just in the first part.
Edit: To clarify, you are using $id in every query statement and setting it afterwards, my guess would be that $id is null and that is why nothing gets returned.
Edit 2: What else is happening in login.php? If you never read your $_POST variables, nothing will ever happen.
Edit 3: Like I already partly said in a comment, your if(isset($previous)) section, elseif (isset($update)) section and elseif (isset($delete)) sections will never do anything as $id is always 0.
After authenticating your user you need to get and filter the posted variables, $_POST['id'], $_POST['previous'], etc.

Related

How to fetch and dispaly specific data with PDO

I'm having issues making my project for lesson attendance and management work the way I'd like it to. Sorry if this has already been addressed here. After days of searching, I still cannot for the life of me find a way to display a limited result set from my DB query to my home page.
This part of the project gets all Towns listed on my homepage like so:
Verona
Mantova
Rovereto
Bardolino
...
What I'd rather want is to get control over whatever is displayed! Specifically, I'd like to have ONLY Rovereto and Bardolino returned (as example). I'm thinking of probably doing this with additional page e.g. index1.php so when this page is loaded it will show only desired values and not all fetched values!
The search function result is also case sensitive. If I type "Bardolino", I get result but with "bardolino", no joy at all. I'm new to this, please help me out. Thank you very much.
File index.php:
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Lesson Number</th>
<th>Town</th>
</tr>
</thead>
<tbody>
<?php
for($i=0; $i < count(User::get_all_users()); $i++){
echo "<tr>";
echo "<td>".User::get_all_users()[$i]['id']."</td>";
echo "<td>".Lesson::get_lesson_by_id(User::get_all_users()[$i]['lesson_id'])['number']."</td>";
echo "<td>".show_town(Lesson::get_lesson_by_id(User::get_all_users()[$i]['lesson_id'])['town_id'])."</td>";
echo "</tr>";
}
?>
File user_controller.php:
if(isset($_GET['type']) && $_GET['type'] == 'search'){
global $user_search_list;
$user_search_list= array();
for($i=0; $i < count(User::get_all_users()); $i++){
$user = User::get_all_users()[$i];
$lesson_number = Lesson::get_lesson_by_id($user['lesson_id'])['number'];
$town_name = show_town(Lesson::get_lesson_by_id($user['lesson_id'])['town_id']);
if(strpos($lesson_number,$_GET['search_term']) !== False ||
strpos($town_name,$_GET['search_term']) !== False)
{
$user_search_list[] = $user;
}
}
$_SESSION['search_list'] = $user_search_list;
header("Location: search_user_list.php");
exit();
}
if(isset($_GET['type']) && $_GET['type'] == 'reserve'){
$user = User::get_user_by_id($_GET['user_id']);
if(!empty($_GET['seat_id'])) {
if(count($_GET['seat_id']) * $user['price'] > intval(Balance::get_user_balance($_SESSION['user_id'])['amount'])){
header("Location: reserve.php?user_id=".$user['id']."&balance_error=set");
exit();
}else{
foreach($_GET['seat_id'] as $seat_id){
echo $seat_id;
echo "<br>";
Reservation::create_reservation('', $_SESSION['user_id'], $_GET['user_id'], $seat_id, getdate()[0]);
Balance::update_balance($_SESSION['user_id'], intval(Balance::get_user_balance($_SESSION['user_id'])['amount']) - intval(User::get_user_by_id($_GET['user_id'])['price']));
Seat::reserve_seat($seat_id,$_SESSION['user_id']);
Action::create_action('', "User - ".$_SESSION['user_id'].'reserve Seat ID - '.$seat_id. " on User ID - ".$_GET['user_id'],"reserve" , getdate()[0]);
}
if(count(Reservation::get_all_reservations_by_user($_SESSION['user_id'])) == 5){
Balance::update_balance($_SESSION['user_id'] ,intval(Balance::get_user_balance($_SESSION['user_id'])['amount']) + 10);
header('Location: index.php?reserve_success=set&reward=set');
exit();
}
header('Location: index.php?reserve_success=set');
exit();
}
}
else{
header("Location: reserve.php?user_id=".$user['id']."&seat_error=set");
exit();
}
}
function show_town($id){
return Place::get_place_by_id(Town::get_town_by_id($id)['place_id'])['name'].
}
File User.php:
class User
{
static $id;
static $lesson_id;
static $starting_date;
static $starting_time;
static $arrival_time;
static $price;
static function create_user($id, $lesson_id, $starting_date, $starting_time, $arrival_time, $price){
global $db;
$sql = "INSERT INTO `lesson_database`.`users` (`id`, `lesson_id`, `starting_date`, `starting_time`, `arrival_time`, `price`) VALUES (NULL, '".$lesson_id."', '".$starting_date."', '".$starting_time."', '".$arrival_time."', '".$price."');";
$db_result = $db->query($sql);
if($db_result){
return True;
}
else{
return False;
}
}
static function get_all_users(){
global $db;
$sql = "SELECT * FROM `users`";
$db_result = $db->query($sql);
if($db_result){
return $db_result->fetchAll();
}
else {
return False;
}
}
static function get_user_by_id($id){
global $db;
$sql = "SELECT * FROM `users` WHERE `id` = '".$id."' LIMIT 1";
if(!isset($sql)){
echo "not set";
}
$db_result = $db->query($sql);
if($db_result){
$db_row = $db_result->fetch(PDO::FETCH_ASSOC);
if($db_row){
return $db_row;
}
else {
return False;
}
}
return False;
}
static function delete_user($id){
global $db;
$sql = "DELETE FROM `lesson_database`.`users` WHERE `users`.`id` = '".$id."'";
$db_result = $db->query($sql);
if($db_result){
return True;
}
else{
return False;
}
}
}
I feel a little bit like you've jumped ahead and skipped some basics as lots of this doesn't make sense.
Firstly, you've said about using PDO in the title but you're not using PDO in your queries, you really need to be using PDO so if you're not sure how then try and find a good tutorial about using prepared statements.
Secondly, you're doing loads of extra calls within loops and duplicating calls all over the place so I think you could do with looking for a tutorial on design patters and think about how you could streamline this code.
As a very basic you could get all your users once by using a fetchAll (or fetch_assoc i think in mysqli) and then just loop through that variable e.g.
<?php
$users = User::get_all_users;
foreach($users as $user){
$lesson = Lesson::get_lesson_by_id($user['lesson_id']);
echo "<tr>";
echo "<td>".$user['id']."</td>";
echo "<td>".$lesson['number']."</td>";
echo "<td>".show_town(lesson['lesson_id'])['town_id'])."</td>";
echo "</tr>";
}
as for your search the simplest way would be to pass a search string in the url and use global $_GET['searchString'] (obviously you will need to sanitize the string) and then search for results directly in sql such as
SELECT * FROM table WHERE town LIKE . $yourvariable .% (ideally in your newly learned PDO style)
then it will be both not case sensitive and will also mean you've got the data in the first place so you don't waste time looping through a bunch of extra rows.
If you need to make this case insensitive in the meantime then the simplest way is to convert the search and the comparison string to the same case (strtolower for example) and then they will match
It also strikes me that your database might not be in good shape as I would be surprised to find that a user table contains lesson ids, so you might want to look into the idea of database normalisation, this will then allow you to do some more creative queries and more easily gather together accurate information for whatever your task is (i.e. make it scalable and manageable).
I hope some of that is helpful, sorry it's not a quick answer but it's not a quick problem I think. Don't fear though, we all started somewhere!!

PHP has to update content from PDO database shown in while loop, but removes it instead

Solution found, but new problem occured - displayed at bottom of this question
I have created this while loop which shows all content from my db and gives the user the possibility to edit it by entering a new value and pressing the 'Update' button. Everything works fine except that when I press the 'Update' button, the value of my object is erased in stead of updated. So the value of my input field becomes blank, but it has to display the value that was filled in.
I'm almost certain that the problem is within the last part my PDO code (in the function Update), but can't point my finger on it. Can you help me?
Connection to my PDO code
<?php
include_once('classes/Day.class.php');
$d = new Day();
$all = $d->getAll();
if(isset($_POST['update'])){
$d->Report = $_POST['myreport'];
$d->Id = $_POST['hidden'];
$d->Update();
}
?>
My while loop
<?php
while ($displayAll = $all->fetch(PDO::FETCH_ASSOC)) {
echo
"
<form method='POST' action=''>
<label>Day " . $displayAll['id'] . ":</label>
<input type='text' name='myreport' value='" . $displayAll['myreport'] . "' />
<input type='hidden' name='hidden' value='" . $displayAll['id'] . "' />
<button type='submit' name='update''>Update</button>
</form>
";
}
?>
My functions
<?php
include_once('Db.class.php'); // connection to the Db.
class Day{
private $m_iId;
private $m_sMyreport;
public function __set($p_sProperty, $p_vValue){
switch($p_sProperty){
case 'Id':
$this->m_iId = $p_vValue;
break;
case 'Myreport':
$this->m_sMyreport = $p_vValue;
break;
}
}
public function __get($p_sProperty){
switch($p_sProperty){
case 'Id':
return $this->m_iId;
break;
case 'Myreport':
return $this->m_sMyreport;
break;
}
}
public function Update(){
$conn = Db::getInstance();
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$statement = $conn->prepare("
UPDATE `tbl_dailyreport`
SET `myreport` = :myreport
WHERE `id` = :id
");
$statement->bindValue(":myreport",$this->m_sMyreport);
$statement->bindValue(":id",$this->m_iId);
$statement->execute();
}
public function getAll () {
$conn = Db::getInstance();
$result = $conn->query("SELECT * FROM tbl_dailyreport");
return $result;
}
}
?>
All help is appreciated!
Edit: solution found + new problem
$d->Report = $_POST['myreport'];
in "Connection to my PDO code" has to become
$d->Myreport = $_POST['myreport'];
because it has to be equal to the case items in the setter and getter. The annoying thing now is that when I press 'Update' the previous message is still visible, so I have to double refresh. Any solutions for this?
If I understand You correctly You will have to load current results just after the update:
if(isset($_POST['update'])){
$d->Report = $_POST['myreport'];
$d->Id = $_POST['hidden'];
$d->Update();
$all = $d->getAll();
}
This way, after the update You will have fresh (updated) results that You can display in My while loop.

Create class instances from data

I've got a PHP class, and I'd like to create instances I can update later from the data that I pull from the database. Here's what I've got so far:
<?php
$servername = "localhost";
$username = "super";
$password = "cala";
$database = "fraga";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$getTableQuery = "SELECT ani.Id, ani.Name, ani.Size, ani.Color, tbs.Name as Species, tbs.Description
FROM animals as ani INNER JOIN
animalTypes as tbs ON ani.Species = tbs.Id
ORDER BY ani.Id";
$table = $conn->query($getTableQuery);
$pageLoaded = false;
if(isset($_POST['btnInsert']) && ($_POST['txtName'] != "")){
$pageLoaded = true;
}
if ($table->num_rows > 0) {
echo "<table border='1'><tr><th>Name</th><th>Size</th><th>Color</th><th>Species</th></tr>";
// output data of each row
while($row = $table->fetch_assoc()) {
echo "<tr><td>".$row["Name"]."</td><td>".$row["Size"]."</td><td>".$row["Color"]."</td><td>".$row["Species"]."</td></tr>";
$fish[] = $row;
}
echo "</table>";
echo "</br>";
} else {
echo "0 results";
}
if(isset($_POST['btnInsert']) && ($_POST['btnInsert'] == "Insert") && $pageLoaded == true)
{
$Animal = new Animal($_POST['txtName'], $_POST['txtSize'], $_POST['txtColor'], $_POST['txtSpecies'], $_POST['txtDescription']);
$Animal->InsertAnimal($conn);
}else if(isset($_POST['btnSave']) && ($_POST['btnSave'] == "Save") && $pageLoaded == true){
$Animal->UpdateAnimal($Animal);
}
class Animal
{
private $name = "Animal Name";
private $size = 0;
private $color = "255:255:255";
private $speciesName = "Species Name";
private $speciesDescription = "Species Description";
public function Animal($name, $size, $color, $species, $description){
$this->name = $name;
$this->size = $size;
$this->color = $color;
$this->speciesName = $species;
$this->speciesDescription = $description;
}
private function ColorCheck($color){
if($color >= 256 || $color <= 0)
return false;
else
return true;
}
public function InsertAnimal($conn, $pageLoaded){
$this->speciesName = mysqli_real_escape_string($conn, $this->speciesName);
$this->speciesDescription = mysqli_real_escape_string($conn, $this->speciesName);
$this->name = mysqli_real_escape_string($conn, $this->name);
$this->size = mysqli_real_escape_string($conn, $this->size);
$this->color = mysqli_real_escape_string($conn, $this->color);
$speciesId = "SELECT Id from animalTypes WHERE Name = '$this->speciesDescription'";
$speciesInsert = "INSERT IGNORE INTO animalTypes (Name, Description)
VALUES ('$this->speciesName', '$this->speciesDescription')";
$result = mysqli_query($conn, $speciesInsert) or die("Query fail: " . mysqli_error($conn));
if($id = $conn->query($speciesId)){
$row = $id->fetch_assoc();
$intId = $row['Id'];
}
$AnimalInsert = "INSERT INTO animals (Name, Size, Color, Species)
VALUES ('$this->name', $this->size, '$this->color', $intId)";
$result2 = mysqli_query($conn, $AnimalInsert) or die("Query fail: " . mysqli_error($conn));
echo '<script type="text/javascript">window.location = window.location.href;</script>';
$_POST['txtName'] = "";
}
public function UpdateAnimal($animal, $conn){
$speciesCheck = "SELECT * FROM animalTypes WHERE Name = '$this->speciesName";
$speciesList = mysqli_query($conn, $speciesCheck) or die("Query fail: " . mysqli_error($conn));
$updateQuery = "UPDATE animals";
}
}
$conn->close();
?>
<body>
<form action="index.php" method="post">
Animal Name:<br />
<input name="txtName" type="text" /><br />
<br />
Size:<br />
<input name="txtSize" type="text" /><br />
<br />
Color:<br />
<input name="txtColor" type="text" /><br />
<br />
Species Name:<br />
<input name="txtSpecies" type="text" /><br />
<br />
Species Description:<br />
<input name="txtDescription" style="width: 419px; height: 125px" type="text" /><br />
<br />
<input name="btnInsert" type="submit" value="Insert" />
<input name="btnSave" type="submit" value="Save" />
</form>
</body>
Now, what I'd like to do is create instances of Animal from the data that loads when the page loads, and store them for update. Problem is, I'm not sure how to do it. I've googled a bit (but my fu is admittedly weak), and saw suggestion for creating an array of Animals and adding them during the while loop. Is that really the best way to do that? And then how could I load the instance back into the text boxes so that I could update them?
First of all you should learn to seperate the concerns in your code correctly.
If I started to explain how you should build your script up from scratch, this would take too long, so I will try to give you only a good direction to go. I think this will help you more in your learning process.
So, if I understand correctly, the code you posted is all set up in one file, I guess it's inside you index.php? (missing some information here)
If this is the case...
index.php
Use your index.php for displaying a list of your "Animals" from db, not more. Every list entry will have an edit and delete button/link next to it. On top of your list put a link that's called create.
Now all your index.php does is getting the animals from db and listing them.
Put this part of your code in another file, called dbconfig.php
$servername = "localhost";
$username = "super";
$password = "cala";
$database = "fraga";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
include it on top of your index.php, before you start scripting the index.php
include 'dbconfig.php'
now you can use your $conn variable inside you index.php. We put this into another file and included it, because we're going to reuse this part in the next steps.
I won't write your whole code here for index.php, I think you'll master that. Maybe you ask yourself what your create, edit, delete links should do.
The create link point to a create.php, a simple html link.
The edit link, you will have to render an html link to edit.php?id=IDOfYourAnimalInsideDB
The delete link looks like the edit one, put a link to delete.php?id=IDOfYourAnimalInsideDB.
So where I wrote "IDOfYourAnimalInsideDB" you have to output the actual id, this will be done in your while loop.
create.php
first of all, include the dbconfig.php again here, so you can use your $conn variable which has the db connection.
check if the request has some of your post variables, if true, build an instance of animal and write it to db.
outside the if you build your form. So it doesn't matter if it's post or not, you will show the create form.
delete.php
Again the dbconfig.php include first.
Then you want to check if $_GET['id'] is set and maybe if it's bigger than 0 and if its an integer value. If so, execute your delete sql to the db.
update.php
Again the dbconfig.php include first.
Then you want to check your GET Parameter again and build an sql request to get your specific database entry.
Output a form that already contains your values from db. If a post request comes, you create a new Animal instance, fill it with your data from $_POST and then use it for updating your db.
getters in Animal Class
add getter functions to you animal class, so you can access the private properties from outside. you should write you create, update, delete logic inside the create.php, update.php, delete.php or in another class which you use for database manipulation. There you want to get access to properties for example in order to build up your update sql.
So make a getter method for every property of your "Animal" model class
public function getName() {
return $this->name;
}
so from outside you can get your animals name like so
$animalName = $animal->getName();
more specific?
If you need something more specific, you should specify a little bit more your question. What I described is just a way that splits your script into parts you can understand and maintain better, because stucture and correct seperation of things is one of the most important things in programming.
What I described is far far away from a clean "CRUD" solution, but I think this is a little step for you that you can take now to come closer to a clean solution.
Kind regards

PHP custom function return value from mysql database

i have looked at the other results for what i'm trying to do, none of them do what i need them to. What i am trying to do is something like this:
myfunction(){
require('./connect.php'); //connect to database
$query = mysql_query("SELECT * FROM users WHERE username='$user'"); //user is defined outside the function but it works in my login function which i use the same way.
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);
$value = row['value'];
mysql_close();
return $value;
} else {
$errmsg = "connection failed.";
$value = 0;
return $value;
}
}
In my php file i would do something like this at the top.
$value = myfunction();
This does not work.
Ultimately what i'm trying to accomplish is getting a value from the database and output it from the function in another file.
(this is my first post on stackoverflow so if i need to change this feel free to tell me and i shall)
Your code has several syntax error. Check this, and read my comments:
function myfunction() {
//connect to database
require('./connect.php');
//user is defined outside the function but it works in my login function which i use the same way.
$query = mysql_query("SELECT * FROM users WHERE username='" . mysql_real_escape_string($user) . "'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
return $row['value']; //Missing $ sign
//No need to create $value if you just return with that.
//mysql_close();
//return $value;
} else {
//Where do you use this errmsg????
$errmsg = "connection failed.";
return 0;
// These 2 lines are unnecessary.
//$value = 0;
//return $value;
}
} //Missing function close
In my example, I've just leave the mysql functions, but please do not use them, they are deprecated. Use mysqli or PDO instead. Also, avoid sql injections by escapeing your variables!
$row = mysql_fetch_assoc($query);
$value = row['value']; // <-------- you forgot the $
and most probably, the correct way to extract the result is,
$row[0]['value'];
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
i'm thinking you forgot a dot here.
require('./connect.php');
And a bit of function improvement
myfunction(){
require_once('../connect.php'); //connect to database
$query = mysql_query("SELECT * FROM users WHERE username='".$user."'"); //user is defined outside the function but it works in my login function which i use the
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);
$value = $row['value'];
mysql_close();
}
else{
$errmsg = "connection failed.";
$value = 0;
}
return $value;
}

what can make an update query not to update but return success

I have this class am using to perform queries - insert, delete, drop create etc, but this time i created a method to update a table when the update have been submitted and to my surprise and hours of headache it is return success but not actually updating the record in the database am so confused, I have been debugging for hours to no avail
so i decided to share my worries to see if i can receive help as am actually 2 weeks old In OOP PHP
so here my class
class queryClass extends MYSQL{ //MYSQL is for connecting to database
//table fields
var $user_table = ''; //table names that will be used in all names, each query method will input its own table name
//connect to database
function dbconnect(){
MYSQL::dbconnect();
}
//prevent injection
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
//update quote function
function updatequote($table, $message1, $message2, $column_name1, $column_name2, $column_name3, $quote_id){
$this->dbconnect();
$this->quote_id = $quote_id;
echo $message1, $message2;
//make sure table name is set
$this->user_table = $table;
$this->column_name1 = $column_name1;
$this->column_name2 = $column_name2;
$this->column_name3 = $column_name3;
//execute login via qry function that prevents MySQL injections
$result = $this->qry("UPDATE ".$this->user_table." SET ".$this->column_name2."='?', ".$this->column_name3."='?'
WHERE ".$this->column_name1."='?';", $message1, $message2, $this->quote_id );
// $result = mysql_query("INSERT INTO ".$this->user_table."(username, password) VALUES('$username', '$password')");
if($result){
$_SESSION['success'] = "The Update Was Successfully Saved";
header('location: edit_quotes.html');
exit();
return true;
}else{
$_SESSION['success'] = "The Update Was Not Saved".mysql_error();
header('location: edit_quotes.html');
exit(); //do something on FAILED login
return false;
}
}
//quote form
function quoteEditorform($formname, $formclass, $formaction, $helptext, $first, $second){
//conect to DB
$this->dbconnect();
echo"
<form name=\"$formname\" method=\"post\" id=\"$formname\" class=\"$formclass\" enctype=\"application/x-www-form-urlencoded\" action=\"$formaction\">
<h2>$helptext</h2>
<div><label for=qoute>NGWA QUOTE
<input type=button value='Quote' onclick=\"wrapInTags(this.form.message1,'quote')\">insert [quote].[/quote]tags
</label>
<textarea name=\"message1\" cols=\"40\" rows=\"4\" onclick=\"copySelection(this)\">$first</textarea><br>
</div>
<div><label for=\"qoute\">ENGLISH MEANING
<input type=button value='Meaning' onclick=\"wrapInTags(this.form.message2,'meaning')\">
insert [meaning].[/meaning]tags
</label>
".$record['meaning']."
<textarea name=\"message2\" cols=\"40\" rows=\"4\" onclick=\"copySelection(this)\">$second</textarea></div>
<input name=\"action\" id=\"action\" value=\"sendeditedquote\" type=\"hidden\">
<div>
<input name=\"submit\" id=\"submitV value=\"Save\" type=\"submit\"></div>
</form>
<div align=\"center\">Read Before Posting</div>
"; }
function createquotetable($tablename){
//connect to DB
$this->dbconnect();
$qry = "CREATE TABLE IF NOT EXISTS ".$tablename."(
quote_id INT(8) NOT NULL AUTO_INCREMENT,
ngwaquote TEXT NOT NULL,
meaning TEXT NOT NULL,
saved_date date,
PRIMARY KEY (quote_id)
) TYPE=INNODB
";
$result = $this->qry($qry);
return;
}
here's my quote-editor.html after including my class files
// instantiate all other needed classes
$cleaner = new cleanPost();
$connect = new MySQL();
$connect->dbconnect();// connect to a database
$bbcode = new BBCode();
$log = new logmein();
if($_REQUEST['action'] == "sendeditedquote"){
//post all the values to the database using our main class
/*topic field checking */
if($_REQUEST['message1'] == "" || $_REQUEST['topic'] > 600) {
$errmsg_arr[] = 'Sorry You Can\'t Send An Empty Qoute OR quote greater than 500 characters at a time';
$errflag = true;
}
if($_REQUEST['message2'] == "" ) {
$errmsg_arr[] = 'Sorry You Can\'t Update With An Empty Qoute';
$errflag = true;
}
//If there are input validations, redirect back
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: edit_quotes.html");
exit();
}
$log->updatequote("quotes", $_REQUEST['message1'], $_REQUEST['message2'], "quote_id", "ngwaquote", "meaning", $cleaner->clean($_GET['quote_id']));
}
ai'ght when i perform the query the success/error line returns that the update was successful but on the other page where i display all available quotes the particular quote still is NOT updated
Anyone who's experienced such please tell me what am gon' do.
BEING ASKED THE LINE FOR THE RAW QUERY
HERE IS IT-
first is the the method that cleanse ouy my post and the I use it for query using $this->qry(somequeries here)
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
//update quote function using $this->qry()
function updatequote($table, $message1, $message2, $column_name1, $column_name2, $column_name3, $quote_id){
$this->dbconnect();
$this->quote_id = $quote_id;
echo $message1, $message2;
//make sure table name is set
$this->user_table = $table;
$this->column_name1 = $column_name1;
$this->column_name2 = $column_name2;
$this->column_name3 = $column_name3;
//execute login via ****qry function**** that prevents MySQL injections
$result = $this->qry("UPDATE ".$this->user_table." SET ".$this->column_name2."='?', ".$this->column_name3."='?'
WHERE ".$this->column_name1."='?';", $message1, $message2, $this->quote_id );
// $result = mysql_query("INSERT INTO ".$this->user_table."(username, password) VALUES('$username', '$password')");
if($result){
$_SESSION['success'] = "The Update Was Successfully Saved";
header('location: edit_quotes.html');
exit();
return true;
}else{
$_SESSION['success'] = "The Update Was Not Saved".mysql_error();
header('location: edit_quotes.html');
exit(); //do something on FAILED login
return false;
}
}
If the where clause of your update statement does not match any rows, the update statement will return success.
However it will not change anything.
Note that MySQL knows when a value has not really changed so the statement
UPDATE table1 SET col1 = 0 WHERE col1 = 0
Will always return 0 for the number of affected rows.
If you want to know if anything has been changed you need to call:
$rows_updated = mysql_affected_rows($this->connection);
or
$rows_updated = mysqli_affected_rows($this->connection); //if you're using mysqli
An update statement will only indicate failure is an error has occured.
A warning about SQL-injection
I notice that you use dynamic table and column names.
If those values are in any way alterable by a user or pass through superglobals that can be affected by another php session that can be affected by a user, you have an SQL-injection hole.
Here's how to secure yourself against that: How to prevent SQL injection with dynamic tablenames?
I think i have found the answer to my problem
In the place i had the $this->quote_id i later figured out that the page editor url was editor.html?quote_id=1
then when I submitted it will now process the form on a flat url === editor.html so my mistake was that I didn't request for the QUOTE ID when i was still on the editing url editor.html?quote_id=1 instead requesting for it when it was not possible ie in editor.html so it was meant to return empty quote id which i used to update thereby resulting in update success but not really updating anything
so
all I did was add an input tag hidden to get the quote_id being edited and then post it along with the rest of the form
So simple but took me me hours of rereading and re coding, wonderful,
small things cause much frustration
Thanks all
if the fields you are updating is not the same has the fields in the database, it will not update. although it return success simple means that it sees the table and connect to the database

Categories