+/- equation with a single textfield - php

I am making a very simple storage system, and i want to make it so that the user puts a number in the box, and press the + or - button, to add or subtract.
I don't know if it's even possible to do it, as simple as i wanted it to be :)
but anyway, here is the code so far for index.php
<?php $v_stk = "v_stk" ?>
<form action="index_sql.php" method="POST">
<input name="v_id" type="hidden" value="<?php echo $v_assoc["v_id"] ?>" />
<input name="v_stk" type="textfield" size="8" />
<input name="+" type="submit" value="+" style="height:23px; width:35px;" />
<input name="-" type="submit" value="-" style="height:23px; width:35px;" />
</form>
<td class="width50 sidepadding">
<?php echo $v_assoc["v_stk"]; ?></td>
<?php }; ?>
and here is for index_sql.php
<?php
require("db/db.php");
$v_id = mysql_real_escape_string($_POST["v_id"]);
$v_stk = mysql_real_escape_string($_POST["v_stk"]);
$sql = mysql_query("SELECT v_stk FROM vare WHERE v_id = '$v_id'");
$assoc = mysql_fetch_assoc($sql);
$v_nu = $v_stk + $assoc;
mysql_query("UPDATE vare SET v_nu = '$v_stk' WHERE v_id = '$v_id'");
header("location: index.php");
?>
I don't know if it is remotely close to something that would work, but with this code it gives me:
Fatal error: Unsupported operand types in C:\wamp\www\lager\index_sql.php on line 8

Because, You are performing addition with an array type variable.
$assoc = mysql_fetch_assoc($sql);
Here, $assoc is an array variable so try like this,
$v_nu = $v_stk + $assoc['v_stk'];

Related

Just need assistance some php CRUD functionality

Im currently coding a website in php, unfortunately ive hit a road block were i cant seem to get my amend.php and update.php pages to work and update on my created display page below is the code.
Display page displays a table with descriptive columns when the hyperlink 'amend' is select it runs the amend.php.
Amend
<?php
include 'connection.php';
$id = $_GET ['theid'];
$query = "SELECT * FROM place WHERE placeid = '$id'";
$results = mysqli_query($connection,$query);
$row = mysqli_fetch_assoc($results);
?>
<?php include 'header.php'; ?>
<body>
<h2>Amend</h2>
<form method="post" action="updateplace.php">
<fieldset class="fieldset-width1">
<input type="hidden" name="hiddenID" value= "<?php echo $row['placeid']; ?>" />
<br />
<br />
<label class="align" for="txtplacename">Place Name: </label>
<input type="text" name="txtplacename" value = "<?php echo $row['placename']; ?>" />
<br />
<br />
<label class="align"for="txtplacedesc">Place description: </label>
<input type="text" name="txtplacedesc" value = "<?php echo $row['placedesc']; ?>" />
<br />
<br />
<label class="align"for="txtplacecat">Place category: </label>
<input type="text" name="txtplacecat" value = "<?php echo $row['placecat']; ?>" />
<br />
<br />
<label class="align" for="txtplaceimg">Place image: </label>
<input type="text" name="txtplaceimg" value = "<?php echo $row['placeimg']; ?>" />
<br />
<br />
<input type="submit" value="Submit" name='submit' />
</fieldset>
</form>
</p>
<?php include 'footer.php'; ?>
</body>
</html>
This php page works as it displays all the data from phpmyadmin using the selected id.
update
<?php
include 'connection.php';
if(isset($_POST['submit'])){
$placeid = $_POST['hiddenID'];
$placename = $_POST['txtplacename'];
$placedesc = $_POST['txtplacedesc'];
$placecat = $_POST['txtplacecat'];
$placeimg = $_POST['txtplaceimg'];
}
$query = "UPDATE place
SET placename = '$placename';
SET placedesc = '$placedesc';
SET placecat = '$placecat';
SET placeimg = '$placeimg';
WHERE
placeid = '$placeid'";
mysqli_query($connection,$query);
header("location:admin.php");
when i select the submit button the header redirects me however none of the columns i change will have been updated. Any help would be appreciated thanks
Look at your UPDATE query,
$query = "UPDATE place
SET placename = '$placename'; <==
SET placedesc = '$placedesc'; <==
...
You're terminating your UPDATE operation in every line using ;, which is breaking your query. Furthermore, your UPDATE query itself is wrong, it should be like this:
$query = "UPDATE place SET placename = '$placename', placedesc = '$placedesc', placecat = '$placecat', placeimg = '$placeimg' WHERE placeid = '$placeid'";
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attacks. Also here's a good read on how you can prevent SQL injection in PHP.
You should not just assume the query was successful. Replace your mysqli_query line with this to figure out what is going on:
if (!mysqli_query($connection, $query)) {
echo("Error description: " . mysqli_error($connection));
die();
}
Assuming you have some sort of error, it will prevent the redirect and display. If you still get a redirect, there was nothing wrong with the query itself, rather your $placeid value does not exist in the database.

