PHP values don't UPDATE mysql table - php

In my first php file I fetch results from mysql and show them in table. Every row value in one column must have value "Yes" or "No". When adding new request that value is "No". On "No" click I want to open another php (zatvaranje_zadatka.php) and send id_zadatka and broj_zadatka to new php file with form to input solution of request. On Submit in new php file I want to change flag in mysql table1 to "Yes" and write solution to another table in mysql.
In short notes in first php:
while ($row = mysql_fetch_array($result))
{
echo '<tr><td>' .$row["id_zadatka"] .'</td>';
echo '<td>Zatvori</td>';
}
In zatvaranje_zadatka.php I have:
$id_zadatak = isset($_GET['id_zadatka']) ? $_GET['id_zadatka'] : '';
$br_zht = isset($_GET['broj_zadatka']) ? $_GET['broj_zadatka'] : '';
if($id_zadatak != '') {
echo '<form action="zatvaranje_zadatka.php?go.php" method="POST" id="zatv_zad" name="zatv_zad">';
echo '<fieldset>';
echo ' Broj zadatka je:';
echo '<legend>Rješenje zadatka</legend>';
echo ' <textarea id= "rjesenje" name = "rjesenje" rows="4" cols="50"></textarea>';
echo '</fieldset>';
echo '<button type="submit" id="submit_zatv" name="submit_zatv"> Zatvori zadatak </button>';
echo '</form>';
$rjesenje = isset($_GET['rjesenje']) ? $_GET['rjesenje'] : '';
$query2 = "INSERT INTO rjesenje(broj_zadatka, rjesenje_zadatka) VALUES ('$br_zht', '$rjesenje')";
$result2 = mysql_query($query2) or die ("Nije uspio zapis u bazu" .mysql_error());
}
Output to table rjesenje is nothing.

This all code looks messy and questionable, but you might try this for testing in order to figure out how this all is working at the end..
$id_zadatak = $_GET['id_zadatka']; // we set this via URL
//$br_zht = $_GET['id_zadatka']; // id i broj su ista stvar
$rjesenje = $_POST['rjesenje'];
if($id_zadatak != '') {
echo '<form action="zatvaranje_zadatka.php?id_zadatka='.$id_zadatak.'" method="POST" id="zatv_zad" name="zatv_zad">';
echo '<fieldset>';
echo ' Broj zadatka je:';
echo '<legend>Rješenje zadatka</legend>';
echo ' <textarea id= "rjesenje" name = "rjesenje" rows="4" cols="50"></textarea>';
echo '</fieldset>';
echo '<button type="submit" id="submit_zatv" name="submit_zatv"> Zatvori zadatak </button>';
echo '</form>';
if(isset($rjesenje))
{
$query2 = "INSERT INTO rjesenje(broj_zadatka, rjesenje_zadatka) VALUES ('$id_zadatak', '$rjesenje')";
$result2 = mysql_query($query2) or die ("Nije uspio zapis u bazu" .mysql_error());
}
}

This is probably due to a typo. You need to leave a space between your table name and the row names. (e.g. rjesenje_(broj_zadatka, rjesenje_zadatka))
But whats worse is that your database is vulnerable for SQL injections. Please take a look at prepared statements

Your form is method="POST" and you check for $_GET variables. Thus the error rjesenje is empty. This should have resulted in an error, however you checked whether or not $_GET['rjesenje'] was set. It was not, thus the value of the variable is nothing, as specified when you check if it's set.
$rjesenje = isset($_GET['rjesenje']) ? $_GET['rjesenje'] : '';
returns false => $rjesenje = nothing
change the line to the following:
$rjesenje = isset($_POST['rjesenje']) ? $_POST['rjesenje'] : '';
To solve the problem, either change the request method of the form to method="get" or check for $_POST variables instead, as suggested above.
One way to check if this is true, you could try printing out the variables while debugging:
print_r($_GET);
or
print_r($_POST);
Make sure that you have your errors on while debugging
error_reporting(E_ALL);
read more: How to get useful error messages in PHP?
Additionally, I'd like to advise you to use mysqli or pdo functions instead of mysql. As mysql functions are deprecated as of php version 5.5 and completely removed in php 7.0, and because mysql functions are prone to attacks.
http://php.net/manual/en/intro.mysql.php

