PHP not updating correctly on POST - php

I'm trying to write a function that will allow a user to enter a name into a field, insert the field to a MySQL table and then update a dropdown menu to include those names (while allowing for further additions).
On first load of the page, the dropdown menu shows the correct names that I seeded into the table. When I input a name into the form, it inserts to the table correctly, but then none of the options show in the dropdown list and it removes my entry form. If I refresh the page, everything comes back fine, and the names previously entered show up in the list.
I know I'm missing something obvious in the code to refresh the page, but I'm not even sure what to search for. I thought that by setting my form action to .$_SERVER['PHP_SELF']. it would cause the page to process and reload. I have a hunch this is where my problem is, but I'm not sure what it is.
The dropdown code was something I found off the web, perhaps I have to rewrite it myself, though it's the one part of this mess that's actually working.
Also, the mysql login is hardcoded in db_tools.php b/c I can't get it to work otherwise.
Sorry for the following wall of text, but I'm just trying to provide the most information possible. Thank you for your replies and pointing me in the right direction.
I have 2 files, db_tools.php and dropdown.inc
db_tools.php:
<?php
require_once 'db_login.php';
require_once 'MDB2.php';
require_once("dropdown.inc");
//Define a function to perform the database insert and display the names
function insert_db($name){
//initialize db connection
//$dsn = 'mysql://$db_username:$db_password#$db_hostname/$db_database';
$dsn = "mysql://redacted";
$mdb2 =& MDB2::connect($dsn);
if (PEAR::isError($mdb2)) {
//die($mdb2->getMessage());
die($mdb2->getDebugInfo());
}
//Manipulation query
$sql = " INSERT INTO participants (id, name) VALUES (NULL, \"$name\");";
$affected =& $mdb2->exec($sql);
if (PEAR::isError($affected)){
//die($affected->getMessage());
die($affected->getDebugInfo());
}
//Display query
$query = "SELECT * FROM participants;";
$result =& $mdb2->query($query);
if (PEAR::isError($result)){
die ($result->getMessage());
}
while ($row = $result->fetchRow()){
echo $row[1] . "\n";
}
$mdb2->disconnect();
}
?>
<html>
<head>
<title>Event Bill Splitter</title>
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
else {
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
}
?>
<p>Participants:<br />
<?php dropdown(id, name, participants, name, participant_name1); ?></p>
</body>
</head>
</html>
dropdown.inc
require_once ('db_login.php');
$connection = mysql_connect($db_host, $db_username, $db_password);
if (!$connection) {
die ("Could not connect to the database: <br />". mysql_error() );
}
$db_select = mysql_select_db($db_database);
if (!$db_select) {
die ("Could not select the database: <br />". mysql_error() );
}
function dropdown($intNameID, $strNameField, $strTableName, $strOrderField, $strNameOrdinal, $strMethod="asc") {
//
// PHP DYNAMIC DROP-DOWN BOX - HTML SELECT
//
// 2006-05, 2008-09, 2009-04 http://kimbriggs.com/computers/
echo "<select name=\"$strNameOrdinal\">\n";
echo "<option value=\"NULL\">Select Value</option>\n";
$strQuery = "select $intNameID, $strNameField
from $strTableName
order by $strOrderField $strMethod";
$rsrcResult = mysql_query($strQuery);
while($arrayRow = mysql_fetch_assoc($rsrcResult)) {
$strA = $arrayRow["$intNameID"];
$strB = $arrayRow["$strNameField"];
echo "<option value=\"$strA\">$strB</option>\n";
}
echo "</select>";
}
?>

The problem of the form disappearing is simple, just remove the else after the insert section:
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
// else { // gone
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
// } // gone
?>
Apart from that I would definitely re-write the dropdown code and add some security, a whitelist for table names, etc.
By the way, you are calling your function in a strange way:
<?php dropdown(id, name, participants, name, participant_name1); ?>
I assume these are variables so it should be $id etc, but where do they come from? If you mean to send values directly, it should be:
<?php dropdown('id', 'name', 'participants', 'name', 'participant_name1'); ?>

Related

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

Return PHP/MySQL results in HTML form for editing

