Update two tables in one query - php

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.

Related

Getting data from POST [id] form in 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.

SQL/PHP Multiple querys

I don't understand this because I'm just getting into query's and php.
I'm trying to get the user's ID from the database and set that equal to a different users friendreq column.
Don't worry about me not escaping properly, this is only a test so I can practice! Thank you! (Although I'm not sure what escaping is, I'm going to do my research!)
$usernameID = "SELECT Id FROM Users WHERE Username = '$username'";
$sql = "UPDATE Users SET FriendReq = $usernameID WHERE Username = '$usernamebeingreq'";
$result = mysqli_multi_query($con, $usernameID, $sql);
if(!$result)
{
echo 'Failed';
}
else
{
echo 'Friend added!';
}
According to the PHP reference of mysqli_multi_query your two queries need to be concatenated with a semicolon. You're passing each query as its own parameter.
Use the following instead:
$result = mysqli_multi_query($con, $usernameID . "; " . $sql);
This will concatenate your two queries, so that it's the following:
SELECT Id FROM Users WHERE Username = '$username'; UPDATE Users SET FriendReq = $usernameID WHERE Username = '$usernamebeingreq'

Database not updating row

Before you assume I didn't establish a database connection, I did. the only portion of the code that does not update is the if empty statements.
All the values can be echoed out correctly, it's just that query doesn't work.
This is in directory config and named stuff.php
$user = $mysqli->real_escape_string($_SESSION['username']);
$user_query = "SELECT * FROM users WHERE username = '$user'";
$result = $mysqli->query($user_query);
$row = $result->fetch_assoc();
$referrer = $row['ref'];
$refearn = $row['refearn'];
verify.php
include('config/stuff.php');
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Get Real IP
$IP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$IP = $_SERVER['REMOTE_ADDR'];
}
if ($IP=="external server ip here") {
if (!empty($referrer)){
$mysqli->query("UPDATE users SET points=points+10, refearn = refearn+10 WHERE username='".$referrer."'") or die(mysqli_error($mysqli));
}
$mysqli->query("UPDATE users SET points=points+".$earnings.", completed = completed+1 WHERE username='".$subid."'") or die(mysqli_error($mysqli));
}
My guess is you could try to retrieve the value of points through a query then add to it so you're just updating to a simple value. However, if mysql_error() is returning an error, it should be easier to figure out.
Example:
$getPoints = mysql_query("SELECT points FROM table WHERE condition");
$points = mysql_result($getPoints, 0, "points");
$update = mysql_query("UPDATE table SET points=" . ($points+10) . " WHERE condition");
Hope that helps. Another consideration, though. Why use an endif structure unless you're breaking PHP tags to display content?
try this:
$mysqli->query("UPDATE `users` SET `points`=`points`+10, `refearn` = `refearn`+10 WHERE `username`='".$referrer."'") or die(mysqli_error($mysqli));
Hope this helps. What I think is, mysql query might be taking those as constant - not as the mysql rows. Try that

MySQL query is running but not running