Related

Check submit form input with mysqli database

When I type a code into my form I want my PHP code to check on submit that the code exists in the database and then run MySqli query. I have tried to do that but I get error Cannot use isset() on the result of an expression (you can use "null !== expression" instead) I have Googled the problem but not a single one did help me to solve or understand my problem.
FORM
<p><b>Skriv in din laddkod nedan och tryck på "Ladda"</b></p>
<form action="laddaklar.php" method="post">
<input type="text" name="laddkod"/>
<input type="submit" name="submit" value="Ladda" />
</form>
PHP
<?php
session_start();
$mysqli = NEW MySQLI ('localhost', 'root', '', 'ph');
$laddkod = isset($_POST['laddkod']) ? $_POST['laddkod'] : '';
$kod= "SELECT refill from card_refill";
$result = $mysqli->query($kod);
if(isset($_POST['submit'] && $laddkod==$result)){
$resultSet = $mysqli->query ("UPDATE card_credit SET value= value + (select credit from card_refill WHERE refill='" . $_POST['laddkod'] . "') WHERE card_id = '" . $_SESSION['card'] . "' ");
echo "<b>Ditt kort har laddats!</b>";
}
else
{
echo "Fel laddkod";
}
The error that you're getting:
Cannot use isset() on the result of an expression
Is caused by what looks like an attempt to use an expression here:
if(isset($_POST['submit'] && $laddkod==$result)){...
You have to close the isset() properly and remove the spurious extra ):
if( isset($_POST['submit']) && $laddkod==$row['refill'] ){...
-----------------------add^ --------------------remove^
Furthermore you're not fetching any row results for the first query:
$kod= "SELECT refill from card_refill";
$result = $mysqli->query($kod);
$row = $result->fetch_assoc(); // The value will be in the $row array
Then you appear to never execute the UPDATE query.
Additionally it is not clear where you're setting $_SESSION['card'], but you will want to make sure it is set before attempting the UPDATE query.

PHP Gallery CMS - Cannot Update Row in PHPMyadmin (LONG)

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.

Taking data from a sql query in php and sending it to another php

So, i have a php page that makes a combobox by taking data from a database. After i interrogate the database i want to save the selection and send it to another php page. But, the problem is it doesn't reach it.
<form action ="sending.php" method="POST" >
<?php
$link = mysql_connect('localhost', 'root', '','printers');
mysql_select_db("printers", $link);
$query = "SELECT name_printer FROM insurers";
// Execute it, or return the error message if there's a problem.
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<select name='users' class='dropdown-menu'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['name_printer']}'>
{$row['name_printer']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
<br><br>
<input type="hidden" name="selected_text" id="selected_text" value="" />
<input type="submit" name="search" value="Search"/>
</form>
And the sending.php
<?php
if(isset($_POST['search']))
{
$makerValue = $_POST['users']; // make value
$maker = mysql_real_escape_string($_POST['selected_text']); // get the selected text
var_dump( $maker);
}
?>
What it prints is string(0) "".
Your issue is with the $maker variable, it is set from an escaped $_POST['selected_text'] which if you look in the html the value is set to value="", so by var_dumping it you would not receive any output.
What you should do instead is use mysql_real_escape to escape the $makerValue rather than $_POST['selected_text'].
That way it will dump the data received from the database.
Actually you are already getting selected_text from bellow statement :
$makerValue = $_POST['users'];
So you can use bellow code directly :
$maker = mysql_real_escape_string($_POST['users']);
One more thing,
mysql_real_escape_string()
is deprecated as of PHP 5.5.0

form with array of checkboxes send incomplete data

I try to pass a form which contains other forms (same inside forms, dynamic) , but I have checked that the data which are sent to the 'script handler' (php) are incomplete data. I think somewhere buffer is overwriting or something. Here is the code :
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
if($number== 0)
{
header('Location: /ceid_coffee/user_order_form.php');
}
else
{
$_SESSION['number'] = $number;
echo '<form action="user_order_form.php" method="POST">';
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<br>';
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
}
echo '<br>';
}
echo '<input type="submit" name="submit" value="FINAL_ORDER">';
echo '</form>';
}
}
?>
And this is the handling script:
<?php
if (isset($_POST['submit']))
{
$number= $_SESSION['number'];
$item = $_SESSION['item'];
$max_id = "SELECT MAX(id_order) FROM id_of_orders";
$x=mysql_query($max_id) or die("my eroors");
$id= mysql_fetch_array($x);
$xyz = $id['MAX(id_order)'];
for($i=0;$i<$number;$i++)
{
$temp = $_POST['yliko'][$i]; // <~~~~ this line is the form's data
$temp2 = implode("," , $temp);
$inserts = ("INSERT INTO orders (order_id,product,ulika) VALUES ('$xyz' , '$item','$temp2')");
$inc_prod=("UPDATE proion SET Counter = Counter + 1 WHERE proion.onomasia='$item'");
mysql_query($inserts) or die(mysql_error());
mysql_query($inc_prod) or die(mysql_error());
}
}
?>
This line here contains the data of each form , but i have echo them ($temp2) and i saw that they are incomplete.
$temp = $_POST['yliko'][$i];
If i select more than 1 checkbox for each item ($i) I get only one value from the checkboxes into the sql.
Do you see if I miss something ?
Ok i found the error. I replace this row :
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
with this row :
echo '<input type="checkbox" name="yliko['.$i.'][]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
I do not know how (i'm new to php) but it worked.
You will only get one value for each form because you are assigning the value of $i to each one:
echo '<input type="checkbox" name="yliko[][$i]" value='. etc.
is your problem line.
Have a look at the HTML that your code produces (ctrl-u in most browsers) and you will see why you get the wrong answer. All your checkboxes need to have unique names.
I would do it by assigning each checkbox a name that relates to the line in the database from which they are drawn eg:
name="checkbox_"'.$row['ylikaprimarykey']."etc.
This will get you up and running fairly quickly. For what it is worth, the ids of your table keys can give attackers information about your site so it is best practice to obfuscate them in some way. There are a number of excellent classes available free on the net that will do this for you.
If you really need to deal with what would have been in each form as a separate chunk of data, you can easily change the checkbox names vis:
name="checkbox_$formnumber_$obfuscatedkeynumber"
then loop through them with nested loops in your handling page.

Trying to use query variable and form data to change tables in database

So as said in title I'm trying to use the query variable given from the page which directs to this one and the form data from THIS page to manipulate the database. I can't seem to get it right and I have no idea what I'm doing wrong. The code snippet looks like this:
<?php
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php' method='post'>";
Echo 'Username:<br>';
Echo '<input type="text" name="usernamecheck" size="14"><br>';
Echo 'Password:<br>';
Echo '<input type="password" name="passwordcheck" size="14"><br>';
Echo '<input type="submit" value="Send">';
Echo '</form>';
if (isset($_POST['usernamecheck'])) {
$sql2 = "SELECT * FROM `storedata`.`users` WHERE `username` LIKE '$_POST[usernamecheck]'";
$found_user_id = mysql_query($sql2, $conn);
print $found_user_id;
}
if (isset($_POST['usernamecheck'])) {
$sql3 = "INSERT INTO `storedata`.`basket` (user_id, ware_id, number, complete)
VALUES
('$found_user_id', '$ware_number', 1, 0)";
$derp = mysql_query($sql3, $conn);
print $derp;
}
?>
The document itself is usernamecheck.php, and I was just printing to try and locate the error. When i check the basket table nothing has happened, even though no error is displayed. Right now the variable $ware_number is causing errors. What am I doing wrong?
I have also made user_id and ware_id foreign keys in the storedata.basket table, since they are primary keys in their own respective table. This means they can only be specific values, but I'm testing with these values, primarily 1's and 0's...
What if $_GET['id'] is not set? it will fail. Also please read up into correct usage of SQL in PHP. Your code is vulnerable to SQL injection attacks and whatnot.
EDIT:
updated piece of code
if(isset$_GET['id'] && is_numeric($_GET['id']))
{
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php?id=" . $_GET['id'] . "' method='post'>";
.....

Categories