I have a database that users can search by any number of predetermined fields (chosen from a drop down). The problem I'm having is being able to edit existing records. The first script prompts for the record ID to edit. If no record is found the user is told to try again.
When a record is found the results are suppose to display in HTML input boxes. The user can then modify the data, hit submit and the record updates (another script).
Enabled errors. This is what is thrown:
Fatal error: Call to undefined method mysqli_result::fetch__assoc() in (path to script) on line 37
Any ideas on what is wrong?
<?php
//Include everything but the password to connect to db
include 'includes/connect_pw.php';
//User supplies password on previous form
$dbpass = $_POST['password'];
//User supplies id on previous form
$rec_id = $_POST['query'];
//Create connection to database using mysqli
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
//Check connection. If error then kill process, show error and tell user to retry
if ($conn->connect_error) {
die ("<br><br>" . $conn->connect_error . "<p></p>Did you forget the password?");
}
//If no error then set select statement as variable
$sql = "SELECT * FROM dcr_master
WHERE (`ID` = '".$rec_id."')";
//Pass select ($sql) into connection ($conn) with result to ($result)
//Set new variables to populate input boxes. ex: $variable = $row['record field']
$result = $conn->query($sql);
if ($result->num_rows >=1) {
while ($row = $result->fetch__assoc()) {
$Server_Name = $row['Server_Name'];
$Description = $row['Description'];
$IP_Address = $row['IP_Address'];
$Wiki_Link = $row['Wiki_Link'];
}
?>
<form action="modify_dcr_3.php" method="POST">
<input type="hidden" name="ID" value="<?=$rec_id;?>">
Server Name<input type="text" name="Server_Name" value="<?=$Server_Name;?>">
Description<input type="text" name="Description" value="<?=$Description;?>">
IP_Address<input type="text" name="IP_Address" value="<?=$IP_Address;?>">
Wiki_Link<input type="text" name="Wiki_Link" value="<?=$Wiki_Link;?>">
<input type="submit">
</form>
<?php
}
else {
echo "<rb><br>No matching ID found.
<p></p>Try again. Just don't use " .$rec_id. " OK?";
}
?>
You have a double underscore on fetch__assoc(), this should have only a single underscore: fetch_assoc(). Specifically change this:
while ($row = $result->fetch__assoc()) {
...
}
To:
while ($row = $result->fetch_assoc()) {
...
}

select data from DB and Insert new data in front of selected row

I want to insert a data into a mysql database, but I need to put some constrains over that insertion. And my code is not working for me.
Basically I have selected "departments" from the mysql db using html select tag and show that in dropdown. And now I want to insert subject and subject code in front of that row which is selected in the drop down. But the problem is my code is not working and show me error please help and checkout code.
This is code for inserting data from mysql database. It work's fine.
<code>
<select class="form-control" name="department">
<?php
$host="localhost";
$username = 'root';
$password = "";
$con = mysql_connect($host,$username,$password);
mysql_select_db('sims',$con);
// Checking connection
if (!$con){
echo ("Failed to connect to MySQL:. " .mysql_error($con));
}
else {
echo("db connect");
}
$result = mysql_query("SELECT * from `sims-reg-department`");
if($result == FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_array($result)){
?>
<option value="<?php '.row[dept-id];'?>"><?php echo $row["dept-name"];?></option>
<?php }
?>
</select>
</code>
This section is showing me errors:
<code>
<?php
if(isset($_POST['submit'])){
$dptname = $_POST["department"] or
$coursename = $_POST["course-name"] and
$coursecode = $_POST["course-code"];
if($coursename=="" or $coursecode=="" )
{
echo "Please fill all the fields before hit submitting button";
return true;
}
else
{
$q = "INSERT INTO `sims-reg-department`(`course-name`,`course-code`)VALUES ('$coursename','$coursecode') where '$dptname' LIKE `dept-name`";
}
$res = mysql_query($q) or die(mysql_error());
mysql_close($con);
}
?>
</code>

Database used to populate selection list

