Getting data from POST [id] form in PHP - php

On a table that displays data from a database, I have a form that has a text area on which a user can type a receipt number and submit to save in a database for a specif row. The PHP code below is what updates the database after the form is submitted.
I want to pick the rest of the details for the specific row so I used the $_POST['id'] on which the receipt has been submitted. The id is the primary key. I'm however having a challenge since I can't fetch data from the database using $id = $_POST['id'];I created before outside the function The update statement works perfectly but the SELECT STATEMENTdoesn't . How do I go about it? Any one?
if(isset($_POST['submit'])) {
$rec = $_POST['receipt'];
$id = $_POST['id'];
//reate connection
$sql = "UPDATE customer SET `receipt` = '".$_POST['receipt']."', `date_entered` = NOW(), `receipt_lock` = 1 WHERE `id` = '".$_POST['tid']."' AND receipt_lock = 0";
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit();
$conn->close();
}
function wall(){
global $recp;
global $id;
// Create con
$sql = "SELECT * FROM customer WHERE id ='$id'";
$result1 = mysqli_query($conn, $sql);
$resultarr = mysqli_fetch_assoc($result1); // fetch data
$name = $resultarr['name'];
echo "$name"; //Does not display
$amount = $resultarr['amount'];
$transaction_id = $resultarr['trans_id'];
$date = $resultarr['time_paid'];
}
else {
echo "this is not right!;
}
wall();

Ignoring all the (valid) questions about SQL security and just addressing your problem - how about passing the $id variable as a parameter to your wall function.?
wall($id);
function wall($id){
$sql = "SELECT * FROM customer WHERE id ='$id'";
// ... use prepared statements for security...
...
}

Looks like you are using $_POST['tid'] instead of $_POST['id'] or $id in your SQL-query.

What you are doing there is a big nono, in terms of security. Make sure you escape your POST parameters before adding them inside your query.
$id = $_POST['id'];
$id = mysqli_real_escape_string($conn, $id);
http://php.net/manual/ro/mysqli.real-escape-string.php
Think about sending data as parameters of a function function wall($id) instead of a global parameter.

Related

Update two tables in one query

I can't update two table in one query. Is there any other way to do it? below is an example of my code.
$id = $_GET['idnum'];
$txtEditUsername=$_GET['txtEditUsername'];
$txtlname=$_GET['txtlname'];
$txtfname=$_GET['txtfname'];
$txtgender=$_GET['txtgender'];
$txtbdate=$_GET['txtbdate'];
$txtnationality=$_GET['txtnationality'];
$txtcnum=$_GET['txtcnum'];
$txtaddress=$_GET['txtaddress'];
$sql = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
$sql = "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname', ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (mysqli_query($conn, $sql)) {
} else {
echo "Error ".mysqli_error($conn);
}
You can use mysqli_multi_query like this
$sql = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
$sql .= "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname',
ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (mysqli_multi_query($conn, $query)) {
do {
/* sStockage du premier résultat */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* Affichage d'une séparation */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
}
} while (mysqli_next_result($conn));
}
And here you can know more about it https://www.php.net/manual/en/mysqli.multi-query.php
You should use different name for variables like $sql and $sql2, but you can even use one query, try this:
UPDATE users, people
SET users.u_username = '$txtEditUsername',
people.ppl_lname = '$txtlname',
people.ppl_fname = '$txtfname',
// AND SO ON
WHERE
users.u_uid = '$id'
AND people.ppl_id = '$id';
EDIT
However, like someone else said, you can be victim of sql injection.
Try to use prepared statement with PDO, give a look here
The problem is here:
$sql = "UPDATE users ...";
$sql = "UPDATE people ...";
You are using the same variable to execute two different queries. The second statement overrides the first one, erasing it. That's why the users table isn't updated.
$usersSQL = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
if (!mysqli_query($conn, $usersSQL)) {
echo "Error while updating users table: ".mysqli_error($conn);
// Eventually, consider to exit the function..
}
$peopleSQL = "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname', ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (!mysqli_query($conn, $peopleSQL)) {
echo "Error while updating people table: ".mysqli_error($conn);
}
Last but not least
Never ever use unsanitized data. Always filter and validate user's data.
Adding validation, you'll avoid passing invalid values to the query (example: ppl_lname's length is maximum 50 chars, and user sends 51 chars).
And most important, NEVER use user's data directly to a SQL query, because you are exposing your database to a serious risk.
Give a read to this link, or this one, they will explain what's the problem when using unsanitized data.

