hielo 65 Veteran Poster

What is your PHP INSERT query? Are you by any chance casting the value of type to an integer? Also, where is the javscript code that is actually sending the data to the server? The updateNewsFeed(...) doesn't seem to be doing anything with the encodedata and url variables.

hielo 65 Veteran Poster

Try appending the data as a querystring -ex:

jq("#myid").load(location.href + " #myid?firstName=John&lastName=Smith");
hielo 65 Veteran Poster

From what I see, the input and the corresponding select can be "tied/related" to each other by inspecting their id attributes. By removing the non-numeric portion of the id, whatever is left helps you the determine the id of the corresponding element. Since ids must be unique, the previous method helps you identify the unique corresponding element. Try:

 <script>
  $('input[name="txt"]').each(function () { 
          var id_suffix = this.id.replace(/\D/g,'');
          $('#budget'+id_suffix).on('change', function(){
          var total = $(this).val();
         $('#txt'+id_suffix).val($(this).find("option:selected").attr("value")); 
    });
 });
 </script>
hielo 65 Veteran Poster

Are you referring to the document.write predefined method? If so, just assign a reference to if for your own write property -ex.

var subject = new Object();
subject.write = document.write;
subject.write("hi");//works as if you had called document.write("...")
hielo 65 Veteran Poster

You need to fix your <form> tag to include enctype="multipart/form-data" otherwise the $_FILES array will remain empty. Also, you forgot to use echo for the action attribute. Try:

<form name="form1" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post" enctype="multipart/form-data">...</form>
hielo 65 Veteran Poster

And in terms of Finder menu options ... Not sure why they're missing for you

FYI - They are not missing for me. However the list of items under my "Favorite Forums" is not the same as what I had prior to the "upgrade." I wonder if I am seeing someone else's "Favorite Forums" list. I used to have four items -- Databases, Web Development, Software Development, and UI/UX Design, but after the migration I now see only three: Hardware and Software, Software Development, and Community Center. On another note, it would be nice if there was a way to customize that list.

hielo 65 Veteran Poster

Your code above begins with:

<?php
require 'database.php';
$code_id = $_SESSION['SESS_CODE_NAME'];

Are you calling session_start(); at the beginning of database.php? If not, then $code_id will not have the value you expect.

Also on line 178 I see:

$q = mysql_query ("SELECT * FROM studentreg WHERE jamb='$jamb'");

but I don't see $jamb being initialized anywhere. If undertand you correctly, you have a file with a form that submits the script above. If that is the case, you need to initialize $jamb on the script above.

I suggest you start adding debugging statements to help you track the bug in the script. For example, lines 77-82 above could be changed to:

$errors=Array();

echo '<pre>' . __FILE__ . '[' . __LINE__. '] $_SESSION=' . print_r($_SESSION,true) . '</pre>';

echo '<pre>' . __FILE__ . '[' . __LINE__. '] $_POST=' . print_r($_POST,true) . '</pre>';

echo '<pre>' . __FILE__ . '[' . __LINE__. '] $_FILES=' . print_r($_FILES,true) . '</pre>';