i am trying to create a form and in that form have a selection list in which the options are automatically populated with data from a database (namely customer's last names), after which when the last name is chosen from the list and the submit button is hit the "customer ID" that is related to that last name in the database will be submitted to another PHP file (task8.php) to be sent through further queries. I hope i have explained that all in an understandable manner. I have had a go at some code but i am really unsure on how to do this or if what i have written is on the right path.
Here is what i have written so far:
<body>
<?php
$conn = mysql_connect("localhost", "twa312", "dam6av9a");
mysql_select_db("warehouse312", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "select customerID, lastName from customer";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
$options= '<option value="0">Choose</option>';
while ($row=mysql_fetch_array($rs)) {
$id=$row["customerID"];
$name=$row["lastName"];
$options="<OPTION VALUE='" . $id . "'>" . $name ."</option>";
}
?>
<form method="GET" action="task8.php" id="custinfo" >
Choose name:<select name="lname" id="lname"><?php echo $options; ?>
</select>
<p><input type="submit" name="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</form>
What i am trying to do with the code is access the table "customer" and fields "customerID" and "lastName". Using the customer's last name as the option and the customer's ID as the options value in the selection list. Currently the code displays only a single name as an option in the selection list when it should display all the names in the database. Any help on this would be really great as i am fairly unsure.
There is an error in the code that I can see would cause PHP to generate notice error.
In the while loop you're using .= on the $options variable that isn't yet defined so PHP will barf on that.
Aside from that, it doesn't make sense to me that you're waiting for $_GET['submit'] to be set before iterating over the result set from mysql. As far as I can tell, the first time you'd hit this page there would be a single option in the select ("Choose"), and since the form submits to a different page I don't think you'd ever see a list of customer last names.
Finally, it's not really recommended to name your submit buttons 'submit', since when the page is parsed by the browser all the form elements of a specific form are created as attributes of that form, JS form objects have a 'submit' method so when you name an input 'submit' you clobber that value in the form object which makes it really hard to submit that form with JS.
First off move away from the mysql_functions.
Secondly create a model with all querys related to your customers that will handle fetching/puttin/updating the data related to your customer db.
<?php
Class CustomerModel{
private $db;
function __construct($host,$dbname,$user,$pass){
$this->dbhost = $host;
$this->dbname = $dbname;
$this->dbuser = $user;
$this->dbpass = $pass;
}
private function connect(){
if (!$this->db instanceof PDO){
$this->db = new PDO('mysql:dbname='.$this->dbname.';host='.$this->dbhost, $this->dbuser, $this->dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}
}
public function select_all_customer($cols="*"){
$this->connect();
$sql = "SELECT $cols FROM customer";
$statement = $this->db->prepare($sql);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
public function select_customer($cols="*",$where=null, $id=null){
$this->connect();
$sql = "SELECT $cols FROM customer WHERE $where = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
}
?>
Now you can access the model like:
<form method="POST" action="task8.php" id="custinfo" >
Choose name:
<select name="customerID" id="customerID">
<option value="0">Choose</option>
<?php foreach($customer->select_all_customer("customerID, lastName") as $row): ?>
<option value="<?php echo $row['customerID']?>"><?php echo $row['lastName']?></option>
<?php endforeach; ?>
</select>
<p><input type="submit" name="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</form>
<?php
//Get customer from form values
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['customerID'])){
$result = $customer->select_customer("*", "customerID", $_POST['customerID']);
//Do something with result
echo '<pre>'.print_r($result, true).'</pre>';
}
?>
Hope it helps

Inject dynamically some content on a listbox and get it back with PHP

I've created a webpage which uses JQuery to redirect the content of a form to another webpage using PHP to connect to a database to find some content and put it back on the first page.
Eveything works great (thanks to the help of followers of stack overflow :-) ) but now I'd like the following : I'm asking for the postal code of a city, if I'm lucky this postal code is unique (only one city has it) but it also happens that a postal code is the same for several cities so I'd like in that case to display a listbox for the user to choose his/her city.
Does someone has an idea of how to do this ?
my code :
home.html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action="/" id="myform">
<input type="text" name="postal_code" id="postal_code" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
$('#myform').submit(function() {
var url = 'target.php';
var postal_code = $('#postal_code').val();
$.post( url, { postal_code: postal_code },
function( data ) {
$( "#result" ).empty().append( data );
}
);
return false;
});
target.php
<?php
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host=localhost;dbname=mydatabase', 'root', '', $pdo_options);
$response = $bdd->prepare('SELECT city FROM city_list where postal_code = ?');
$response->execute(array($_POST['postal_code']));
echo '<ul>';
while ($data = $response->fetch())
{
?>
<br/>The city you entered the postal code is : <?php echo $data['city'];
}
$response->closeCursor();
}
catch (Exception $e)
{
die('Error : ' . $e->getMessage());
}
?>
EDIT:
This is the code ok for my needs. I'd only to make some very minor changes from Jules' code to make it ok (for an unknow reason his answer worked perfectly for him but not for me :-) )
<?php
try {
//Get the postal code:
$postcode = $_POST['code_postal'];
//Make MySQL connection
mysql_connect("localhost", "root", "") or die (mysql_error());
//Select the database
mysql_select_db("site_artisans_amélioré");
//Do your query based on the postcode...
$query = "SELECT ville FROM liste_communes_code_postaux where code_postal = '" . mysql_real_escape_string($postcode) . "'";
//Return the response in a variable
$data = mysql_query($query) or die (mysql_error());
//echo "Num rows: " . mysql_num_rows($data);
//Check how many rows the query returned. If more than 1 that means several cities
//exist for one postcode, so you should show a listbox.
//If not, just return the ville name
if (mysql_num_rows($data) > 1) { ?>
<select name="cities">
<?php while ($row = mysql_fetch_assoc($data)) { ?>
<option value="<?php echo $row['ville']?>"><?php echo $row['ville']?></option>
<?php } ?>
</select>
<?php }
else {
$row = mysql_fetch_assoc($data);
echo $row['ville'];
}
}
catch (Exception $e) {
die("Error : " . $e->getMessage());
}
?>
I am not sure which library you are using for your Database queries, so I'll do it in Pseudo-code and mysql_query..
target.php
<?php
try {
//Get the postal code:
$postcode = $_POST['postal_code'];
//Make MySQL connection
mysql_connect("localhost", "username", "password") or die (mysql_error());
//Select the database
mysql_select_db("mydatabase");
//Do your query based on the postcode...
$query = "SELECT city FROM city_list where postal_code = '" . mysql_real_escape_string($postcode) . "'";
//Return the response in a variable
$data = mysql_query($query);
//Check how many rows the query returned. If more than 1 that means several cities
//exist for one postcode, so you should show a listbox.
//If not, just return the city name
if (mysql_num_rows($data) > 1) { ?>
<select name="cities" multiple="multiple">
<? while ($row = mysql_fetch_assoc($data)) { ?>
<option value="<?=$row['city']?>"><?=$row['city']?></option>
<? } ?>
</select>
<? }
else {
$row = mysql_fetch_assoc($data);
echo $row['city'];
}
}
catch (Exception $e) {
die("Error : " . $e->getMessage());
}
?>
I hope you catch my drift and you can complete it yourself.

Categories