Alright let me explain myself here:
I am making an online text based game. I have a page where 3 things can happen:
They can create a position
Can edit a position
Can delete a position
So far I have creating a position working. I moved on deleting a position next. All was good and I got no errors, no warnings, etc.. And when I ran it, it came back to the screen it was supposed to after the script to delete the position ran. It is only supposed to come here after the query runs.
Well nothing happened and after 3 hours of trying crap I'm coming to you guys b/c I'm on my last leg. I still have no critical errors, nothing is making it fail: Here is my code.
<?php
//In the include file is the connection to the db
include("library/new_library.php");
//Below is the session id, gets their position id from the DB, than grabs whether or not they can edit the company
$user_id = $_SESSION['user_id'];
$sql = "SELECT ID, PositionID FROM users WHERE ID = '$user_id'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
$position = $row['PositionID'];
}
$sql = "SELECT * FROM tblCPositions WHERE PositionID = '$position'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
$editCompany = $row['Edit_Company'];
}
//Next I check for position edit and if they try to put in the position id of a position the company does not control it gives them a "nice" message.
$company = $_SESSION['company'];
if($_GET['pidedit']){
$position = $_GET['pidedit'];
$sql = "SELECT * FROM tblCPositions WHERE PositionID = '$position'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
if($row['CompanyID'] != $company)
{
$warning = "<div class='warning'>You are trying to edit a position that does not belong to your company. DO NOT TRY TO CHEAT THE SYSTEM!</div>";
}
else
{
$positionArray[] = array(ID => $row['PositionID'], name => $row['Name'], hire => $row['Hire'], fire => $row['Fire'], bid => $row['Contract'], edit => $row['Edit_Company'], finances => $row['Finances']);
}
}
}
//Here I check for $_GET delete
elseif($_GET['piddelete'])
{
$position = $_GET['piddelete'];
$sql = "SELECT * FROM tblCPositions WHERE PositionID = '$position'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
if($row['CompanyID'] != $company)
{
$warning = "<div class='warning'>You are trying to delete a position that does not belong to your company. DO NOT TRY TO CHEAT THE SYSTEM!</div>";
}
}
}
else
{
$sql = "SELECT * FROM tblCPositions WHERE CompanyID = '$company'";
$query = mysql_query($sql);
$number = mysql_num_rows($query);
$numberLeft = 12 - $number;
while($row = mysql_fetch_assoc($query))
{
$positionArray[] = array(ID => $row['PositionID'], name => $row['Name'], hire => $row['Hire'], fire => $row['Fire'], bid => $row['Contract'], edit => $row['Edit_Company'], finances => $row['Finances']);
}
}
//
if($_POST['submitNewPosition'])
{
$name = $_POST['positionName'];
$hire = $_POST['hire'];
$fire = $_POST['fire'];
$bid = $_POST['bid'];
$edit = $_POST['edit'];
$finances = $_POST['finances'];
$cid = $_SESSION['company'];
$sql = "INSERT INTO tblCPositions(CompanyID, Name, Hire, Fire, Contract, Edit_Company, Finances) VALUES ('$cid','$name','$hire','$fire','$bid','$edit','$finances')";
$query = mysql_query($sql);
if($query)
{
header("location: view_company.php?newp=success");
}
}
//Haven't finished this section yet
if($_POST['submitEditPosition'])
{
$name = $_POST['positionName'];
$fire = $_POST['hire'];
$fire = $_POST['fire'];
$bid = $_POST['bid'];
$edit = $_POST['edit'];
$finances = $_POST['finances'];
}
//This this is my problem area, this is where it says its running the query but its not.
if(isset($_POST['deletePosition']))
{
$deleteID = $_GET['piddelete'];
$deleteSql = "DELETE FROM tblCPositions WHERE PositionID = '$deleteID'";
$deleteQuery = mysql_query($deleteSql);
if($deleteQuery)
{
header("location: view_company.php?delete=success");
}
if(!$deleteQuery)
{
header("location: view_company.php?delete=failure");
}
}
UPDATE -
Ok so I got it working the problem was something I forgot, this form was just meant to be a "yes or no form" so I was doing post only to post the submit button, nothing else was on the form. What I had forgot was on the action="file.php" (what I had) I had forgotten to pass on the get variable so once I changed it to action="file.php?piddelete=12" it worked.
Thanks for everyones help I really appreciate it.
10 to 1 your variable $_GET['piddelete']; is empty. What do you get when you do this:
var_dump($_GET['piddelete']);
Disable the header redirect so that you can see the output.
edit
Or, as Nick pointed out, you can add die() statements to your queries:
$deleteQuery = mysql_query($deleteSql) or die(mysql_error());
If your query still runs, and the script doesn't die, and the position is still not deleted, you should check the query, it may be deleting 0 rows successfully. try killing at die($deleteSql); and run the query through MySQL's console.
/edit
Also, I'm compelled to introduce you to my good friend SQL injection attack. You should filter all data contained in the $_POST and $_GET superglobals before handing them over to the MySQL server. use mysql_real_escape_string().
Try to grok this:
whatever.com/your_url.php?pidedit=x'%3B%20DROP%20TABLE%20tblCPositions%3B%20--
If I were to execute that query string on your application, your tblCPositions table would be dropped.

Drupal: PHP field for allowed values

I'm working in Drupal 6 with CCK. Under each text field there is a PHP section where you can run some PHP code to get allowed values. I'm running into trouble using an "if" statement to change the allowed values based on user type
So to start, I do a query to determine current users user type. -1 is default user, which is employees and user type id "1", is for site users. What I want is to restrict the site user to only the allowed values they need to see, while allowing employees to edit that value when on the node edit screen with all choices.
The first part of the if statement works. However, the "else" part doesn't work. Is this field set up to deal with control structures?
global $user;
$sql1 = "SELECT user_type_id FROM user_types_user WHERE uid = ".$user->uid." ";
$res1 = db_query($sql1);
if($res1 == '1'){
$sql = "SELECT account FROM users WHERE uid = ".$user->uid." ";
$res = db_query($sql);
while($row = db_fetch_array($res)){
$rows[] = $row['account'];
}
$rows = drupal_map_assoc($rows);
return $rows;
}
else {
$sql2 = "SELECT title FROM node WHERE type = 'accounts' ";
$res2 = db_query($sql2);
while($row2 = db_fetch_array($res2)){
$rows2[] = $row2['title'];
}
$rows2 = drupal_map_assoc($rows2);
return $rows2;
}
The choices are type=accounts in nodes, however, when a user is created one of the choices is selected and stored in the user table, under a column I created named "account"
If by 'the "else part does not work' you mean that it is never executed, even if user_type_id does not equal 1, it might be the missing db_fetch_array() on $res1. You're comparing your result object directly to the string '1', not the field value.
Here is the working code for this. There may have been a quicker/shorter way to do this.
global $user;
$sql1 = "SELECT user_type_id FROM user_types_user WHERE uid = ".$user->uid." ";
$res1 = db_query($sql1);
while($type = db_fetch_array($res1)){
$types[] = $type['user_type_id'];
}
$resType = $types[0];
if($resType == "1"){
$sql = "SELECT account FROM users WHERE uid = ".$user->uid." ";
$res = db_query($sql);
while($row = db_fetch_array($res)){
$rows[] = $row['account'];
}
$rows = drupal_map_assoc($rows);
return $rows;
}
else {
$sql2 = "SELECT title FROM node WHERE type = 'accounts' ";
$res = db_query($sql2);
while($row2 = db_fetch_array($res)){
$rows2[] = $row2['title'];
}
return $rows2;
}

Categories