Reusable Delete PHP Statement?

I was wondering how to make my code less cluttered and more re-usable. I have seperate delete.php files for deleting specific data from pages. For example I have Genre,Platform and Customers.
Genre Delete
//get value of ?id= from the url
$DeleteID = $_GET['id'];
echo $DeleteID;
require("connect.php");
//Linking
$link = connectToDB();
//SQL Query
$sql = "DELETE
FROM Genre
WHERE GenreID = ".$DeleteID;
//Execute
$result = $link->query($sql);
//Check
if ($link->affected_rows == 1) {
header( "Location: genre.php" );
}
else {
echo "Didn't Work";
}
Platform Delete
<?php
session_start();
//get value of ?id= from the url
$DeleteID = $_GET['id'];
echo $DeleteID;
require("connect.php");
//Linking
$link = connectToDB();
//SQL Query
$sql = "DELETE
FROM Platform
WHERE PlatformID = ".$DeleteID;
//Execute
$result = $link->query($sql);
//Check
if ($link->affected_rows == 1) {
header( "Location: platform.php" );
}
else {
echo "Didn't Work";
}
I wanted to know if it was possible for these to be made into 1 delete file that I can alter, or statement. The user is redirected to these pages through a button in a table, and it redirects to the delete page with the PK ID of the record.
You could pass another variable into the URL to indicate what you want to be deleted (Genre, Platform, Customers, etc.).
Granted, it becomes very easy to create a mess of if/else statements, but it would keep all the functionality limited to one file.
you could write a small helper function:
function deleteMe($link, $table, $id){
//SQL Query
$id = intval($id);
$sql = "DELETE
FROM `$table`
WHERE `{$table}ID` = ".$id;
//Execute
$result = $link->query($sql);
return $link->affected_rows;
}
You could then include this on a single delete page and use it as needed, passing your table and id in with GET params.

Prevent Form from inserting data multiple times into database

