In my database users have a balance, im trying to set up a form that allows them to transfer amounts to each other. So for the from user it would - out of their current balance and update it to the new balance ( existing - amount transferred ) and for the receiver it would update ( existing + amount received ).
Heres my code below but its not updating any of the information:
<?php
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
$newmoney1 = ($res1['money'] + $_POST['amount']);
$newmoney2 = ($res2['money'] - $_POST['amount']);
$result1 = mysql_query("UPDATE `users` SET `money`='$newmoney1' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`='$newmoney2' WHERE username = '$fromuser'");
}
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.<br><br>
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['username']}'>{$row['username']}</option>";
}
$dropdown .= "\r\n</select></div><div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='text' name='amount' class='form-control margin-bottom-20'>
</div></div>";
echo $dropdown;
?>
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
<button type="submit" class="btn-u">Transfer</button>
</center>
</form>
All help much appreciated.
$_POST does not contain submit because you never put a NAME tag on the submit button.
Instead of:
<button type="submit" class="btn-u">Transfer</button>
You need:
<button type="submit" class="btn-u" name="submit">Transfer</button>
See here:
How do I post button value to PHP?
On further reflection it's probably a good idea to talk about some of the problems here, let's start with this one:
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
This is duplicated code, you can move this into a function to avoid copying and pasting, which is good practice, and you can use that function in other places in your code when you need to get the balance. Formatting the structure correctly helps in the event that your table changes, and you need to update the SQL. Without this in a single place, you are going to climb all over your code to find all the changes and update them.
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
This is very bad practice, as it makes it easy for someone to slip an extra variable into the header and submit whatever user they want to your code, transferring money out of any other account that they want. Since this page already has access to this variable:
$user_data['username']
You should be using this in the IF statement at the top, instead of submitting it along with the form.
<input type='text' name='amount' class='form-control margin-bottom-20'>
This is another problem. You are asking for an amount, but creating a text field. A better example of this would be:
<input type='number' name='amount' class='form-control margin-bottom-20'>
Again though, these are easily modifiable post values, you have to make sure to check again on the server to make sure you didn't get fooled:
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == ''))
The code above checks to make sure you have a numeric value, and that it is not 0 or blank, both of which would be invalid inputs. If either of those values is submitted, then it errors out and sends the user back to the form without processing the update.
Later on in your code, you start a PHP Tag to create the drop down:
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
Assigning all of this to the $dropdown variable is completely wasted if you aren't going to use that drop down again (and it seems you are not). I can see that you wrapped it in PHP so you can loop over the options to print them out, but you can do that just as easily with a smaller PHP tag with a loop inside it, like this:
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
Note that this option ALSO includes a default "null" value for the select menu, and filters out the existing user (you can't transfer money to yourself, at least in this example). The null value is necessary because without it your code would automatically select the first user on the drop down list.
This would be my implementation of the same set of code here:
<?php
// If our submit is set...
if (isset($_POST['submit'])) {
// Get the balance for the from user
$fromBalance = getBalance($user_data['username']);
// Get the balance for the to user
$toBalance = getBalance($_POST['touser']);
// Get our new amounts, but don't do anything yet!
$newmoney1 = $toBalance + $_POST['amount'];
$newmoney2 = $fromBalance - $_POST['amount'];
// Check to make sure we have a valid amount
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == '')) {
// Or error out!
echo 'ERROR: Bad amount Specified!';
// Check to make sure we have two valid users
} elseif($user_data['username'] == $_POST['touser']) {
// Or error out!
echo 'ERROR: Cannot transfer money to yourself!';
// Check to make sure sufficient funds are available
} elseif($newmoney2 < 0) {
// Or error out!
echo 'ERROR: Insufficient funds!';
// Check for default user selection...
} elseif($_POST['touser'] === 'null') {
// Or Error Out
echo 'ERROR: No username selected!';
// Otherwise we are good...
} else {
// So we call our update functions.
updateMoney($user_data['username'], $newmoney2);
updateMoney($_POST['touser'], $newmoney1);
// Send a success message
echo 'Transfer completed successfully, thank you!<br /><br />';
}
}
/** updateMoney()
*
* This function will take a user name and an amount and update their balance.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #arg $amount integer
*/
function updateMoney($user, $amount) {
// Update our database table for this user with this amount
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
}
/** getBalance()
*
* This function will return a balance for a given username.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #return $amount integer
*/
function getBalance($user) {
// Execute query to get the result
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
// Assign the result to a value
$res1 = mysql_fetch_array($balanceto);
// Return only the value we care about
return $res1['money'];
}
// Set our query for getting usernames from the DB
$query = "SELECT username FROM users";
// Get the usernames!
$result = mysql_query($query) or die(mysql_error());
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.
<br>
<br>
<div class='row'>
<div class='col-sm-6'>
<label>Transfer $ To<span class='color-red'> *</span></label>
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
</div>
<div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='number' name='amount' class='form-control margin-bottom-20'>
</div>
</div>
<button type="submit" class="btn-u" name="submit">Transfer</button>
</center>
</form>
But you STILL need to go fix the code so that you are NOT using MySQL and switch to MySQLi or PDO so that you can do prepared statements and actually protect yourself from MySQL injection attacks.
See here for more details:
https://wikis.oracle.com/display/mysql/Converting+to+MySQLi
You have posting the form with nameless button and trying to access via $_POST['submit']
<button type="submit" class="btn-u">Transfer</button>
name is missing. Add and try
<button type="submit" name="submit" class="btn-u">Transfer</button>
I think the button is missing tag 'name'. Try add this on your button:
<button type="submit" class="btn-u" name='submit'>Transfer</button>
To optimize your script I suggest do this:
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$result1 = mysql_query("UPDATE `users` SET `money`= `money` + '$amount' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`= `money` - '$amount' WHERE username = '$fromuser'");
}
So, you will eliminate two steps of processing and two hits on database.
start transaction
INSERT INTO power (sender, receiver, amount) VALUES ('$sender', '$receiver', '$amount')
UPDATE users SET power=power-$amount WHERE user_id='$sender'
UPDATE users SET power=power+$amount WHERE user_id='$receiver'
Submit button missing the name tag. use Transfer
Nothing glaringly wrong with the code, I'm assuming this is fake money.
Probably a malformed sql statement, try echoing the attempted sql before hand.
make sure all the queries work for a test example.
Related
Project: Create a simple CMS for a photography website. My first project in php. :)
Problem: I am 90% finished with the CMS, but have ran into an issue of not being able to UPDATE row data after being READ from database.
The Goal: What I am trying to achieve seems simple. I have an admin page that reads image data from a database (id, image) and I am using a while loop to display this. It works great, and so does the delete button.
<?php
$query = "SELECT * FROM photos";
$select_all_photos_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_all_photos_query)) {
$photos_id = $row['photos_id'];
$photos_image = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_alt = $row['photos_alt'];
echo "<tr>
<td><input type='checkbox' name='photo' value='photo'></td>
<td><img src='../images/$photos_image' width='70'></td>
<td><a class='edit' href='edit_photo.php?&p_id={$photos_id}'>Edit</a></td>
<td><a onClick=\"javascript: return confirm('Are you sure?') \"class='delete' href='admin.php?delete={$photos_id}'>Delete</a></td>
</tr>";
}
?>
The problem I am having is the Edit Button in my while loop. I am using a get method in my href to get the edit_photo.php page with a parameter named "p_id" that is = to $photos_id.
Once I click the Edit button it sends me to the edit_photo.php page and I see all of the CORRECT information which tells me it is reading it correctly. I do get a error at the bottom ( Notice: Undefined variable: photos_file) See code below.
<?php
if (isset($_GET['p_id'])) {
$photo_id = $_GET['p_id'];
// Send query to photos table in database. //
$query = "SELECT * FROM photos WHERE photos_id = $photo_id";
$result = mysqli_query($connection, $query);
// Grab unique row from photos table in database. //
while($row = mysqli_fetch_assoc($result)) {
$photo_file = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_desc = $row['photos_alt'];
}
}
?>
Now. Here comes the big problem. When I try to update this information, the program busts. I even checked to see if my sql is correct, and if the queries are connecting to database. See code below.
<?php
if (isset($_POST['image'])) {
// After "Save" is pressed, the values white space is trimmed and assigned to a variable. //
$photos_title = trim($_POST['photos-title']);
$photos_desc = trim($_POST['photos-description']);
$photos_file = $_FILES['image']['name'];
$photos_file_temp = $_FILES['image']['name_tmp'];
// The new variables are sanitized. //
$photos_title = mysqli_real_escape_string($connection, $photos_title);
$photos_desc = mysqli_real_escape_string($connection, $photos_desc);
}
// Send the Update query to the database. //
$update_query = " UPDATE photos SET
photos_image = '$photos_file', photos_title = '$photos_title', photos_alt = '$photos_desc'
WHERE photos_id = '$photo_id' ";
// Test the SQL syntax. //
if(!$update_query) {
echo "Wrong." . " " . mysqli_error($connection);
}
else { echo "The SQL appears right..." . "<br>";
}
// Test the Update query. //
$update_result = mysqli_query($connection, $update_query);
if(!$update_result) {
echo "Didnt Connect." . " " . mysqli_error($connection);
} else {
echo "Sent query to to database.";
}
?>
<form action="edit_photo.php" class="settings-form" method="post" enctype="multipart/form-data">
<div class="form-group edit-preview">
<label for="image">Photo</label>
<img src= <?php echo "../images/$photo_file"?> >
<input type="file" name="file_upload">
</div>
<div class="form-group">
<label for="photos-title">Title</label>
<input type="text" name="photos-title" value= <?php echo "$photos_title" ?> class="form-control">
</div>
<div class="form-group">
<label for="photos-description">Description</label>
<textarea type="text" rows="4" name="photos-description" class="form-control" ><?php echo "$photos_desc" ?> </textarea>
</div>
<div class="form-group">
<input type="submit" name="image" class="btn btn-primary" value="Save Photo">
</div>
</form>
I have spent four days trying to figure this out with no luck.
For one thing, it's failing because of this ['name_tmp'].
The syntax is ['tmp_name'] - you had those inversed
Ref: http://php.net/manual/en/features.file-upload.php so your temp file never gets processed.
Then as per your edit and seeing your HTML form:
You're using name="file_upload" and then using the $_FILES['image'] array; those names need to match.
Error reporting would have helped you here.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional note.
If you are attempting to set the given (file) column as binary data instead of the path to the given file(s) as text, then you MUST escape it.
Otherwise, MySQL will throw you an error.
If that is the case, you will need to do the same as the others:
$photos_file = $_FILES['file_upload']['name']; // notice I changed it to what it should be
$photos_file = mysqli_real_escape_string($connection, $photos_file);
as per <input type="file" name="file_upload">
Check for errors against all your queries; you're not doing that in your $query = "SELECT * FROM photos WHERE photos_id = $photo_id"; query.
Add or die(mysqli_error($connection)) to all mysqli_query() should there be an error somewhere.
HTML stickler.
<textarea type="text" - <textarea> does not have a "text" type; remove it.
Footnotes.
If you want to check if your UPDATE truly was successful, use mysqli_affected_rows().
http://php.net/manual/en/mysqli.affected-rows.php
Instead of else { echo "The SQL appears right..." . "<br>"; }
As outlined in comments, your code is open an SQL injection.
If $photo_id is an integer, change
$photo_id = $_GET['p_id'];
to
$photo_id = (int)$_GET['p_id'];
However, if that is a string, then you will need to quote it and escape it in your query.
I have a users.php where admin can see all registered users information and he is able to change their levels with a form that goes to edit_level.php.
It's not working properly, when I change the level of a user, it is affecting the wrong user.
This is my form in users.php (I didn’t include all the user info , just the level part)
$sql = "SELECT * FROM users ORDER BY username ASC";
$result = mysqli_query($conn,$sql) or die(mysqli_error());
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)){
$level = $row['level'];
<form method='post' action='edit_level.php?ed=$id'>
<input type='hidden' name='id' value='$row[id]'>
<input type='text' name='level' value='$row[level]'>
<input type='submit' name='submit' value='Change Level'>
}
This is edit_level.php
if(isset($_POST['submit'])){
$ed_id = $_GET['ed'];
$level = $_POST['level'];
$sql = "UPDATE users SET level ='$level' WHERE id='$ed_id'";
if(mysqli_query($conn,$sql)){
echo "<p>User Level has been sucessfully udpated! <a href='users.php'>Click here to return to User List.</a>";
}
else{
echo "<p><b>ERROR:User level has not been updated!";
}
}
Edit:
I actually just copied the same format of a delete function I have, but the delete was a link not a form.
<a href='deleteaccount.php?del=$id'>Delete</a> and then in the php:
$del_id = $_GET['del'];
$sql = "DELETE FROM users WHERE id='$del_id'";
Not sure how to do the same but with a form. I need a form because I want to be able to type a new value.
I think problem is wrong naming. Below on action attribute you are sending $id value with ed name, but on hidden input you are sending $id value with id name.
If you are using ?ed=$id on action why you are using hidden $id? Or if you are using hidden $id why you are using ?ed=$id on action area.
<form method='post' action='edit_level.php?ed=$id'>
<input type='hidden' name='id' value='$row[id]'>
You should remove ed or id then if your edit_level.php gets $id value by $_GET or $_POST you should fix it like below
edit_level.php
if you used hidden field you can get $id like $_POST["id"]
if you used edit_level.php?ed=$id you can get $id like $_GET["ed"]
Decide what you want. But don't forget to change you action page while you are doing these changes.
First of all this is my first question on here, and altohugh I have searched the site none of the answers I've seen resolve my current problem.
I am a PHP novice and am currently working on an end project for a course. The object is to make a rudimentary blog where users can post, delete and edit their news, admins can edit or delete everything etc. I am mostly doing fine, but am having a bit of trouble with the editing feature.
The following code displays all blog posts, their authors and dates of posting. If the currently logged in person is the author of a post or a admin, they have the option of deleting or editing each individual post. A small form appears that contains the title and post text. When the user types something else in clicking on the edit button should change the values in the database to the new values the user specified. The problem is that whenever i click on the edit button in the current setup, nothing happens. If i move the if statement outside of the other if statement, the posts do update, but become blank in the database.
Running print_r($_POST) after the fact shows that the array it builds has correct names and updated values, but still they aren't updated in the database. Here is the code, the pertinent part starts at the last if statement( I know, it isn't injection proof, will get to that as soon as it works):
$query = "SELECT id, title, body, pub_date, user_id FROM posts ORDER BY id desc";
$query_fetch = mysql_query($query);
while ($blog_post = mysql_fetch_assoc($query_fetch)) {
$author_id = $blog_post["user_id"];
$post_id = $blog_post["id"];
$post_id2 = $blog_post["id"] . 2;
$title = $blog_post['title'];
$body = $blog_post['body'];
$query = "SELECT username FROM users WHERE id = '$author_id'";
$query_run = mysql_query($query);
$author = mysql_fetch_assoc($query_run);
echo "<h2>" . censor($blog_post["title"]) . "</h2>" . "<br> <p> Autor: " . $author["username"] . "</p><br><p>Objavljeno: " . $blog_post["pub_date"];
if ($_SESSION['admin'] == 1 or $_SESSION['username'] == $author["username"]) {
echo "<form action='' method='POST'><input type='submit' name= '$post_id' value= 'Obriši objavu'></form>";
echo "<form action='' method='POST'><input type='submit' name= '$post_id2' value= 'Uredi objavu'></form>";
}
echo "<p>" . censor($blog_post["body"]) . "</p>";
if (isset($_POST["$post_id"])) {
$del_post = "DELETE FROM posts WHERE id = '$post_id'";
mysql_query($del_post);
}
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
}
}
Any help would be appreciated.
This last piece of code
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
}
gets activated when post_id2 is sent, but generates a form where post_id2 is not contained anymore. So when you submit that form, the IF is not entered.
You can modify it like this:
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
}
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
In general I think you would find it easier to use forms differently, specifically by using some sort of action tag:
input type="hidden" name="command" value="edit"
input type="hidden" name="post" value="{$post_id}"
This way you could run one single query immediately, without the need for browsing all the posts in a cycle.
One other useful possibility is to split your code between different PHP files, and keeping common code in one include:
<?php // this is delete.php
include "common.php";
$post_id = my_get_var('post_id');
my_sql_command("DELETE FROM posts WHERE...");
used from
<form action="delete.php" method="post" ...>
As you can see this allows for different ways of retrieving post_id (centrally defined in a single function my_get_var in common.php) and the central definition of SQL functions. How this function interfaces to MySQL can then be updated, specifically passing from mysql_ functions (which are deprecated, and soon will no longer be available) to e.g. PDO.
It also allows you to test a single command independently, by directly entering delete.php in the browser (you need for my_get_var to accept both POST and GET variables to do this).
Details
You want to inspect and/or modify a collection of posts. You then require initially at least the following operations: list, edit, and delete.
Only the first works against all posts.
So you could have a list.php file running the SELECT. Also, it is only in this SELECT that you need information about the user, so your query could become:
$query = "SELECT posts.id, title, body, pub_date, user_id, username FROM posts JOIN users ON (posts.user_id = users.id) ORDER BY posts.id desc";
In the display cycle we would display this information:
$query_fetch = mysql_query($query);
// This file will receive requests to edit or delete
// We can use a single form.
echo '<form action="manage.php">';
while ($post = mysql_fetch_assoc($query_fetch)) {
echo "<h2>" . censor($post["title"]) . "</h2>" . "<br> <p> Autor: " . $post["username"] . "</p><br><p>Objavljeno: " . $post["pub_date"];
if ((1 == $_SESSION['admin']) or ($_SESSION['username'] == $post["username"]) {
echo "<input type=\"submit\" name=\"Obriši objavu\" value=\"{$post['id']}\" />";
echo "<input type=\"submit\" name=\"Uredi objavu\" value=\"{$post['id']}\" />";
}
echo "<p>" . censor($blog_post["body"]) . "</p>";
}
echo "</form>";
This way you need only one form, and it will submit one field with a name describing the action to be taken, and the post on which to do it.
The file manage.php will then receive this information -- and can also be used to update it:
foreach(array(
"delete" => "Obriši objavu", // from list.php
"edit" => "Uredi objavu", // " "
"update" => "update" // from this file itself (see below)
)
as $test_todo => $var) {
if (array_key_exists($var, $_POST)) {
$id = $_POST[$var];
$todo = $test_todo;
}
}
if (isset($id)) {
switch($todo) {
case "delete":
mysql_query("DELETE FROM posts WHERE id = '{$id}'");
break;
case "edit":
// Get this post.
$query = "SELECT posts.id, title, body, pub_date, user_id, username FROM posts JOIN users ON (posts.user_id = users.id) WHERE posts.id = '{$id}';";
echo '<form action="manage.php" method= "POST">';
// This is how we tell this file what to do, and to what.
echo "<input type=\"hidden\" name=\"update\" value=\"{$id}\">";
// run query, fetch the one record, display info...
echo "</form>";
break;
case "update":
// Build the update query from $_POST.
mysql_query("UPDATE posts SET ...");
}
At first check that your query is correct. Then try to hard-code your query. Also test your query in phpMyAdmin Also you can try to remove the '' from your number variables on every query.
Please, can you give us your error?
There is a possibility also that your database has already been updated. So double check it.
This is how I usually debug. echo the query. Run it in PHPmyadmin, and see the error.
so, in your case.
echo "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
echo that and you will have the query that the script will be trying to run.
Try running it in phpmyadmin and check what the error is.
I tried to build an admin page. The admin will fill a form to add new product in the database and display it in the shop website. The problem is when I tried to select a gender from the dropbox, the new product doesn't add in the product table in the database as you can see below: (I want to select gender such as Boys)
The Admin Page and database result:
The code I used:
$host = "";
$userMS = "";
$passwordMS = "";
$connection = mysql_connect($host,$userMS,$passwordMS) or die("Couldn't connect:".mysql_error());
$database = "projectDataBase";
$db = mysql_select_db($database,$connection) or die("Couldn't select database");
if (isset($_POST['sAddProduct']))
{
addNewProduct();
}else if(isset($_POST['delete']))
{
$Product_ID=$_POST['Product_ID'];
$mysqlquery="delete from Product where Product_ID= ".$Product_ID."";
mysql_query($mysqlquery);
echo "Deleted successfully";
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}else{
showForm();
}
// add new product
function addNewProduct()
{
$ProductName = $_POST['Product_Name'];
$ProductPrice = $_POST['Price'];
$Gender = $_POST['Gender_ID'];
//database query to add product
$insertStringProduct = "INSERT into Product(Product_Name, Price,Gender_ID)
VALUE('$ProductName', '$ProductPrice', '$Gender')";
$result = mysql_query($insertStringProduct);
echo ("<p1>Product added Successfully</p1>");
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}
//function for the form page
function showForm()
{
//First form for adding new product
$self = htmlentities($_SERVER['PHP_SELF']);
echo("<form action = '$self' method='POST'>
<fieldset>
<legend>Adding New Product</legend>
Product Name: <input name='Product_Name' type='text' size = '40'>
<br /><br />
Price: <input name='Price' type='text' size = '20'><br><br />
Gender:
<select name='Gender_Description'>
<option value = '%'> <-- select--></option>");
$dbQuary = " SELECT DISTINCT Gender_Description from Gender";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[0]</option>");
}
echo("
</select>
<br/><br/>
<input type='submit' name='sAddProduct' value = 'Add'/>
<input type='reset' value='Clear' />
</fieldset>
</form>");
}
The result ( nothing added)
However, when I change the code to
Gender:
<select name='Gender_ID'>
<option value = '%'> <-- select--></option>");
$dbQuary = " SELECT DISTINCT Gender_ID from Gender";
$result = mysql_query($dbQuary);
It's working
Can anyone help me with this?
In addNewProduct you are expecting $_POST['Gender_ID'] to be set. So of course, <select name='Gender_Description'> would not work, because Gender_Description != Gender_ID. That's also why it does work when you change it.
I'm assuming what you want to achive is to display the gender description, and it still to work. For that, you need both the id and the description:
$dbQuary = " SELECT DISTINCT Gender_ID, Gender_Description from Gender";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[1]</option>");
}
Security
Your code is extremely unsafe. You are using mysql_* which is deprecated since 2013, and you are not sanitizing the input in any way, so your code is open to SQL injection (which is possibly in all kinds of queries; insert, update, delete, etc, and allows for data leaks, DOS, and possibly code execution and deletion/changing of data). The preferred way to prevent this are prepared statements (either using mysqli_* or PDO). They are not difficult to use, and the resulting code is also nicer.
You are not concatenating values as it should
Change
echo("<option value ='$row[0]'> $row[0]</option>");
to
echo("<option value =". '$row[0]' . "> ". $row[0]. "</option>");
OR
echo("<option value ='{$row[0]}'> {$row[0]}</option>");
EDIT:
Change your While-loop
while($row = mysql_fetch_array($result,MYSQL_BOTH)) {
echo("<option value ='{$row['gender_id']}'> {$row['gender_description']}</option>");
}
This will generate a Select list showing the Gender Description and and values will be numeric(of database)
This is my first php project. I have created a website where users can upload their picture and then view the pictures of other users, one person at a time (similar to the old hotornot.com). The code below works as follows:
I create an array (called $allusers) containing all members except for the user who is currently logged in ($user).
I create an array (called $usersiviewed) of all members who $user has previously either liked (stored in the likeprofile table) or disliked (stored in the dislikeprofile table). The first column of likeprofile and dislikeprofile has the name of users who did the liking/disliking, second column contains the name of the member they liked/disliked.
I use the array_diff to strip out $usersiviewed from $allusers. This is the list of users who $user can view (ie, people they have not already liked or disliked in the past).
Now the problem is when I click the like button, it updates the likeprofile table with the name of the NEXT person in the array (i.e., not the person who's picture I am currently looking at but person who's picture appears next). Additionally, if I refresh the current page, the person who's profile appears on the current page automatically gets 'liked' by me. I would really appreciate any advice on this.
<?php
// viewprofiles.php
include_once("header.php");
echo $user.' is currently logged in<br><br>';
echo <<<_END
<form method="post" action="viewprofiles.php"><pre>
<input type="submit" name ="choice" value="LIKE" />
<input type="submit" name ="choice" value="NEXT PROFILE" />
</pre></form>
_END;
$allusers = array();
//Create the $allusers array, comprised of all users except me
$result = queryMysql("SELECT * FROM members");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;
$allusers[$j] = $row[0];
}
//Create the $i_like_these_users array, comprised of all users i liked
$result = queryMysql("SELECT * FROM likeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_like_these_users[$j] = $row[1];
}
//Create the $i_dislike_these_users array, comprised of all users i disliked
$result = queryMysql("SELECT * FROM dislikeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_dislike_these_users[$j] = $row[1];
}
//Create the $usersiviewed array, comprised of all users i have either liked or disliked
if (is_array($i_like_these_users) && is_array($i_dislike_these_users))
{
$usersiviewed = array_merge($i_like_these_users,$i_dislike_these_users);
}
elseif(is_array($i_like_these_users))
{
$usersiviewed = $i_like_these_users;
}
else
{
$usersiviewed = $i_dislike_these_users;
}
// this removes from the array $allusers (i.e., profiles i can view) all $usersviewed (i.e., all the profiles i have already either liked/disliked)
if (is_array($usersiviewed))
{
$peopleicanview = array_diff($allusers, $usersiviewed);
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
else {
$peopleicanview = $allusers;
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
$current_user_profile = $peopleicanview[0];
echo 'check out '.$current_user_profile.'s picture <br />';
if (file_exists("$current_user_profile.jpg"))
{echo "<img src='$current_user_profile.jpg' align='left' />";}
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['choice']) && $_POST['choice'] == 'LIKE')
{
$ilike = $current_user_profile;
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$ilike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['choice']) && $_POST['choice'] == 'NEXT PROFILE')
{
$idontlike = $current_user_profile;
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$idontlike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
?>
Because when you refresh page it sends previus value of
Form again...and problem when u like a user it being liked next user.. There there is something in yor for loop while fetching row ...insted of for loop try once while loop ...i hope it will solve ur problem
You are calculating the $iLike variable with the currently loaded user and then updating the database with that user.
You should probably change your application logic a bit:
pass the user ID of the user you liked or did not like as a POST parameter in addition to the like/didn't like variable
move the form processing logic to the top of your page (or better yet separate out your form processing from HTML display)
Also, it's best not to use the mysql_* extensions in PHP. Use mysqli or PDO.
Try to make two different forms. One with "LIKE", another with "NEXT" to avoid liking from the same form
When you submit your form - your page refreshes, so in string $current_user_profile = $peopleicanview[0]; array $peopleicanview doesn't have user from previuos page (before submitting) you have to attach it, e.g. in hidden field
<form method="post" action="viewprofiles.php">
<input type="hidden" name="current_user" value="$current_user_profile" />
<input type="submit" name ="choice" value="like" />
</form>
<form method="post" action="viewprofiles.php">
<input type="submit" name ="go" value="next" />
</form>
and INSERT it later
"INSERT INTO likeprofile VALUES" . "('$user', '".$_POST['current_user']."')"
ps remove <pre> from your form
Lets start by simplifying and organizing the code.
<?php
// viewprofiles.php
include_once("header.php");
//if form is sent, process the vote.
//Do this first so that the user voted on wont be in results later(view same user again)
//use the user from hidden form field, see below
$userToVoteOn = isset($_POST['user-to-vote-on']) ? $_POST['user-to-vote-on'] : '';
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['like']))
{
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['dislike']))
{
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
//now we can create array of available users.
$currentProfileUser = array();
//Create the $currentProfileUser array,contains data for next user.
//join the 2 other tables here to save php processing later.
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
and `user` <> '$user'
LIMIT 1");
//no need for a counter or loop, you only need the first result.
if(mysql_num_rows > 0)
{
$row = mysql_fetch_assoc($result);
$current_user_profile = $row['user'];
}
else
$current_user_profile = false;
echo $user.' is currently logged in<br><br>';
//make sure you have a user
if($current_user_profile !== false): ?>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="like" value="LIKE" />
</form>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="dislike" value="NEXT PROFILE" />
</form>
check out <?=$current_user_profile?>'s picture <br />
<?php if (file_exists("$current_user_profile.jpg")): ?>
<img src='<?=$current_user_profile.jpg?>' align='left' />
<?php endif; //end check if image exists ?>
<?php else: //no users found ?>
Sorry, there are no new users to view
<?php endif; //end check if users exists. ?>
You'll notice I changed the code a lot. The order you were checking the vote was the main reason for the issue. But over complicating the code makes it very difficult to see what's happening and why. Make an effort to organize your code in the order you expect them to run rather a vote is cast or not, I also made an effort to separate the markup from the logic. This makes for less of a mess of code to dig through when looking for the bug.
I also used sub queries in the original query to avoid a bunch of unnecessary php code. You could easily have used JOIN with the same outcome, but I think this is a clearer representation of what's happening. Also please use mysqli instead of the deprecaded mysql in the future, and be aware of SQL injection attacks and makes use of real_escape_string at the very least.
Hope it works out for you. Also I didn't test this code. Might be a few errors.