Trying PHP IF Else Statements for the first time

I'm learning PHP and trying to understand the if .. else statements a little better, so I'm creating a little quiz. However, I have come across an issue and I don't seem to know what the issue is. My problem is that whenever I type in the age in the input area, it will give me the $yes variable every time even if I enter the wrong age.
Here is my code so far:
My html file:
<form action="questions.php" method="post">
<p>How old is Kenny?<input></input>
<input type="submit" name="age" value="Submit"/>
</p></form>
My php file:
<?php
$age = 25;
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25){
echo "$yes";
}else{
echo "$no";
}
?>
You catch the user input inside the $_POST superglobal var (because the method of your form is POST.
So
<?php
$age = 25;
should be
<?php
$age = $_POST['age'];
There is an error in HTML too. This
<input type="submit" name="age" value="Submit"/>
should be
<input type="text" name="age" value=""/>
<input type="submit" value="Click to submit"/>
Because you want one input and one button. So one html element for each element.
and <input></input> must be cleared because it's not valid syntax :-)
<form action="questions.php" method="post">
<p>How old is Kenny?</p><input type="text" name="age"></input>
<input type="submit" value="Submit"/>
</form>
$age = (int) $_POST["age"];
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25) {
echo $yes;
} else {
echo $no;
}
<?php
/* Test that the request is made via POST and that the age has been submitted too */
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['age'] ) ){
/*
ensure the age is an integer rather than a string ..
though for this not overly important
*/
$age=intval( $_POST['age'] );
if( $age==25 ) echo "Congratulations";
else echo "Bad luck!";
}
?>
<form action="questions.php" method="post">
<p>How old is Kenny?
<input type='text' name='age' placeholder='eg: 16' />
<input type="submit" value="Submit" />
</p>
</form>
A simple html form, note that the submit button does not carry the values you want to process, they are supplied via the input text element.
First of all, you need to echo the variable; echoing "$no" will keep it as a string. Remove the quotes from "$no" and "$yes" in your if then statement. Otherwise, your code seems sound!

Cannot echo variable in text jQuery Easy UI

Why I cant set value with echo variable in text form jquery eui?
<input type="text" name="text1" class="easyui-validatebox" value="<? echo $varPhp; ?>" size="53"/></td>
My php function like this..
<?php
$query = "SELECT MAX(kode_barang) as maxID FROM tb_barang";
$hasil = mysql_query($query);
$data = mysql_fetch_array($hasil);
$idMax = $data['maxID'];
$noUrut = (int) substr($idMax, 1, 4);
$noUrut++;
$varPhp = "B" . sprintf("%04s", $noUrut);
?>
Anyone can help me?
Question Closed.. :) i pass the process and create in model.
May be your php version doesnt support the use of short tags.Check the documentation .And try this
<input type="text" name="text1" class="easyui-validatebox" value="<?php echo $varPhp; ?>" size="53"/>
Try
<?php echo $varPhp; ?>
I assume that your variable is empty.
To ensure that, use var_dump to dump it.
Try this:
<input type="text" name="text1" class="easyui-validatebox" value="<?php var_dump($varPhp); ?>" size="53"/>