Trying to insert form data into mysql database, my issues is as the user submits the form the data gets inserted twice into database. I know that I am doing something wrong with my 2nd query $query_file = "INSERT INTO upperbit_files... statment as when I remove the whole if loop if(mysqli_query($dbc, $query_info)){...} the form gets submitted once as expected.
Basically I need to insert data into 2 tables. One is for general product info and the other one is to store photos relating to that product both the table are connected via a global variable $advert_id. I am using 2 separate queries
Table1: advert_sell_category1, is for general product info
Table2: upperbit_files, is to store details of the images uploaded
But for some reason the 1st query relating to general product info is getting inserted twice into database and the irony is both the time the $advert_id is the same. Below is my code and a screenshot of the database for your understanding,
if(isset($_POST['postad'])){
$adtype = $_POST['offering_type'];
$manufacturer = mysqli_real_escape_string($dbc, $_POST['manufaturer']);
$mediafile = mysqli_real_escape_string($dbc,$_POST['mediafile']);
$GLOBALS['advrt_post_id'] = crypto_rand_secure(10, 100000);
$query_info = "INSERT INTO advert_sell_category1(advert_id,manufacturer,image_file)
VALUES('$advrt_post_id','$manufacturer','$mediafile')";
$result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));
if(mysqli_query($dbc, $query_info)){
$last_id = mysqli_insert_id($dbc);
$query_link_id = "SELECT advert_id FROM advert_sell_category1 WHERE id = '$last_id' ";
$result_id = mysqli_query($dbc, $query_link_id);
while ($row = mysqli_fetch_assoc($result_id)) {
$link_id = $row['advert_id'];
if(!empty($mediafile)){
$media_file = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafile']));
$media_file = array_filter($media_file);
$media_file_size = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafilesize']));
$media_file_size = array_filter($media_file_size);
$media_file_type = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafiletype']));
$media_file_type = array_filter($media_file_type);
for ($var = 0; $var < sizeof($media_file); $var++){
$query_file = "INSERT INTO upperbit_files(file,size,type,link_id) VALUES ('$media_file[$var]','$media_file_size[$var]','$media_file_type[$var]','$link_id')";
$result_file = mysqli_query($dbc, $query_file) or die(mysqli_error($dbc));
}
}
}
}
/********** Your Code ************/
$result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));
if(mysqli_query($dbc, $query_info)){
/**********************/
See here in if statement you are calling mysqli_query() second time so same data is inserted twice. Use following code to solve your problem
/********** Suggested Code ************/
$result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));
if(mysqli_affected_rows()>0){
/**********************/

deleting records from mysql table

Continuing with my simple CRUD, I'm stuck again...
So I have a table created called "usuaris" and a column called "id" which is my auto-increment and then another column called "usuari_nom". Now, I want to add "delete function", so when I am displaying the records of my table I've added a to delete it:
<div id="main">
<?php
global $conn;
$query = "SELECT * FROM usuaris";
if($grup_usuaris = mysqli_query($conn, $query)) {
echo "<table>";
echo "<tr><th>Usuaris</th><th>Accions</th></tr>";
while($row = mysqli_fetch_assoc($grup_usuaris)) {
echo "<tr><td>" . $row['usuari_nom'] . "</td><td>Eliminar usuari</td></tr>";
}
echo "</table>";
echo "+ Afegeix Usuari";
mysqli_free_result($grup_usuaris);
} else {
echo "query failed";
echo("Error description: " . mysqli_error($conn));
}
?>
</div>
So now, If I click on "eliminar usuari" it goes to the file where I am adding the query to delete, plus the id of that user; for example: "http://localhost/calendario/elimina_usuari.php?subject=6". But then, in the file elimina_usuari.php, how do I select the id to know what record to delete?
I've thought with $_GET but it doesn't seems to work, either with $_POST:
elimina_usuari.php
<?php
global $conn;
$usuari_id = $_GET['id'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
Any clue how can I get its id? Should I take it from the url somehow?
Thanks
you're doing fine.
just need to change this
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
as you're setting subject instead of id in your url
http://localhost/calendario/elimina_usuari.php?subject=6
^
and if you want to process id, like $_GET['id'], you need to change URL.
"http://localhost/calendario/elimina_usuari.php?id=6"
^ change here
EDIT
as per your comment,
you can use any $variable to $_POST or $_GET, it has nothing to do with the database column name.
Like you can use following.
"http://localhost/calendario/elimina_usuari.php?eve_mf=6"
and on elimina_usuari.php page,
$id = $_GET['eve_mf'];
and second part, why can I do that and I don't need to call it id as it is called in my db table?
Again, it's not the issue what you call variables in you local environment, all you to do(and should take care of) is to put right parameters in your sql query.
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
Here id is the name of your column name in your database. You can't change it here if you even want it to.
however, $usuari_id is your local variable, and you can change it whatever you want.
Hope I've explained what you're looking for :)
You can get the id with $_GET['subject'].
Please be aware about SQL injection as you are wrongly get the id of the user to be deleted:
$usuari_id = mysqli_real_escape_string($conn, $_GET['subject']);
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
You just need to Get the exact variable name or parameter name which you have sent with your url
I mean see your url contains subject=6
that means you have to get subject instead of id;
please replace this code
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
try this in elimina_usurai.php
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>

Is this coding wrong it's not working properly

The below script inputs data to a database this takes some information from a form then stores them in to the database. And I'm also using uplodify to upload a image file and store the file name in the database but my issue is this data processing script keeps updating the row ID one never jumps to the second line I tried every thing can some one help me with this or show me what I'm doing wrong.
Also this checks the ID and if it's not equal to 1 then does an insertion if it's equal then update it but this not happening.
The ID is auto incrementing.
My script
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM poiinfo ORDER BY ID DESC LIMIT 1");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
//$poiId = $_REQUEST['pID'];
if($row['ID'] != "1"){
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon'";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
I tried u r suggestions but it's still the same now my code for the update is looks like this.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE `ID`='".$row['ID']."'";
But still it keeps up dating the ID 1 not moving on to the next one.
Your update query is missing a WHERE clause. Try this:
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE ID = '".$row['ID']."'";
Also be beware of MySQL Injections: http://en.wikipedia.org/wiki/SQL_injection
To check why your update failed, you should call mysql_error in your last else clause :
} else {
echo mysql_error();
}
As for the first problem : if you never insert a new record (I don't see how that could happen, provided your code), you will never have a record whose ID is 2.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon'";
You need a where clause in this sql to specify a record to update. Currently it is updating all records.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE `ID` = ".$row['id']";";
You will need to set an $id variable for this to work.

Categories