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.
Related
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.
I am trying to create a Secret Santa system using a PHP page and a MySQL database to store the details so if someone forgets their match they can re-request it.
Step 1: I created a random number generator based on the number of people in the list in the database.
Count Function:
$maxSQL = "SELECT COUNT(id) as total FROM secretsanta";
$maxRS = mysqli_query($conn, $maxSQL);
$maxQuery = mysqli_fetch_array($maxRS);
$maxpersons = $maxQuery['total'];
Then the Random Number Generator:
$assigned = rand(1,$maxpersons);
Step 2: Test if the random number matches the persons own id and regenerate a new number if true.
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id);
Step 3: Write the paired id to the persons database record.
$assignSQL = "UPDATE secretsanta SET assigned = '".$assigned."' WHERE secretsanta.id = ".$id;
if (mysqli_query($conn, $assignSQL)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
The Problem: Now I need to check that other people aren't assigned to that person or otherwise some could miss out and others would get more than others.
I tried to implement a function that contained a query to test each record to see if that number already existed and was hoping to add it as a condition to perhaps a while or do while statement?
if (!function_exists('checkRandom')){
function checkRandom($funcid){
$Check_SQL = "SELECT assigned FROM secretsanta ORDER BY id ASC";
$Check_RES = mysqli_query($conn, $Check_SQL);
if (Check_RES) {
while ($CheckArray = mysqli_fetch_array($Check_RES, MYSQLI_ASSOC)) {
$CheckAsgn = $CheckArray['assigned'];
if ($funcid==$CheckAsgn) {return true;}else{return false;}
}
}
}
}
Then implement it into the do while statement like this:
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id||checkRandom($assigned));
No luck so far...HELP!.. please :)
P.S. I know there are websites that already do this, I just don't trust them to give out mine and family email address' if I can make my own private version myself.
Using your method, the first few assignments will be done with no problem, but imagine the last unassigned entry and how many times it will try a random number only to find the person with that id is already assigned..
I'm gonna give you another approach to your problem: for each user that you want to assign a santa to, make a new SELECT statement with a WHERE clause that lets you select only those users that are not assigned yet.
check out my code and see if that helps you. I just typed this and didnt test it so there could be some mistakes.
// load all unassigned users into an array
$unassignedUsers = [];
$query = "SELECT id, assigned FROM secretsanta WHERE assigned is NULL";
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedUsers[] = $row;
}
if(count($unassignedUsers) == 1){
echo 'There is only 1 unassigned user. Therefore he cannot be matched';
} else {
// for loop for each user in DB that is not assigned yet
//for ($i = 1;$i <= count($unassignedUsers); $i++){
$i = 0;
foreach($unassignedUsers as $user)
// if its the second-to-last iterations of the for-loop, check for legality of the last one
if(count($unassignedUsers) - $i == 1){
$lastUserID = $unassignedUsers[count($unassignedUsers)-1]['id'];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id = ".$lastUserID;
$res = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($res);
if ($rowcount){
// last user is still unassigned
$query = "UPDATE secretsanta SET assigned = '".$lastUserID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
} else {
// select all unassigned users
$unassignedIDs = [];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id <> ".$user['id'];
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedIDs[] = $row['id'];
}
// get a random id from $unassignedIDs
$randomIndex = rand(0, count($unassignedIDs)-1);
$randomID = $unassignedIDs[$randomIndex];
// assign $randomID to user
$query = "UPDATE secretsanta SET assigned = '".$randomID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
$i++;
}
}
last edit: refactored whole code so it is able to be run multiple times and only assigns new users who are not assigned yet.
Step 1 is dependent on have a contiguous set of ids for the people. Think what happens if '3' leaves the company and it hires 6 to replace them....1,2,4,5,6 ($maxpersons=5)
"Now I need to check" - no you are still trying to solve the problem by guessing then seeing if your guess worked. Use an algorithm which is always going to return a correct result. The method below requires the addition of a temporary field 'sequence' of type float.
mysqli_query($conn,"UPDATE secretsanta SET sequence=RAND()");
$first=false;
$prev=false;
$all=mysqli_query($conn, "SELECT * FROM secretsanta ORDER BY sequence, id");
while ($r=mysqli_fetch_assoc($all)) {
if (false===$first) {
$first=$r['id'];
} else {
save_pair($prev, $r['id']);
}
$prev=$r['id'];
}
save_pair($prev, $first);
(but with better error checking)
The error is just like the title, and from various posts in SO mentioned about server side of error.
I just repeat the same PHP script with differences in table name and column name. The script is for update column, but only one of the columns not updated - bizPhone, and deleted the content. Other column - bizName, bizAddress etc, no problem.
I have compared the string in Config file and in PHP script - no difference.
Original PHP script:
$sql = "SELECT countryID FROM wg_countries WHERE country = '$country'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
$countryID = $row[0];
}
$sql2 = "SELECT categoryID FROM wg_categories WHERE category = '$category'";
$res2 = mysqli_query($con, $sql2);
$result2 = array();
while($row2 = mysqli_fetch_array($res2)){
$categoryID = $row2[0];
}
$sql3 = "UPDATE wg_groups SET groupName = '$groupName', description = '$description', countryID = '$countryID', categoryID = '$categoryID', url = '$url' WHERE groupID = '$groupID'";
if(mysqli_query($con,$sql3)){
echo "Successfully Updated";
}else{
echo "Could not update";
}
Copied and modified PHP script:
$sql = "SELECT countryID FROM wg_countries WHERE country = '$country'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
$countryID = $row[0];
}
$sql2 = "SELECT categoryID FROM wg_categories WHERE category = '$category'";
$res2 = mysqli_query($con, $sql2);
$result2 = array();
while($row2 = mysqli_fetch_array($res2)){
$categoryID = $row2[0];
}
$sql3 = "UPDATE wg_biz SET bizName = '$bizName', bizAddress = '$bizAddress', countryID = '$countryID', categoryID = '$categoryID', bizURL = '$bizURL', bizPhone = '$bizPhone' WHERE bizID = '$bizID'";
if(mysqli_query($con,$sql3)){
echo "Successfully Updated";
}else{
echo "Could not update";
}
Since I keep getting error 500, I have checked the log errors in GoDaddy but no details - just 500 xx xx xx something like that.
Also, the query already tested and have no problem. Where should I check again? :(
500 error is a server error. not android error. you can look in apache error log to see the error.
if you call that script from the browser do you get the same error?
the debugging is step by step.
call with Volley any URL or empty file and print it. see that you don't get an error (see if it is working then you know Volley is working)
then use Volley to print the input with like a PHP script like: var_dump($_REQUEST);
if your script is failing and not volley, then print the result of each step in the PHP file. maybe print something and exit after the first part. to see if the script comes to this point. also, you can print the SQL statements and try to run them by hand to see if they are working.
Basically, I have been having some trouble with sending a request to a MySQL server and receiving the data back and checking if a user is an Admin or just a User.
Admin = 1
User = 0
<?php
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`";
$checkAdmin = $checkAdminQuery
mysqli_query = $checkAdmin;
if ($checkAdmin == 1) {
echo '<h1>Working!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
Sorry that this may not be as much info needed, I am currently new to Stack Overflow.
Firstly, your SQL query is wrong
SELECT * FROM `users` WHERE `admin`
It's missing the rest of the WHERE clause
SELECT * FROM `users` WHERE `admin` = 1
Then you're going to need fetch the result from the query results. You're not even running the query
$resultSet = mysqli_query($checkAdminQuery)
Then from there, you'll want to extract the value.
while($row = mysqli_fetch_assoc($resultSet))
{
//do stuff
}
These are the initial problems I see, I'll continue to analyze and find more if needed.
See the documentation here
http://php.net/manual/en/book.mysqli.php
You need to have something like user id if you want to check someone in database. For example if you have user id stored in session
<?php
// 1. start session
session_start();
// 2. connect to db
$link = mysqli_connect('host', 'user', 'pass', 'database');
// 3. get user
$checkAdminQuery = mysqli_query($link, "SELECT * FROM `users` WHERE `id_user` = " . $_SESSION['id_user'] );
// 4. fetch from result
$result = mysqli_fetch_assoc($checkAdminQuery);
// 5. if column in database is called admin test it like this
if ($result['admin'] == 1) {
echo '<h1>Is admin!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
// get all admin users (assumes database already connected)
$rtn = array();
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`=1";
$result = mysqli_query($dbcon,$checkAdminQuery) or die(mysqli_error($dbconn));
while($row = mysqli_fetch_array($result)){
$rtn[] = $row;
}
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`"; !!!!
where what ? you need to specify where job = 'admin' or where name ='admin'
you need to specify the column name where you are adding the admin string
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;
}