if( array_key_exists('submit1',$_POST) )
{
    echo 'Executing line ' . __LINE__ .'<br/>';
    if(!empty($_FILES))
    {
         echo 'Executing line ' . __LINE__ .'<br/>';

        // these are your "settings"           
        $errors=Array();

        if( array_key_exists('submit1',$_POST) )

That way when you submit the first form/page to the script above, you should be able to see which lines are being executed in addition to the critical data from the various arrays and see if they are missing. From there you should be able to track down the reason why they are missing.

hielo 65 Veteran Poster

Line 78 is wrong -- it should be lowercase "s". To clarify, your initial form has

<input style="font-size:18px; height:45px; font-weight:bold; color:#0033FF" type="submit" style="height:50px" name="submit1" value="Save / Submit Form" >

Notice that the value of the name attribute is "submit1" (again, lowercase "s").

hielo 65 Veteran Poster

On submit button on your first form has name="submit1", so you need to update line 78 to test for 'submit1' instead of 'Submit'. Also, on lines 83-87 you need to update'destination'=>'/path/to/save/directory/' with the actual location of the directory where the files are to be saved.

hielo 65 Veteran Poster

You need ... LIMIT offset, rowCount -- ex:

SELECT blabla
FROM a INNER JOIN b ON a.a = b.b
ORDER BY a.id DESC LIMIT 50, 10

will give you at most 10 rows, starting with row 50.

hielo 65 Veteran Poster

It worked fine for me. Did you copy and paste the code above or did you integrate it onto some existing codebase?

I updated the code with the one below so that it will not allow overwriting of existing files. Do a copy-paste onto a new file and try it. If it works, then integrate whatever other code you need onto it.

<?php
//this is where the detected errors will be stored
$errors=Array();

if( array_key_exists('Submit',$_POST) )
{
    if(!empty($_FILES))
    {
        // these are your "settings"
        $myFiles=Array(  'pri'      => Array('required'=>true, 'destination'=>'C:\\Path\\to\\uploads\\directory', 'allowed'=>'pdf;doc;docx', 'label'=>'Pri') 
                        ,'oresult'  => Array('required'=>true, 'destination'=>'C:\\Path\\to\\uploads\\directory', 'allowed'=>'pdf;doc;docx', 'label'=>'OResult')
                        ,'oresult2' => Array('required'=>true, 'destination'=>'C:\\Path\\to\\uploads\\directory', 'allowed'=>'pdf;doc;docx', 'label'=>'OResult2')
                        ,'dob'      => Array('required'=>true, 'destination'=>'C:\\Path\\to\\uploads\\directory', 'allowed'=>'pdf;doc;docx', 'label'=>'DOB')
                        ,'photo'    => Array('required'=>true, 'destination'=>'C:\\Path\\to\\uploads\\directory', 'allowed'=>'png;jpg;jpeg;gif', 'label'=>'Photo')
                        );
        foreach($myFiles as $field=>&$prop)
        {
            $prop['uploaded_file'] = '';        

            if( array_key_exists($field, $_FILES) )
            {                   
                // http://php.net/manual/en/features.file-upload.php
                // http://php.net/manual/en/features.file-upload.errors.php
                if( true===$prop['required'] )
                {
                    if($_FILES[$field]['error']===UPLOAD_ERR_NO_FILE)
                    {
                        $errors[] = $prop['label'] . ' is a required field.';
                    }
                    elseif($_FILES[$field]['error']!==UPLOAD_ERR_OK)
                    {
                        $errors[]='File upload for ' . $prop['label'] . ' failed with error code ' . $_FILES[$field]['error'] . '.';
                    }
                }
                elseif($_FILES[$field]['error']!==UPLOAD_ERR_OK)
                {
                    $errors[]='File upload for ' . $prop['label'] . ' failed with error code ' . $_FILES[$field]['error'] . '.';
                }

                if(!empty($errors))
                {
                    break;
                }
                else
                {
                    $prop['destination'] = array_key_exists('destination', $prop) ? $prop['destination'] : getcwd().'/uploads';
                    $prop['destination'] = str_replace('/',DIRECTORY_SEPARATOR,$prop['destination']);
                    $prop['destination'] = rtrim($prop['destination']," \t\n\r\0\x0B\/.\\");
                    if( !is_dir($prop['destination']) )
                    {
                        $errors[] = 'The destination directory for '.$prop['label'].' does not exist.';
                    }
                    else
                    {                   
                        // sanitize filename -- allows only letters, numbers, underscore and periods
                        $_FILES[$field]['name'] = preg_replace('/[^\w\.]/', '', $_FILES[$field]['name']);
                        if( !preg_match('/\w+\.(\w+)$/', $_FILES[$field]['name'],$m) …
hielo 65 Veteran Poster

...but the files are not moving to its destination folders...

Check your server's error log to see if it gives you a clue as to why it may not be working (ex: permission problem)

After clicking save form, it loads and brings me back to the form with empty inputs...

That was intentional. I don't know what you were expecting, but you can easily add:

elseif( !empty($_FILES)  )
{
    echo '<h1>Thank You</h1>';
}

after line 105.

hielo 65 Veteran Poster

It's hielo, not helio. As for the healthcheck form look at how I implemented the attendance form and then make an effort to implement the healthcheck form. If you have questions or get stuck then ask.

If you analyze what I did on the index.php page you will notice that I did the data processing (but only if the form was submitted) at the top first, then I began emitting the html. This is pretty much the same approach you need to take.

hielo 65 Veteran Poster

Upon closer inspection I see that you are mixing mysqli_ (with an "i") with mysql_ ( without an "i") functions. To clarify, you are connecting to the database using mysqli_connect, but then you are using mysql_real_escape_string() and mysql_query(). Stick with mysqli_ since mysql_ function are now deprecated. Read the manual to see how mysqli_query() is different from mysql_query(). The same goes for the other function. The number of parameters are different, so just adding and "i" to the function call will not work.

Copy and paste the following into your index.php file. The connect-db.php file is the same I posted earlier. Read through the comments to understand what the code is doing.

<?php
# specify your table first
$mysql_db = 'attendance';

# include your db connection file
require 'connect-db.php';

# if it makes it here, then the connection was successful.  Do your select * FROM $mysql_db
# AFTER the updates (see line 87) so that your page may reflect the updated information.

# this will be used to save any potential errors
$feedback=Array();

// Now there is student_id hidden field in the first column.  It should correspond to the unique id 
// record on your table.
if( array_key_exists('student_id',$_POST) )
{
    // Notice that the name of the hidden field is "student_id[]" (with brackets at the end).  This
    // way PHP "sees" an array of student_id fields.
    foreach($_POST['student_id'] as $id)
    {
        $id = intval($id);
        // The corresponding fields for a given row also have the student_id. So, instead of 
        // name="present", …
hielo 65 Veteran Poster

but i got error on line 44

On my post above, there is a missing semicolon at the end of line 46:

 ...
 $prop['destination'] = array_key_exists('destination', $prop) ? $prop['destination'] : getcwd().'/uploads';

  // add semicolon at the end of the following line
 $prop['destination'] = rtrim($prop['destination']," \t\n\r\0\x0B\/.");

 if( !is_dir($prop['destination']) )
 ...
hielo 65 Veteran Poster

Did you check your spam folder? If in fact it is not sending emails, then it's most likely a server configuration problem. If you are on a linux machine, try executing the following from a command line:

sudo setsebool -P httpd_can_sendmail 1

if you just want to see the error message (for purposes of troubleshooting your login() function, try:

...
$message = 'DB Error: ' . mysqli_error($conn);
die($message);
...
hielo 65 Veteran Poster

You can put your email address.

hielo 65 Veteran Poster

Ah, yes. The procedural style needs the connection handle. Try:

 $result = mysqli_query($conn, "select * from table where `username`='" . mysqli_real_escape_string($conn,$username) . "' and `passwd` = sha1('" . mysqli_real_escape_string($conn,$password) . "')");
hielo 65 Veteran Poster

Try:

<?php
function login($username, $password)
{
    // check username and password with db
    // if yes, return true
    // else throw exception
    // connect to db
    $conn = db_connect();

    // check if username is unique
    $result = mysqli_query($conn, "select * from table where `username`='" . mysqli_real_escape_string($username) . "' and `passwd` = sha1('" . mysqli_real_escape_string($password) . "')");

    if (!$result)
    {
        // email yourself the error details
        $to = 'yourUsername@domain.com';
        $subject ='db error';
        $message = 'DB Error: ' . mysqli_error($conn);
        mysqli_close($conn);

        mail($to, $subject, $message, "From: webmaster@yourDomain.com");

        throw new Exception('Could not log you in.', __LINE__ );
    }

    if (mysqli_num_rows($result)>0)
    {
        return true;
    }
    else
    {
        throw new Exception( 'Could not log you in.', __LINE__);
    }
}

If you update it to include your email address, it should email the details of the error. Your select statement needs an actual table name. You currently have table as the table name. You probably meant user (or something similar).

hielo 65 Veteran Poster

That is your login form (not your login() function), which is sending/submitting the username and password to member.php. So, in member.php you should have function login(...){...}. Based on one of your other posts, my guess is that it is defined in require_fns.php.

hielo 65 Veteran Poster

OK, so clearly the login() function is throwing an exception. Print out the exception message within the catch clause so you know why the login is failing, and then inspect your login() function to see why it is throwing the error. It would help if you posted your login() function.

hielo 65 Veteran Poster

I can get in, but when I go to log in after, it won't let me log in

What you posted doesn't help. You need to post what you are doing before it gets to that point.

and I can re-create the same member multiple times.

If you are using a database (as opposed to a file), it sounds like you are missing a unique index on the username field.

hielo 65 Veteran Poster

Update: On my last post, move line 78 to the end of the file (after line 155):

...
</html>
<?php
mysqli_close($link);
hielo 65 Veteran Poster

I suggest that you use only one db connection file:

<?php
// connect-db.php
if(!isset($mysql_db))
{
  die('You forgot to define $mysql_db first.');
}

$conn_error = 'Could not connect.';

$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';

$link = mysqli_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_db);

if (!$link) 
{
    die($conn_error);
}
?>

Then index.php would be:

<?php
# specify your table first
$mysql_db = 'attendance';

# include your db connection file
require 'connect-db.php';

#if it makes it here, then the connection was successful.
# now do the query for this file
$result = mysqli_query($link, "SELECT * FROM `$mysql_db`");


$errors=Array();

// Now there is student_id hidden field in the first column.  It should correspond to the unique id 
// record on your table.
if( array_key_exists('student_id',$_POST) )
{
    // Notice that the name of the hidden field is "student_id[]" (with brackets at the end).  This
    // way PHP "sees" an array of student_id fields.
    foreach($_POST['student_id'] as $id)
    {
        $id = intval($id);
        // The corresponding fields for a given row also have the student_id. So, instead of 
        // name="present", you now have name="present[X]" where X is the actual student_id for that
        // row.  If this is not clear, look at the browser's source code and you inspect one of the
        // rows.  Look at what's generated for student_id and how that field's value is 
        // "tied/related" to the other fields on that row.
        if(  array_key_exists('timeIn',$_POST) && array_key_exists('timeOut',$_POST) && array_key_exists('remarks',$_POST) && isset($_POST['timeIn'][$id]) && isset($_POST['timeOut'][$id]) && isset($_POST['remarks'][$id]) )
        {
            if (!empty($id))
            {
                // query to see if record …
hielo 65 Veteran Poster

Try:

function getWorkingDays($startDate, $endDate, $holidayList)
{
    $working_days = 0;
    $begin = strtotime($startDate);
    $end = strtotime($endDate);
    if($begin > $end)
    {
        echo "startdate is in the future! <br />";
    }
    else
    {
        foreach($holidayList as $k=>$v)
        {
            $holidayList[$k] = strtotime($v);
        }

        $no_days = 0;
        $weekends = 0;
        $holidays = 0;
        while($begin <= $end)
        {
            $no_days++;
            $what_day = date("N", $begin);
            if($what_day > 5)
            {
                $weekends++;
            }
            elseif( in_array($begin,$holidayList) )
            {
                $holidays++;
            }
            $begin += 86400;
        };
        $working_days = $no_days - ($weekends + $holidays);
    }
    return $working_days;
}
hielo 65 Veteran Poster

The second parameter of function createChatBox(chatboxtitle,minimizeChatBox) should be chatName (not minimizeChatBox) since you are using chatName on line 19.

hielo 65 Veteran Poster

Try saving the following as test.php and give it a try:

<?php
if( array_key_exists('Submit',$_POST) )
{
    if(!empty($_FILES))
    {
        // these are your "settings"
        $myFiles=Array(  'pri'      => Array('required'=>true, 'destination'=>'/path/to/save/directory/', 'allowed'=>'pdf;doc;docx', 'label'=>'Pri') 
                        ,'oresult'  => Array('required'=>true, 'destination'=>'/path/to/save/directory/', 'allowed'=>'pdf;doc;docx', 'label'=>'OResult')
                        ,'oresult2' => Array('required'=>true, 'destination'=>'/path/to/save/directory/', 'allowed'=>'pdf;doc;docx', 'label'=>'OResult2')
                        ,'dob'      => Array('required'=>true, 'destination'=>'/path/to/save/directory/', 'allowed'=>'pdf;doc;docx', 'label'=>'DOB')
                        ,'photo'    => Array('required'=>true, 'destination'=>'/path/to/save/directory/', 'allowed'=>'png;jpg;jpeg;gif', 'label'=>'Photo')
                        );

        //this is where the detected errors will be stored
        $errors=Array();

        foreach($myFiles as $field=>$prop)
        {
            if( array_key_exists($field, $_FILES) )
            {
                // http://php.net/manual/en/features.file-upload.php
                // http://php.net/manual/en/features.file-upload.errors.php
                if( true===$prop['required'] )
                {
                    if($_FILES[$field]['error']===UPLOAD_ERR_NO_FILE)
                    {
                        $errors[] = $prop['label'] . ' is a required field.';
                    }
                    elseif($_FILES[$field]['error']!==UPLOAD_ERR_OK)
                    {
                        $errors[]='File upload for ' . $prop['label'] . ' failed with error code ' . $_FILES[$field]['error'] . '.';
                    }
                }
                elseif($_FILES[$field]['error']!==UPLOAD_ERR_OK)
                {
                    $errors[]='File upload for ' . $prop['label'] . ' failed with error code ' . $_FILES[$field]['error'] . '.';
                }

                if(!empty($errors))
                {
                    break;
                }
                else
                {
                    $prop['destination'] = array_key_exists('destination', $prop) ? $prop['destination'] : getcwd().'/uploads';
                    $prop['destination'] = rtrim($prop['destination']," \t\n\r\0\x0B\/.")

                    if( !is_dir($prop['destination']) )
                    {
                        $errors[] = 'The destination directory for '.$prop['label'].' does not exist.';
                    }
                    else
                    {                   
                        // sanitize filename -- allows only letters, numbers, underscore and periods
                        $_FILES[$field]['name'] = preg_replace('/[^\w\.]/', '', $_FILES[$field]['name']);

                        if( !preg_match('/\w+\.(\w+)$/', $_FILES[$field]['name'],$m) )
                        {
                            $errors[] = 'Invalid file name for ' . $prop['label'] . '.';
                        }
                        else
                        {
                            // check ending file extension
                            $prop['allowed'] = preg_split('/\W+/', strtolower($prop['allowed']), -1, PREG_SPLIT_NO_EMPTY);

                            if( !in_array( strtolower($m[1]), $prop['allowed']) )
                            {
                                $errors[] = 'The attached file type for ' . $prop['label'] . ' is not accepted.';
                            }
                            else
                            {
                                // attempt to move file to …
hielo 65 Veteran Poster

How can i simply review Q/A on forum databases

See if you find it under Finder > My Favorite Forums > Databases. I too was gone for a long time, and now that I am back, the Databases shows up there (along with other ones). If you were actively posting on that forum, it will probably be there already. I totally understand your frustration. I am yet to find a way to modify/update My Favorite Forums or My Favorite Tags list or an FAQs page with instructions on how to achieve that.

If it is not under Finder > My Favorite Forums, then try Finder > Featured Forums. Otherwise, as cereal suggested, the blue icon on the upper-right-hand-side of the page contains the main categories.

hielo 65 Veteran Poster

Try the fetch() function given at http://php.net/manual/en/mysqli-stmt.bind-result.php#102179. By now you probably realized that to use bind_result() you need to provide variable names to it, one for every field you are selecting in your query. The fetch() function in the user comment mentioned above is dynamically creating variable references:

$meta = $result->result_metadata();
 while($field = $meta->fetch_field())
        $variables[] = &$data[$field->name]; // pass by reference

To call it, try:

...
$stmt->execute();//execute your prepared statement
$data = fetch($stmt);
echo '<pre>',print_r($data,true),'</pre>';
hielo 65 Veteran Poster

Read through the comments of the script below. Notice that the underlying html markup has changed.

<!DOCTYPE html>
<?php
require 'connect2.inc.php';

$errors=Array();

// Now there is student_id hidden field in the first column.  It should correspond to the unique id 
// record on your table.
if( array_key_exists('student_id',$_POST) )
{
    // Notice that the name of the hidden field is "student_id[]" (with brackets at the end).  This
    // way PHP "sees" an array of student_id fields.
    foreach($_POST['student_id'] as $id)
    {
        $id = intval($id);

        // The corresponding fields for a given row also have the student_id. So, instead of 
        // name="present", you now have name="present[X]" where X is the actual student_id for that
        // row.  If this is not clear, look at the browser's source code and you inspect one of the
        // rows.  Look at what's generated for student_id and how that field's value is 
        // "tied/related" to the other fields on that row.
        if(  array_key_exists('timeIn',$_POST) && array_key_exists('timeOut',$_POST) && array_key_exists('remarks',$_POST) && isset($_POST['timeIn'][$id]) && isset($_POST['timeOut'][$id]) && isset($_POST['remarks'][$id]) )
        {
            if (!empty($id))
            {
                // query to see if record exist on db
                $query = "SELECT COUNT(*) as `total` FROM `attendance` WHERE `id`='$id'";
                $query_run = mysql_query($query);
                if(!$query_run)
                {
                    echo 'Error ',__LINE__,': Sorry, we couldn\'t update at this time. Try again later.';
                }
                else
                {
                    // retrieve the query result
                    $row = mysql_fetch_assoc($query_run);

                    if( 0===intval($row['total']) )
                    {
                        $errors[$id] = 'Error ' . __LINE__ . ': There is no matching record for StudentID '.$id.'.';
                    }
                    elseif( 1===intval($row['total']) )
                    {
                        $present = (int)(array_key_exists('present',$_POST) && array_key_exists($id, $_POST['present']));
                        $late …
hielo 65 Veteran Poster

It is not clear how you are initializing A[] but on line 6, if the value of A[j] is more than 166, then on line 15, the numeric index for SUM would be out of bounds.

hielo 65 Veteran Poster

Refer to get_result():
http://php.net/manual/en/mysqli-stmt.get-result.php

// this is where the data will be stored/buffered
$data = Array();

$stmt = $dbconn->prepare("SELECT * FROM `members` WHERE username=? AND password=?");

$stmt->bind_param("ss", $username, $password);

$stmt->execute();

$result = $stmt->get_result();

//iterate over the result retrieving one row at a time    
while ($row = $result->fetch_array(MYSQLI_NUM))
{
     //buffer the row onto $data
    $data[] = $row;
}

if( 0==count($data) )
{
     echo 'No records found.';
}
else
{
    print_r($data);
}
hielo 65 Veteran Poster

I have declared the variables in the register_new.php script as $username=$_POST['username'];
$passwd=$_POST['passwd'];

The problem is not $username. The problem is $_POST['username']. If your page is hosted at yoursite.com/member.php, when you type that url directly onto the browser's address bar you are submitting a GET request (or if you have a <form> that does not explicitly specify method="post", it defaults to a GET request), not a POST request. Yet, line 8 of your script assumes that there is a field/key named username in$_POST. You need to test to see if username exists in $_POST before you attempt to use it. Try:

<?php
// include function files for this application
require_once('require_fns.php');
session_start();

//create short variable names
$username = null;
$passwd   = null;

if( array_key_exists('username', $_POST) )
{
    $username = $_POST['username'];
}

if( array_key_exists('passwd', $_POST) )
{
    $passwd = $_POST['passwd'];
}

if ($username && $passwd) {
// they have just tried logging in
  try  {
    login($username, $passwd);
    // if they are in the database register the user id
    $_SESSION['valid_user'] = $username;
  }
  catch(Exception $e)  {
    // unsuccessful login
    do_html_header('Warning:');
    echo 'You have not filled the form out correctly.
          Please go back and try again.';
    //do_html_url('login.php', 'Login');
    do_html_footer();
    exit;
  }
}
do_html_header('Home');
check_valid_user();
// give menu of options
display_user_menu();
do_html_footer();
?>
rproffitt commented: Post gets +1 +10
hielo 65 Veteran Poster

When obj.Set_draw ("Rectangle"); is executed, line 90 allocates memory for a Rectangle and obj points to it:

obj ---> +---+ Rectangle
         |   |
         +---+

You then execute: obj.Set_draw ("Circle");, resulting in:

         +---+ Rectangle
         |   |
         +---+

obj ---> +---+ Circle
         |   |
         +---+

Notice that what your line 90 did the second time around is to just allocate memory for the specified shape (Circle) and had obj point to it. The previous shape (Rectangle) is not destroyed because there is no automatic garbage collection in C/C++. You (the programmer) are responsible for keeping track of it and reclaiming it when no longer needed. Hence the reason you are not seeing the destructor being called -- it is still "hanging around" but you have no way to dereference (aks: memory leak).

You can fix this by initializing obj to nullptr. Whenever Set_draw() is called, delete whatever obj points to only if it is not nullptr - read comments in code below

class Draw
{
    private:
        IShape *obj;

    public:
        // provide a constructor that initializes obj to nullptr.  That way when
        // Set_draw() gets called the first time, you will know that if obj==nullptr
        // then there is no shape in obj yet, and hence there is nothing to delete.
        // After the first call, then you obj would have a reference to some shape
        Draw():obj(nullptr){}

        void Set_draw(string param)
        {
            // The first time you create a shape, this clause will be skipped
            // since initially obj==nullptr.  After the …
hielo 65 Veteran Poster

How could I request id, name only from users for example

In general, you would just need SELECT tableName.columnName, otherTableName.columnName FROM ....

The order in which you list the columns/fields after the SELECT doesn't matter. So you could do:
SELECT user.id, user.name, forums.lastAutherID FROM forums INNER JOIN users ON forums.lastAuthorID = users.id or SELECT forums.lastAutherID, user.id, user.name FROM forums INNER JOIN users ON forums.lastAuthorID = users.id.

As a matter of fact, just because you can have a JOIN between/among tables it does not mean you are required to select a field from evey joined table. As an example, the following selects only from user table even though there is an inner join with forums:
SELECT user.id, user.name FROM forums INNER JOIN users ON forums.lastAuthorID = users.id.

Oh and is it possible to mash more than 2 tables

Yes. Just add more join clauses ON the related column. For example, on your original post, forums.lastAuthorID is related to user.id. So if you have a other tables with fields user_id that are also related to user.id, then your query would be:

SELECT * FROM (forums INNER JOIN users ON forums.lastAuthorID = users.id
                                             (INNER JOIN thirdtable ON thirdTable.user_id = user.id)
                                             (INNER JOIN fourthtable ON fourthTable.user_id = user.id)
                             )
hielo 65 Veteran Poster

try:
SELECT * FROM forums AS F INNER JOIN users AS U ON F.lastAuthorID = U.id

To help you understand ... forums AS F simply makes F an alias for forums. Similarly, ... users as U makes U an alias for users. The AS keyword is optional, so it could have been written as
SELECT * FROM forums F INNER JOIN users U ON F.lastAuthorID = U.id and it still would have worked. You are not required to "alias" the table names, so you could have also written it as SELECT * FROM forums INNER JOIN users ON forums.lastAuthorID = users.id. Notice that the ON clause uses the actual table names since there are no prefixes.

hielo 65 Veteran Poster

On my proposed design I basically got rid of the red table (since it appears to be only a lookup table with three records), and instead took the red TicketID column and used it as the TicketType in the light-blue table. The records on the light-blue (Ticket) table would look as follows:

Ticket (On this table TicketID is PK auto_increment)
=====
TicketID    TicketNumber  TicketType 
1                1234567  1
2                2222222  2
3                3333333  3
4                7777777  1
5                8888888  2

Then in the purple table:

TicketID CheckListID status
1              1                   complete
1              3                   
1              4                   
1              5
1              7 
2              2
2              3
2              6
2              8
3              4                   complete
3              7                   complete

To search based on a specific TicketNumber:

SELECT FROM Ticket A INNER JOIN purpletable B on A.TicketID=B.TicketID WHERE A.TicketNumber =2222222

Similarly, to search for specific TicketID

SELECT FROM Ticket A INNER JOIN purpletable B on A.TicketID=B.TicketID WHERE A.TicketID = 2
hielo 65 Veteran Poster

Based on what you posted, theTicket# column on the light-blue table (to the right of the red table) has unique values. If this is true, then merge Ticket# with the red table and on the purple table instead of Ticket#, use TicketID.

                   TicketCheckList
                   ===============
              +->* TicketID FK
              |    CheckListID FK *<-----------+
              |                                |
              |                                |
              |                                |
Ticket(Red)   |                                |   CheckList (Green)
======        |                                |   =========
TicketID PK --+ 1                            1 +-- CheckListID PK
TicketType    |                                |   Description
TicketNumber  |                                |   Notes
              |                                |
              |                                |
              |                                |
              |    UserTicketCheckList(Purple) |
              |    =========================== |
              +->* TicketID FK                 |
                   CheckListID FK *<-----------+
              +->* UserId FK
              |    completedIndicator
              |    Date
              |    Notes
User          |
====          |
UserID PK ----+ 1

On your diagram, I don't know why you have the dark-blue table(below the red one, which I labeled above as TicketCheckList), but the info in that table is also in UserTicketCheckList. So if you don't need it, you can get rid of it.

hielo 65 Veteran Poster

If you are going to use header('Location: ...'), you cannot use echo. So your else clause should be:

            ...
            else
            {
                $_SESSION['id'] = $row['id'];
                $_SESSION['user'] = $myusername;
                $_SESSION["startTime"] = date("r");

                //you call header AFTER you have set your session variables.
                header("Location: index.php");
                exit;
            }
hielo 65 Veteran Poster

Therefore, to allow for both, i would need a way for the PHP code to detect whether a request was an AJAX request or not.

I don't know how you are submitting the ajax requests, but if you are using jQuery, it already contains a header named X-Requested-With which is set to XMLHttpRequest. So, on the server, you should be able to see if the header exists in the $_SERVER variable:

if(array_key_exists('HTTP_X_REQUESTED_WITH',$_SERVER) && 'XMLHttpRequest'==$_SERVER['HTTP_X_REQUESTED_WITH'])
{
  //process ajax request here
}

If you are not using jQuery, then once you have the ajax object call the setRequestHeader() method - ex:

//here xhttp is an instance of the XMLHttpRequest object
xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
hielo 65 Veteran Poster

However, i would also like to get the roleid returned

That implies that you don't know the initial roleid. So your function should not be accepting $roleid and shouldn't be part of the WHERE clause since you don't know what it is. Try:

function getUserRole($username)
{
    $roleid = false;
    $con=dbConnect();
    $query="select userrole.roleid from user 
                    inner join userrole on user.id = userrole.userid 
                    inner join role on role.id = userrole.roleid 
            where username = :username";
    $sql=$con->prepare($query);
    $sql->bindValue(':username',$username);
    $sql->execute();
    $sql->store_result();
    if($sql->num_rows>0)
    {
        $sql->bind_result($roleid);
        $sql->fetch();
    }
    $sql->free_result();
    $sql->close();
    $con->close();
return $roleid;
}
hielo 65 Veteran Poster

Try:

<select name="cmbclient">
  <option value=""></option>
<?php
      /* select only the fields you need.  Doing SELECT * gets you all the fields on the table, even the one you don't need! */
      $dataSql = 'SELECT reff_number, name FROM pelanggan ORDER BY name';
      $dataQry = mysql_query($dataSql, $koneksidb) or die ("Gagal Query".mysql_error());
      while ($dataRow = mysql_fetch_assoc($dataQry))
      {
        if ($dataRow['reff_number'] !== $_POST['cmbclient'])
        {
            echo '<option value="',htmlentities($dataRow['reff_number'],ENT_QUOTES),'">', htmlentities($dataRow['name'] . ' (' . $dataRow['reff_number'] . ')',ENT_QUOTES), '</option>',PHP_EOL;
        }
        else
        { 
            echo '<option value="',htmlentities($dataRow['reff_number'],ENT_QUOTES),'" selected>', htmlentities($dataRow['name'] . ' (' . $dataRow['reff_number'] . ')',ENT_QUOTES), '</option>',PHP_EOL;
        }
      }
      mysql_free_result($dataQry);
?>
</select>
hielo 65 Veteran Poster

By selecting organization, it will calculate how many customers are there to send SMS, It will display the SMS Count along with all managers names using JQUERY AJAX.
For counting this value,it takes so much time in online,
How to solve that?.

Is the customer list on a file? If so, then try porting it to a database. If your list is already on a database, then try adding an index on the field by which you are searching.

hielo 65 Veteran Poster

Indeed! That is certainly news to me. FYI: that seems to be a MySQL-specific feature. It is not standard sql (see section 13.8 <insert statement> at http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt).

On another note, the following line:

if (checkForm($row_pages['source'], '<form')){ /*...the sql injection tests go here...*/ }

will not perform any of the sql injection test on the relevant page whenever the page in question does not have a <form> in it. I looked at the site with the masks, and I did not find any page with forms in them, so the sample url you supplied is not the ideal site on which to try out your tests.

hielo 65 Veteran Poster

The main issue is, it's not detecting any vulnerability

How do you know that it is not detecting any vulnerabilities? Are you echoing (and inspecting) the intermediate results

so it doesn't post into injection_result table

Well, that's because what you have is a hybrid of the INSERT and UPDATE statements. The correct syntax is:

INSERT INTO `tableName` (`fieldName1`,`fieldName2`) VALUES ('value1', 'value2');
-- and for updates
UPDATE `tableName` SET `fieldName1` = 'value1', `fieldName2`='value2'

After executing a query, you should check to see if it fails. You are not doing error checking after executing queries. Otherwise you would have found the error.

hielo 65 Veteran Poster

Is it possible to be able to have those printed out results turn into a textbox where you, as the user, can edit them?

That is what you need to on the server when you first generate the page. Intead of

echo "<td>". $row["FirstName"] . "</td>";

you need

echo "<td><input type='text' name='firstname' value='". htmlentities($row["FirstName"],ENT_QUOTES) . "'/></td>";

The same goes for the other fields that you wish to edit. Refer to http://php.net/manual/en/function.htmlentities.php if you are not familar with htmlentities().

hielo 65 Veteran Poster

I want to know if I can use the event listener to help trigger a php code that will make a query to update that specific user

Yes. Give all your update buttons a common class, and your delete buttons a common class (see sample code below). Then you bind an event listener for the update buttons, and one for the delete buttons. If you give your <tr> an id that references the EmployeeID (assuming that EmployeeID is unique on that query result), then you can determine which record to UPDATE/DELETE.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
<script>
$(document).ready(function()
{

        $('.update-button').on('click', function(){
                        // go to jquery's site and read about the closest() method
                        var tr = $(this).closest("tr");

                        // you will need to "collect" the data in the text fields
                        // since this is what the user has changed
                        var fields={};
                        $("input",tr).each(function(){
                            //here I am dynamically creating:
                            //  fields.firstname and assigning it its corresponding text field value
                            //  fields.lastname and assigning it its corresponding text field value
                            fields[$(this).attr("name")] = $(this).val();
                        });

                        fields.action_requested="update";

                        // if you open your page in chrome and do right-click > inspect > console
                        // you should see the contents of fields
                        if( typeof(console)!='undefined')
                        {
                            console.log( 'fields=',fields );
                        }

                        //send the data to process.php
                        $.ajax({ method: "POST",
                                  url: "process.php",
                                  data: fields
                                })
                               .done(function( msg ) {
                                    alert( "Data Saved: " + msg );
                                });
                });

        $('.delete-button').on('click', function(){
                        // go to jquery's site and read about the closest() method
                        var tr = $(this).closest("tr");
                        var fields={'action_requested':'delete'};
                        // …
hielo 65 Veteran Poster

If you noticed carefully, I used $(this).hide();. Within that function this refers to the element that triggered the action. So it only applies to the clicked button.

hielo 65 Veteran Poster

In HTML, an elements id attribute must be unique. Since you have <button id='button'>Update</button> within the while construct, all the buttons are getting the same id value. By contrast, your $('#button') works only on the first button because it was expecting to find only one to begin with! What you need to do is change id to class, and the # to .

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
<script>
$(document).ready(function()
{
        $('.button').on('click', function()
                {
                        $(this).hide();
                });
});
</script>
</head>
<body>
<?php
        include_once("sqlConnect.php");
        $sql = "SELECT * FROM engineers ORDER BY LastName";
        $result = mysqli_query($conn, $sql);
        echo "<table style='width:85%'>";
        echo "<tr>";
        echo "<td>FirstName</td>";
        echo "<td>LastName</td>";
        echo "<td>Extension</td>";
        echo "<td>Office</td>";
        echo "<td>Mobile</td>";
        echo "<td>Email</td>";
        echo "<td>PersonalPhone</td>";
        echo "<td>TelephoneAgent</td>";
        echo "<td>UserID</td>";
        echo "<td>EmployeeID</td>";
        while($row = mysqli_fetch_assoc($result))
        {
                echo "<tr>";
                echo "<td>". $row["FirstName"]          . "</td>";
                echo "<td>". $row["LastName"]           . "</td>";
                echo "<td>". $row["Extension"]          . "</td>";
                echo "<td>". $row["Telephone"]          . "</td>";
                echo "<td>". $row["Mobile"]             . "</td>";
                echo "<td>". $row["Email"]              . "</td>";
                echo "<td>". $row["PersonalPhone"]      . "</td>";
                echo "<td>". $row["TelephoneAgent"]     . "</td>";
                echo "<td>". $row["UserID"]             . "</td>";
                echo "<td>". $row["EmployeeID"]         . "</td>";
                echo "<td><button type='button' class='button'>Update</button></td>";
                echo "</tr>";
        }
        echo "</table>";
?>
</body>
</html>
hielo 65 Veteran Poster

Are you sure that your $row_injection_text['inject_code'] has a value? Meaning, have you tried running your LEFT JOIN query in an sql tool to verify that you are getting the expected results? Or even simpler, does it work when you try INNER JOIN?

The relevant block of code in question seems fine:

<?php
//save this as test.php and try it out
$row_pages = Array('link'=>'http://domain.com/mask_details.php?mask=28&page=1');
$row_injection_text=Array('injection_code'=>"' ' or 1=1 --");

            $urls = parse_url($row_pages['link']);
            echo '<pre>',__LINE__,'. ',print_r($urls,true),'</pre>';
            parse_str($urls['query'], $query_string);
            $get_inject = "";
            if (!empty($query_string))
            {
                $i = 0;
                foreach ($query_string as $var => $value)
                {
                    $get_inject .= (($i==0) ? "?" : "&") . $var . "=" . $row_injection_text['injection_code'];
                    $i++;
                }
            }
            $url_to_inject = $urls['scheme'] . "://" . $urls['host'] . $urls['path'];

echo $url_to_inject.$get_inject;