What am I doing wrong? Edit table data in form [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a table with a edit link and a delete button on each row. Delete button is working fine but the edit link I don´t know what I´m doing wrong with!
Clicking the edit link for a specific row it leads to edit page with the form BUT the data is not filled out. There is no error message... I can see up in the URL field that it´s the correct id for the chosen movie.
What am I missing? Do I need to write any queries etc on the edit page as well? I did try and make it a require page so when clicking on the edit button the edit form pops up on the index page. But I couldn't manage to do that.
I know I'm using mysql functions which are outdated, and I have yet to add SQL protection.
The database is called moviedata and has 2 tables.
Table 1 is called: movies
Fields/columns (5): id (primary key, AI), ****title** , release_year,** ****genre_id**, **director****
Table 2 is called: categories
Fields/columns (2): genre_id (primary key, AI), genre
There is a relation (Foreign key) between genre_id (primary key, table 2) and genre_id (table 1).
index.php code
<!DOCTYPE html>
<html>
<head>
<title>My movie library</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="mall.css" />
</head>
<body>
<?php
require 'connect.inc.php';
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = $_POST['id'];
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
if (!mysql_query($query, $sql))
echo "DELETE failed: $query<br>".
mysql_error() . "<br><br>";
}
$query = "SELECT * FROM movies m INNER JOIN categories c ON m.genre_id = c.genre_id";
$result = mysql_query($query);
if (!$result) die ("Database access failed:" .mysql_error()) ;
$rows = mysql_num_rows($result);
echo '<table><tr><th>Title</th><th>Release year</th><th>Genre</th><th>Director</th><th>Update</th><th>Delete</th></tr>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr><td>' .$row["title"] . '</td>' ;
echo '<td>' .$row["release_year"] . '</td>' ;
echo '<td>' .$row["genre_id"] . '</td>' ;
echo '<td>' .$row["director"] . '</td>' ;
echo '<td>'."<a href='edit_movie.php?edit=" . $row["id"] . "'>Edit</a>".'</td>';
echo '<td><form action="index.php" method="POST">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="'. $row["id"] .'" />
<input type="submit" value="Delete" /></form>
</td></tr>' ;
}
echo '</table>';
?>
</body>
</html>
And here is the code on edit_movie.php page. The edit page with the form:
<!DOCTYPE html>
<html>
<head>
<title>My movie library</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="mall.css" />
</head>
<body>
<?php
require 'connect.inc.php';
//close MySQL
mysql_close($sql);
?>
<p>Edit movie</p>
<div id="form_column">
<form action="edit_movie.php" method="post">
<input type="hidden" name="id" value="<?php if (isset($row["id"])) ?>" /> <br>
Title:<br> <input type="text" name="title" value="<?php if (isset($row["title"])) { echo $row["title"];} ?>" /> <br>
Release Year:<br> <input type="text" name="release_year" value="<?php if (isset($row["release_year"])) { echo $row["release_year"];} ?>" /> <br>
Director:<br> <input type="text" name="director" value="<?php if (isset($row["director"])) { echo $row["director"];} ?>" /> <br><br>
Select genre:
<br>
<br> <input type="radio" name="genre_id" value="1" checked />Action<br>
<br> <input type="radio" name="genre_id" value="2" />Comedy<br>
<br> <input type="radio" name="genre_id" value="3" />Drama<br>
<br> <input type="radio" name="genre_id" value="4" />Horror<br>
<br> <input type="radio" name="genre_id" value="5" />Romance<br>
<br> <input type="radio" name="genre_id" value="6" />Thriller<br><br>
<input type="submit" />
</form>
</div>
</body>
</html>
The database connection is in a separate connect.inc.php file which is required at the top of these files. The code in the connect.inc.php file you can see below:
<?php
//connect to MySQL
$servername = "localhost";
$username = "root";
$password = "";
$sql = mysql_connect($servername,$username,$password);
mysql_connect($servername,$username,$password);
//select database
mysql_select_db("moviedata");
?>
Well, your code is kinda mess, because it's not even procedural. You're making problems for yourself. Really.
There are some things you must remember when developing an application using PHP:
Never print/echo html tags.
Try to avoid this as much as possible because this makes your code unmaintainable and unreadable. Use an alternate syntax instead.
That is, PHP should be used as a template engine itself, not "generate" the ones.
Separate responsibilities. Clearly and wisely
A functions which connect to a database should not be used in a presentation (in this case - HTML). You'd create one file which is responsible for database, another one which is responsible for data manipulation(such as DELETE, CREATE, UPDATE operations) and the like.
Don't forget about SQL injection & XSS
Never trust data you get from superglobals like $_GET, $_POST, $_COOKIE and $_REQUEST. At minimum, mysql_real_escape_string() should be used for each dynamic input you are going to deal with.
Generally speaking, XSS allows to execute any JavaScript code via aforementioned superglobals as well as injecting another html code within general markup. In order to prevent this, basically htmlentities() would be great enough here.
Wrap things into a function
So instead of doing this,
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = $_POST['id'];
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
You should re-write it like so:
function delete_movie_by_id($id){
return mysql_unbuffered_query(sprintf("DELETE FROM `movies` WHERE id='%s' LIMIT 1", mysql_real_escape_string($id)));
}
if ( isset($_POST['delete'], $_POST['id']) ){
delete_movie_by_id($_POST['id']); // it's safe & readable now
}
Learn about OOP and switch to PDO
Well, a procedural code is not the way to go when you're developing something like this. Next time you will be writing something, you'd really start using both PDO for database access and OOP.
I could go on, but it's better to stop now, and switch back to your original question.
Well, you didn't say which error exactly you get. For example, do you know if mysql_select() returns FALSE ( === failure on database selection), this won't terminate the script!? According to code you've posted, you do not "track it" in any way.
First
So, connect.inc.php should look like this:
error_reporting(E_ALL); // <-- Important!
$servername = "localhost";
$username = "root";
$password = "";
if ( ! mysql_connect($servername,$username,$password) ){
die(sprintf('Cannot connect to MySQL server because of "%s"', mysql_error()));
}
//select database
if ( ! mysql_select_db("moviedata") ){
die(sprintf('Cannot select a database, because of "%s"', mysql_error()))
}
Second
In edit_movie.php page, this code block, isn't required at all. The connection will be closed automatically when a script terminates.
So just remove this:
<?php
require 'connect.inc.php';
//close MySQL
mysql_close($sql);
Third
In that edit_movie.php, you're clearly asking: if ( isset($row['some_column']) )..., but what is it all about? Where's the $row itself? it wasn't defined anywhere, so you won't get what you expect. Here:
<input type="hidden" name="id" value="<?php if (isset($row["id"])) ?>" /> <br>
Title:<br> <input type="text" name="title" value="<?php if (isset($row["title"])) { echo $row["title"];} ?>" /> <br>
Release Year:<br> <input type="text" name="release_year" value="<?php if (isset($row["release_year"])) { echo $row["release_year"];} ?>" /> <br>
Director:<br> <input type="text" name="director" value="<?php if (isset($row["director"])) { echo $row["director"];} ?>" /> <br><br>
Okay, that's enough.
Consider, rewriting your application like this:
File: movie.inc.php
require_once('connect.inc.php');
/**
* Fetch all movies from a table
* #return array on success, FALSE on failure
*/
function get_all_movies(){
$query = "SELECT * FROM movies m INNER JOIN categories c ON m.genre_id = c.genre_id";
$result = mysql_query($query);
if ( ! $result ){
return false;
} else {
$return = array();
while ($row = mysql_fetch_assoc($result)){
$return[] = array('director' => $row['director'], 'genre_id' => $row['genre_id'], 'release_year' => $row['release_year'], 'title' => $row['title'], 'id' => $row['id']);
}
return $return;
}
}
function delete_movie_by_id($id){
// I already wrote this, see above
}
File index.php
<?php
require('movie.inc.php');
if ( isset($_GET['delete']) && isset($_GET['id']) ){
if ( delete_movie_by_id($_POST['id']) ){ //it's 100% safe
die('Movie has been removed. Refresh the page now'); // or the like
} else {
// could not - handle here
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My movie library</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="mall.css" />
</head>
<body>
<table>
<tr>
<th>Title</th>
<th>Release year</th>
<th>Genre</th><th>Director</th>
<th>Update</th>
<th>Delete</th>
</tr>
<?php foreach (get_all_movies() as $index => $row) : ?>
<tr>
<td><?php echo $row['title'];?></td>
<td><?php echo $row['release_year']; ?></td>
<td><?php echo $row['genre_id'];?></td>
<td><?php echo $row['director'];?></td>
<td><a href='<?php printf('edit_movie.php?edit=%s', $row['id']);?>>Edit</a></td>
<td>
<form action="index.php" method="GET">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="<?php echo $row['id'];?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
I'm tired now, hope you can get the core idea from this answer.
UPDATE
There are basic steps to make a movie "editable" :
1) You grab the data you are going to edit (from the table)
2) You send edited data back to the server (php script)
3) You validate the input
4) You run UPDATE query
That's all.
So it would be similar to this (File: edit_movie.php):
<?php
require_once('movie.inc.php');
/**
* Grabs the movie data by its id
*
* #param $id A movie id
* #return array on succes, FALSE if $id is wrong
*/
function get_movie_by_id($id){
$query = sprintf("SELECT * FROM `enter_movie_table_name_here` WHERE `id` = '%s' LIMIT 1", mysql_real_escape_string($id));
$result = mysql_query($query);
if ( ! $result ){
return false;
} else {
return $result;
}
}
function update_movie_by_id($id, array $data){
$query = sprintf("UPDATE `the_movie_table`
SET `director` ='%s',
`genre_id` = '%s',
`relase_year` ='%s',
`title` = '%s' WHERE `id` = '%s' LIMIT 1"),
mysql_real_escape_string($data['director']),
mysql_real_escape_string($data['genre_id']),
mysql_real_escape_string($data['relase_year']),
mysql_real_escape_string($data['title']),
mysql_real_escape_string($id) );
// not mysql_query() !!! but this
return mysql_unbuffered_query($query);
}
// Next thing is to get an id by query string,
// So if it was /movide_edit.php?id=1
// then id we have is 1
// So we need to handle that right now
if ( isset($_GET['id']) ){
$movie = get_movie_by_id($_GET['id']);
if ( ! $movie ){ // <- make sure that id isn't fake
die(sprintf('Invalid movie id "%s"', $_GET['id']));
}
} else {
die('Please supply an id you want to edit'); // <- this makes sence
}
// Ok, we'll reserve this block for an update
if ( !empty($_POST) ){ // This will run when user clicked on Save button
if ( update_movie_by_id($_POST['id'], array(
'director' => $_POST['director'],
'genre_id' => $_POST['genre_id'],
'relase_year' => $_POST['relase_year'],
'title' => $_POST['title']
)) ){
die('Movie has been updated');
} else {
die('Could not update a movie for some wicked reason..');
}
}
// That's all. Now it can:
//1) Fetch the data
//2) Edit accordingly
?>
<!DOCTYPE html>
<html>
<!--
This is kinda quick and dirty form
You need to fix this later
-->
<body>
<form method="POST">
<label for="title">Title</label>
<input type="text" name="title" value="<?php echo $movie['title']; " />
<!--
Add another elements this way..
-->
<button type="submit">Save</button>
</form>
</body>
</html>

