I'm probably going to make myself look like a fool with my horrible scripting but here we go.
I have a form that I am collecting a bunch of checkbox info from using a binary method. ON/SET=1 !ISSET=0
Anyway, all seems to be going as planned except for the query bit. When I run the script, it runs through and throws no errors, but it's not doing what I think I am telling it tom which is updating the specified fields within the DB.
I've hard coded the desired values into the query and it DOES update the DB. Relying on the variables I believe I've established and am then calling upon in the query does NOT update the DB.
I've also tried echoing all the needed variables after the script runs and exiting right after so I can audit them... and they're all there. Here's an example.
####FEATURES RECORD UPDATE
### HERE I DECIDE TO RUN THE SCRIPT BASED ON WHETHER AN IMAGE BUTTON WAS USED
if (isset($_POST["button_x"])) {
### HERE I AM ASSIGNING 1 OR 0 TO A VAR BASED ON WHTER THE CHECKBOX WAS SET
if (isset($_POST["pool"])) $pool=1;
if (!isset($_POST["pool"])) $pool=0;
if (isset($_POST["darts"])) $darts=1;
if (!isset($_POST["darts"])) $darts=0;
if (isset($_POST["karaoke"])) $karaoke=1;
if (!isset($_POST["karaoke"])) $karaoke=0;
if (isset($_POST["trivia"])) $trivia=1;
if (!isset($_POST["trivia"])) $trivia=0;
if (isset($_POST["wii"])) $wii=1;
if (!isset($_POST["wii"])) $wii=0;
if (isset($_POST["guitarhero"])) $guitarhero=1;
if (!isset($_POST["guitarhero"])) $guitarhero=0;
if (isset($_POST["megatouch"])) $megatouch=1;
if (!isset($_POST["megatouch"])) $megatouch=0;
if (isset($_POST["arcade"])) $arcade=1;
if (!isset($_POST["arcade"])) $arcade=0;
if (isset($_POST["jukebox"])) $jukebox=1;
if (!isset($_POST["jukebox"])) $jukebox=0;
if (isset($_POST["dancefloor"])) $dancefloor=1;
if (!isset($_POST["dancefloor"])) $dancefloor=0;
### I'VE DONE LOADS OF PERMUTATIONS HERE... HARD SET THE 1/0 VARS AND LEFT THE $estab_id TO BE PICKED UP. SET THE $estab_id AND LEFT THE COLUMN DATA TO BE PICKED UP. ALL NO GOOD. IT _DOES_ WORK IF I HARD SET ALL VARS THOUGH
mysql_query("UPDATE thedatabase SET pool_table='$pool', darts='$darts', karoke='$karaoke', trivia='$trivia', wii='$wii', megatouch='$megatouch', guitar_hero='$guitarhero', arcade_games='$arcade', dancefloor='$dancefloor' WHERE establishment_id='22'");
###WEIRD THING HERE IS IF I ECHO THE VARS AT THIS POINT AND THEN EXIT(); they all show up as intended.
header("location:theadminfilething.php");
exit();
THANKS ALL!!!
I recommend you to use something like:
$fields = array('pool', 'darts', 'karaoke', 'trivia', ...);
foreach ( $fields as $field ) {
$$field = isset($_POST[$field]) ? 1 : 0;
}
instead of 20 lines of ifs.
Your columns are ENUM or int type ? If int - drop apostrophes.
Your code could really use some error checking. Make sure you have activated the displaying of errors in your script.
In your testing environment add this at the top of your main script for instance (if you haven't done something equivalent already):
error_reporting( E_ALL | E_STRICT );
ini_set( 'display_errors', 1 );
Then (although not dependant on the above) make sure you probe the result of the query with something like:
if( false === mysql_query( 'UPDATE ...etc' ) )
{
echo 'query failed with error:' . mysql_error();
}
My guess is it will fail with the error that your column name karaoke is mispelled. But there may be more errors.
Also, hsz' suggestions are spot on (though probably not the root of your problem). Makes for easier to maintain code, and significantly reduces code.
Firstly, construct the sql query string in a variable and then pass it to mysql_query(), comment out the header() line and print out the query for debugging. For example:
...
$sql="UPDATE thedatabase SET pool_table='$pool', darts='$darts', karoke='$karaoke', trivia='$trivia', wii='$wii', megatouch='$megatouch', guitar_hero='$guitarhero', arcade_games='$arcade', dancefloor='$dancefloor' WHERE establishment_id='22'";
print("$sql");
mysql_query($sql);
//header("location:theadminfilething.php");
exit();
...
Secondly, even tho you are exiting the script, its good practice to always match your braces. You are missing the end brace for the if statement at the end of your code.
The value of the $sql variable output you can see if it works by executing it 'manually' thru phpmyadmin or the command line. What happens?
Related
I am trying to register a button click on my website using PHP.The click downloads a file to client's machine. Database connection was tested before and it works fine. I just need to register that click into DB. Here is my code, could you guide me through?
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
if(isset($_GET['dl']))
{
$server = "xx.xxx.xx.xxx";
$dbusername = "xxxx";
$dbpassword = "xxxx";
$database = "xxxx";
$dbcon = new mysqli($server,$dbusername,$dbpassword, $database);
$userid = $_SESSION['suserid'];
$date_downloaded = date('Y-m-d H:i:s');
$sql = "INSERT INTO external_activity (
userid,
saleid,
activity,
date_register,
) VALUES (
'".$userid."',
'".$ref_no."',
'".'Downloaded file'."',
'".$date_downloaded."'
)";
$dbcon->query($sql);
$dbcon->close();
}
If using jquery is an option, you could create a "register_click.php", paste the if(isset($_GET['dl'])) stuff inside and call it via ajax using an onclick listener that you will have to create and bind to the anchor.
You could do it with POST data instead of GET.
$i = 0;
if $_POST['submit'] {
$i++;
$number_of_times_clicked = $number_of_times_clicked_stored_into_database + $i;
}
After that restore the new value back into the database. If you really want the onclick you need javascript. PHP is unable to check when a button is clicked, since the code only works once when the page is loaded.
This is too long for a comment.
The & in your code might give you some problems, I said "might". If so, then consider changing those to & (ampersands).
Should it be the case, then you could change:
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
to:
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
Then you will need to check and see if each GET array is is set/not empty with isset() and !empty().
References:
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
I only see if(isset($_GET['dl'])) as a single array, so it's unsure as to how you're wanting to fetch the other GET arrays in your URL and if you did set those.
Your present code (if it's the full code), will throw a few notices about certain variables not being defined.
For example, the if(isset($_GET['dl'])) and using the other GET arrays, would look like this:
if( isset($_GET['f']) && !empty($_GET['l']) && !empty($_GET['dl']) ){
// do something inside here
}
You also need to make sure that the session was indeed started with session_start(); and to be included inside all files using sessions.
Reference:
http://php.net/manual/en/function.session-start.php
This is usually the first line under the opening PHP tag.
<?php
session_start();
// rest of your code
The $userid = $_SESSION['suserid']; needs to have a value/equal something, so that is unknown as to whether or not there is indeed a value for it.
Error reporting will be of help here for you, as will checking for errors against your query.
References:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
You also have a trailing comma in date_register, < and that needs to be removed, as I already stated in comments.
That alone would have thrown a syntax error.
The use of '".'Downloaded file'."' is unclear. If you just want to insert the Downloaded file as a string, then you can just place it inside single quotes 'Downloaded file' and do:
$sql = "INSERT INTO external_activity (
userid,
saleid,
activity,
date_register
) VALUES (
'".$userid."',
'".$ref_no."',
'Downloaded file',
'".$date_downloaded."'
)";
Make sure that the date_register column type is DATE and not VARCHAR or other format. Although VARCHAR would not throw an error, it's best to use MySQL's built-in dating functions; that column's type is unknown.
Now, make sure that the userid column is not an AUTO_INCREMENT'ed column, otherwise your code will fail.
If the ultimate goal here is to "UPDATE" that userid column, then use just that, UPDATE:
http://dev.mysql.com/doc/refman/5.7/en/update.html
You also need to make sure that all columns' types are correct and have a length long enough to accomodate the incoming data and that there are no characters that MySQL will complain about, such as apostrophes.
Escaping those with a prepared statement will ensure that it doesn't throw/cause a syntax error and is something you should be using in order to help prevent against an SQL injection and you are open to one right now.
References:
https://en.wikipedia.org/wiki/Prepared_statement
https://en.wikipedia.org/wiki/SQL_injection
This is the best way that I can offer for the question, given the information left in the question.
Again; check for errors. That is one of the most important things that needs to be done during the development of your code.
I'm setting $_SESSION['showroom'] to 'active' when a particular page in Wordpress is displayed:
if(get_the_ID()==6470||get_the_ID()==252){
$_SESSION['showroom']='active';
}
I then set 2 arrays of pages to check against. If the next page displayed is NOT in one of these arrays, $_SESSION['showroom'] gets changed to 'inactive'.
$allowed_templates = array('template-A.php',
'template-B.php',
'template-C.php',
'template-E.php',
'template-G.php');
$allowed_ids = array(6470,252);
$template_name = get_page_template_slug();
$page_id = get_the_ID();
if(in_array($template_name,$allowed_templates)==false && in_array($page_id,$allowed_ids)==false){
$_SESSION['showroom']='inactive';
}
The if statement works most of the time, but sometimes my $_SESSION['showroom'] changes to inactive EVEN though one of the arrays is returning true! After several hours of testing I am unable to locate where the problem is. Echoing out the two parts of the if statement ALWAYS gives me 2 trues or 1 true + 1 false, but never 2 falses:
if(in_array($template_name,$allowed_templates)==false){echo 'TFALSE';}
if(in_array($template_name,$allowed_templates)){echo 'TTRUE';}
if(in_array($page_id,$allowed_ids)==false){echo 'IFALSE';}
if(in_array($page_id,$allowed_ids)){echo 'ITRUE';}
What am I missing here?
Thanks in advance for any help!
EDIT: Have continued testing and found the following anomaly:
if(in_array($template_name,$allowed_templates)==false && in_array($page_id,$allowed_ids)==false){
$_SESSION['showroom']='inactive';
echo 'SET TO INACTIVE';
}
The if statement changes $_SESSION['showroom'] to 'inactive' but DOES NOT echo out 'SET TO INACTIVE'!
There's something strange going on here!
Problem solved. My code was fine. Two missing images files were causing WordPress to crash my sessions. Took 10 hours to find out but happy I found it. Thanks to everyone for their help.
You can try the following;
if(!in_array($template_name,$allowed_templates) && !in_array($page_id,$allowed_ids)){
$_SESSION['showroom']='inactive';
}
Edit: lets try and break it down further... similar to your examples
if(!in_array($template_name,$allowed_templates){
echo "not in templates,";
}
if(!in_array($page_id,$allowed_ids)){
echo "not in ids,";
}
if(!in_array($template_name,$allowed_templates) && !in_array($page_id,$allowed_ids)){
echo "not in both\n";
}
then see if we get a result with not in templates,not in ids, but no trailing not in both
The problem is pure logical. Lets look at this statement:
if (in_array($template_name,$allowed_templates)==false && in_array($page_id,$allowed_ids)==false)
Which translates to "If the template is not valid AND page is not valid"
This means that both statements needs to be fulfilled in order to mark session as inactive. What if the template is fine, but the page is not valid? That definitely should be marked as inactive as well.
By changing the statement to read "If the template is not valid OR page is not valid", we cover up the invalid cases. Because either of them counts as an invalid state, and thus, only one of them needs to be false in order for everything to be false. (the OR-statement)
So code-wise it would be
if (in_array($template_name,$allowed_templates)==false || in_array($page_id,$allowed_ids)==false)
And you are set.
As and addition. I would structure the code as you noted works. Which is more logical. That is, mark it as inactive whenever it's should be treated as inactive, in all other cases mark it as 'active'. Or vice-versa.
I have successfully extracted the correct data from my database during testing (its just a prototype - so yes I know its not secure SQL). The test SQL is
$sql=
SELECT *
FROM jobcards
WHERE jobnumber='$jobnumber'
";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{loop}
The issue is the source of the data to which $jobnumber is set.
If during testing I set $jobnumber to the string Agen912-491 (implicitly) I get out of the database exactly what I should get out. However here is the problem.
I am clicking from a link on another page. The link creates the URL:-
domain.php/jobcard.php?jobnumber=%20Agen912-491
which take me to the page on which the SQL query (and the output) resides. So on the page I set
$jobnumber = $_GET["jobnumber"];
echo $jobnumber;//testing
to request (and test) the jobnumber (passed from the link) that I need to insert into the WHERE condition. As expected the echo correctly returns Agen912-491. So exactly the same string (it seems) as the implicit value used succesfully in testing. All good so far.
However when I then set $jobnumber= $_GET["jobnumber"]; the database query fails to find any records. [In desperation I fudged the process so that the variable $jobnumber = $_SESSION ["jobnumber"]; (and ensured via an echo that $_session[] gave me Agent912-491). Now the database correctly returns the record again!
So for some reason the $GET["jobnumber"]; statement when set to $jobnumber is failing [even though when it is echoed it returns the correct value that works implicity (and when set it via $s[session]. So there is clearly an issue with a) requesting $_GET["jobnumber"]; b) setting it to the $jobnumber and then c) using that in the WHERE statement. Everything else works as does setting $jobnumber implicitly or via $_session.
I have an incline it might be something to do with santitising the $_GET result before using it. But that really is a guess and even if correct I dont know what exactly to try out.
Help would be really appreciated. Many thanks.
I have been trying to create an edit link for my web application. the update request doesn't work and oddly I am not getting any error. any ideas please .Thanks in advance
Here is my code:
<?php
$id=$_GET["invistID"];
if(isset($_POST['validation']))// the submit buttom
{
try
{
$req = $bdd->prepare('UPDATE invistigation_en SET fininvist=:fininvist,rapportinvist=:rapportinvist,status=:status WHERE invistID=:invistID');
$data =array(
':invistID'=>$id,
':fininvist'=> $_POST['fin'],
':rapportinvist'=> $_POST['rapport'],
':status'=> $_POST['status']
);
$req->execute($data);
echo "success ...";
}catch(PDOException $e){
echo "Error ... :".$e->getMessage();
}
header('Location:invistigation.php');//
}
?>
Debug is an important step when you build applications. When you write code, some times, application behavior is not as you expects. This is your case. At this time, you should isolate your issue and fix it.
To isolate issue they are some techniques. At this time you don't know why this code don't run. Then you should identify program check points and check if, at this points, all is as you expect.
For your code:
Check all page parameters have expected values. var_dump( $_POST )
Check all query parameters you send to execute are right: var_dump( $data )
Print errors as #andrewsi suggest: var_dump($bdd->ErrorInfo()) var_dump($req->ErrorInfo()) .
If problem persist raise your own errors: change Update word by XXXX, execute and check if some errors appear.
Remove redirect ( header('Location ... ), change it by die("end") to see all page errors.
good luck, and please, let us know, finally, where your error was.
can someone please help, i am trying to get the column 'privellages' (i know its spelt wrong) to update in my table 'ptb_permissions' when a link is clicked.
basically i've done this before for loads of other things and its worked fine its just this not working for some reason.
users are notified in their inbox when a user sends a request to view their pictures. and the user will have two links one to approve or one to delete the request.
if they click approve then this should update the enum colum 'privellages' from 0 to 1.
this is not working. im not getting any errors im just not getting anything happening. please can someone show me where im going wrong thanks.
Yes this is ok
contents of approve_priv_pix.php;
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
approve_pix ($_GET['picture'], $_SESSION['user_id']);
header("Location: {$_SERVER['HTTP_REFERER']}");
?>
mysql function:
function approve_pix($picture, $user) {
global $connection;
global $_SESSION;
$query = "UPDATE ptb_permissions
SET privellages='1'
WHERE id=$picture
AND to_user_id=$user";
mysql_query($query, $connection);
}
$_GET['picture'] should be $_GET['pix']
Also double check your privellages column enum values.
Yes this is ok
Here you have pix as a key, but in approve_priv_pix.php you are taking picture id from $_GET['picture']. Suppose it should be replaced with $_GET['pix']
Also, not sure why do you have <?php echo $pix['user_id']; ?> in link code. Possibly it should be something like <?php echo $pix['picture_id']; ?>
Additionally, you code is opened to sql injections. Here:
$query = "UPDATE ptb_permissions
SET privellages='1'
WHERE id=$picture
AND to_user_id=$user";
Instead of that you should better do:
$query = "UPDATE ptb_permissions
SET privellages='1'
WHERE id=" .mysql_real_escape_string($picture) . "
AND to_user_id=" .mysql_real_escape_string($user);
More details about mysql_real_escape_string. Take a look at warning message on top of that page. mysql extension is deprecated and will be remove soon. For new projects you should better use PDO or MySQLi extensions.
Another note: global $_SESSION; is not needed at all. It is accessible form any place in PHP by default.
im not getting any errors im just not getting anything happening
To see all errors you should set error_reporting to E_ALL (in your ini file or directly in code). With this option enabled you would see all notices/warnings/errors.