PHP - How to submit a form containing input fields that point to different MySQL rows

I am setting up a form using this PHP that loops through all records a user may have:
<?php foreach ($items as $row): ?>
<tr>
<td>
<?php echo form_hidden('id', $row->id); ?>
</td>
<td>
<?php echo '<strong>' . $row->name . '</strong>'; ?>
</td>
<td>
<?php echo form_input('number', $number); ?>
</td>
<td>
<?php echo form_input('registry', $registry); ?>
</td>
<td>
<?php echo form_checkbox('OK', $ok, $ok); ?>
</td>
</tr>
<?php endforeach; ?>
This gives me a form with the following look:
The idea here is that each row belongs to a unique ID/row in the database, and I would like to allow the user to edit all on the same page/form, using a single submit button.
What would be the best way of implementing this?
When this data is submitted, there should be a way of looping through each packet of information (from each user) in my controller. Would this be done via ajax/json?
This does not use codeigntier, but you should be familiar with the general technique before attempting to use CI to shortcut this process. Codeigniter will help you with rendering the form elements, performing validation, escaping your input and performing your query - but it will only help you (do anything) if you understand the basic principles involved. Hope this helps
MARKUP
<form action="/process.php">
<div>
<h2>GORDON</h2>
<input type="text" name="user[1][number]" /> <!-- The number corresponds to the row id -->
<input type="text" name="user[1][registry]" />
<input type="checkbox" name="user[1][ok]" value="1" />
</div>
<div>
<h2>ANDY</h2>
<input type="text" name="user[242][number]" />
<input type="text" name="user[242][registry]" />
<input type="checkbox" name="user[242][ok]" value="1" />
</div>
<div>
<h2>STEWART</h2>
<input type="text" name="user[11][number]" />
<input type="text" name="user[11][registry]" />
<input type="checkbox" name="user[11][ok]" value="1" />
</div>
<input type="submit" />
PHP
$users = $_REQUEST['user'];
foreach ($users as $rowId => $info){
// YOU SHOULD MAKE SURE TO CLEAN YOUR INPUT - THIS IS A GUESS AT WHAT YOUR DATA TYPES MIGHT BE
$id = (int) $rowId;
$number = (int) $info['number'];
$registry = mysql_real_escape_string($info['registry']);
$ok = (int) ($info['ok']);
$q = "UPDATE user SET number = $number, registry = '$registry', ok = $ok WHERE id = $id";
mysql_query($q);
// You may want to check that the above query was sucessful and log any errors etc.
}
There's no need to use ajax mate.
For each put a hidden input with the ID of the row in this format:
<input type="hidden" name="id[<?= $row->id ?>]" value="<?= $row->id ?>" ?>
Do the same for each element in the tr, i.e. name them as
name="number[<?= $row->$id ?>]"
name="registry[<?=$row->$id ?>]"
name="ok[<?=$row->$id ?>]"
and once you post the FORM you can iterate each row with:
foreach ($_POST['id'] as $key => $value) {
echo $_POST['name'][$key];
}
You need to set up input-names as array-names, so you will send the whole form and may iterate over the entries.
e.g.
<?php
echo form_input('userdata[' . $row->id . '][number]', $number);
?>
which would possibly create an
<input name="userdata[1][number]" />
(I don't know where those form-functions came from…)
This will result in an array $_POST['userdata'] which may be iterated via:
foreach($_POST['userdata'] as $userId => $userInputFields)
{
$user = new User($userId);
$user->number = $userInputFields['number'];
// …
}

Categories