Jump to content

Hobbyist_PHPer

Members
  • Posts

    119
  • Joined

  • Last visited

Posts posted by Hobbyist_PHPer

  1. Stmt objects use the fetch method. The result objects (as in your first query) use fetch_assoc.

     

    For the life of me, I can't seem to figure out the correct syntax, to make this code work...

    $sql = "SELECT AgenciesAgents.AgentID, Agents.AgentFirstName, Agents.AgentLastName
        FROM AgenciesAgents 
        LEFT JOIN Agents ON AgenciesAgents.AgentID = Agents.AgentID
        WHERE AgenciesAgents.AgencyID = ?
        ";
    if ($stmt = $mysqli -> prepare($sql))
    {
        $stmt->bind_param("i", $AgencyID);
        $stmt->execute();
        while ($row = $stmt -> fetch_assoc())
        {
            echo '<p><span style="vertical-align: top; color: #515151;">'.$row['AgentLastName'].', '.$row['AgentFirstName'].'</span><a href="agency-agent-correlations.php?function=deletecorrelation&agencyid='.$AgencyID.'&agentid='.$row['AgentID'].'" onclick="return confirm(\'Are you certain you wish do delete this agent?\');"> <img src="images/delete_icon.png" width="20" height="20" /></a></p>';
        }
        $stmt -> close();
    }
    
  2. So he does - missed that.

     

    Only open the connection once at top of script and pass the connection to any functions that need it.

     

    It will be closed automatically at end of script. The only time you need to open mid-script is if you change to another server.

     

    So what you're saying is, don't close the connection until the end of the page, after all of the queries on that page are completed?

  3. and since you are closing the mysqli connection after the first block of code, it is not available later in the program.

     

    You know, I'm glad you brought that up, because I was thinking the same thing, so how do you go ahead and open it back up, because in the connection file is where it is originally instantiated...

  4. I'm not really sure what's going on, but I have been replacing all of my mysql queries with mysqli, and so far it is working fine, until I got to this one in particular...

     

    I am getting this error... "Warning: mysqli::prepare(): Couldn't fetch mysqli"  and this error... "Warning: mysqli::close(): Couldn't fetch mysqli"

     

    I researched that problem, but none of what others had to say about fixing it, applied nor worked for me.

     

    What's funny about it is that just above that query, is another query in which has no problems...

     

    Here's the top query that works fine:

    $sql = "SELECT * FROM Agencies ORDER BY AgencyName ASC";
    if ($result = $mysqli -> query($sql))
    {
        while ($row = $result -> fetch_assoc())
        {
            echo '<option value="'.$row['AgencyID'].'">'.$row['AgencyName'].'</option>';
        }
        $result -> free();
    }
    $mysqli -> close();
    

    Now here's the query that is throwing the errors:

    $sql = "SELECT AgenciesAgents.*, Agents.AgentFirstName, Agents.AgentLastName
        FROM AgenciesAgents 
        LEFT JOIN Agents ON AgenciesAgents.AgentID = Agents.AgentID
        WHERE AgenciesAgents.AgencyID = ?
        ";
    if ($stmt = $mysqli -> prepare($sql))
    {
        $stmt->bind_param("i", $AgencyID);
        $stmt->execute();
        while ($row = $stmt -> fetch_assoc())
        {
            echo '<p><span style="vertical-align: top; color: #515151;">'.$row['AgentLastName'].', '.$row['AgentFirstName'].'</span><a href="agency-agent-correlations.php?function=deletecorrelation&agencyid='.$AgencyID.'&agentid='.$row['AgentID'].'" onclick="return confirm(\'Are you certain you wish do delete this agent?\');"> <img src="images/delete_icon.png" width="20" height="20" /></a></p>';
        }
        $stmt -> free();
    }
    $mysqli -> close();
    
  5. Hello everyone, so I just had PHP 5.5.5 installed on my server so that I could take advantage of the new password hashing API, but I'm having problems, it's not validating as true...

     

    Here's my login script code

    <?
    if (isset($_POST['loginform']))
    {
        session_start();
        
        require "../includes/connection.inc";
        require "../includes/functions.php";
    
        $Uname = clean($_POST['Username']);
        $Username = strtolower($Uname);
        $Password = clean($_POST['Password']);
    
        $sql = "SELECT ExaminerID, ExaminerName, ExaminerEmail, ExaminerPassword FROM Examiners WHERE ExaminerUsername = ? AND ExaminerPassword = ?";
        if ($stmt = $mysqli -> prepare($sql))
        {
            $stmt -> bind_param("ss", $Username, $Password);
            $stmt -> execute();
            $stmt -> bind_result($ExaminerID, $ExaminerName, $ExaminerEmail, $ExaminerPassword);
            $stmt -> fetch();
            if (password_verify($Password, $ExaminerPassword))
            {
                session_regenerate_id();
                $_SESSION['ExaminerID'] = $ExaminerID;
                $_SESSION['ExaminerName'] = $ExaminerName;
                $_SESSION['ExaminerEmail'] = $ExaminerEmail;
                session_write_close();
                $stmt -> close();
                $mysqli -> close();
                header("location: https://*****************/index.php");
            }
            else
            {
                $stmt -> close();
                $mysqli -> close();
                header("location: login.php?failed");
                exit();
            }
        }
        else
        {
            $stmt -> close();
            $mysqli -> close();
            header("location: login.php?failed");
            exit();
        }
    }
    ?>
    
  6. So, I'm needing someone to create me a datagrid for my project... I don't care if it's home-brewed, commercial, or open source, but I need an AJAX/jQuery datagrid with the following requirements...

     

    • Show 10, 25, 50, 100 (Dropdown box) entries
    • Showing 0 to 10 of 56 entries
    • Pagination ... First, Previous, 1, 2,3,4,5,etc.,Next, Last
    • Sortable columns
    • Click: when a row is clicked, it should pass the ID so that a Details view can show the details

     

    There's not really any special formatting to speak of, just a decimal value needs to show in money format and a date/time field needs to formatted

     

    I'm using php 5.3.13 and mysql 5.1.63

     

    As of 9/20/2012 @ 3:24 pm (-6 utc) I'm accepting offers ... Please PM me with how long and how much...

     

    Please reply by PM and I will do so as well...

  7. I'm surprised this produces something at all, as you have quite a few validation issues with your HTML code. Make sure your code is valid first, then monitor the developer tools of your browser to see if there's any JS errors in your code somewhere.

     

    WHAT?!?

  8. Your JS is within a script tag that includes external code. You need separate script tags:

     

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    <script type="text/javascript">
        function SubmitThisForm() {
            location.href = 'statuses.php';
        }
    </script>

     

    Thank you... I thought I could just save code by putting it together... Obviously I was wrong... Your suggestion fixed it, thank you very much...

  9. Hello Everyone...

     

    I'm hoping someone can help me with this table grid, I've been pulling out my hair for a couple days now...

     

    I attempted a jQuery solution but could not make it work... So now I'm trying to make it work with just JavaScript...

     

    What I'm trying to do is simply allow a user to click on a row to pass an "id" value which would then display the entire data for that "id" ... essentially just a master/detail...

     

    Here's my current JavaScript:

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js">
        function SubmitThisForm() {
            location.href = 'statuses.php';
        }
    </script>
    

     

    And here's the form table row code, notice the onClick in the <tr>:

    extract($row);
    $rowCounter += 1;
    echo '<form action="statuses.php" method="post">';
    echo '<input type="hidden" id="ID" name="ID" value="'.$OrderTicketID.'" />';
    echo '<tr class="'.OddOrEven($rowCounter).'" style="line-height: 1.75;" onClick="SubmitThisForm(this)">';
    echo '<td style="padding-left: 5px;"> </td>';
    echo '<td>'.$OrderTicketFirstName.' '.$OrderTicketLastName.'</td>';
    echo '<td>'.$BrokerCompanyName.'</td>';
    echo '<td>'.$InsuranceCarrier.'</td>';
    echo '<td>'.$AgentCompanyName.' '.$AgentName.'</td>';
    echo '<td>'.$OrderTicketPolicyType.'</td>';
    echo '<td>'.number_format($OrderTicketPolicyAmount, 2).'</td>';
    echo '<td>'.$OrderTicketCurrentStatus.'</td>';
    echo '<td>'; if($OrderTicketScheduledDateTime != "0000-00-00 00:00:00"){echo date('n-d-Y @ g:i a', strtotime($OrderTicketScheduledDateTime -6));} echo '</td>';
    echo '</tr>';
    echo '</form>';
    

     

    By the way, it currently does nothing...

  10. Thank you for pointing me to that, lots of great information...

     

    I only have one question, upon successful login, I need some session variables loaded with their counterpart values from the database, and I don't really understand PHP OOP, I prefer procedural ... Could you help me out with this bit of code?

     

    First I'll show you the code that I put together from what I learned from your tutorial...

    if (isset($_POST['op']))
    {
        session_start();
        require_once '/home/*****/config.php';
        require_once '../includes/functions.php';
        require_once '../includes/PasswordHash.php';
        
        ForceHTTPS();
        
        $db = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
        if (mysqli_connect_errno())
                fail('MySQL connect', mysqli_connect_error());
        
        $user = get_post_var('Username');
        /* Sanity-check the username, don't rely on our use of prepared statements
        * alone to prevent attacks on the SQL server via malicious usernames. */
        if (!preg_match('/^[a-zA-Z0-9_]{1,60}$/', $user))
                fail('Invalid username');
    
        $pass = get_post_var('Password');
        
        /* Don't let them spend more of our CPU time than we were willing to.
        * Besides, bcrypt happens to use the first 72 characters only anyway. */
        if (strlen($pass) > 72)
                fail('The supplied password is too long');
    
        $op = $_POST['op'];
        if ($op !== 'login')
                fail('Unknown request');
        if ($op === 'login') {
            $hash = '*'; // In case the user is not found
            ($stmt = $db->prepare('SELECT * FROM Agents WHERE AgentUsername=?'))
                    || fail('MySQL prepare', $db->error);
            $stmt->bind_param('s', $user)
                    || fail('MySQL bind_param', $db->error);
            $stmt->execute()
                    || fail('MySQL execute', $db->error);
            $stmt->bind_result($hash)
                    || fail('MySQL bind_result', $db->error);
            if (!$stmt->fetch() && $db->errno)
                    fail('MySQL fetch', $db->error);
    
            if ($hasher->CheckPassword($pass, $hash)) {
                //Login Successful
                session_regenerate_id();
                $_SESSION['AgentID'] = $row['AgentID'];
                $_SESSION['AgentLicenseCode'] = $row['AgentLicenseCode'];
                $_SESSION['AgentCompanyName'] = $row['AgentCompanyName'];
                $_SESSION['AgentName'] = $row['AgentName'];
                $_SESSION['AgentState'] = $row['AgentState'];
                session_write_close();
                header("location: index.php");
                exit();
            } else {
                //Login failed
                header("location: login.php?failed");
                exit();
            }
            unset($hasher);
            $stmt->close();
        }
        $db->close();
    }
    

     

    So you can probably see where I need the variables set, but I'll repeat that part here...

            if ($hasher->CheckPassword($pass, $hash)) {
                //Login Successful
                session_regenerate_id();
                $_SESSION['AgentID'] = $row['AgentID'];
                $_SESSION['AgentLicenseCode'] = $row['AgentLicenseCode'];
                $_SESSION['AgentCompanyName'] = $row['AgentCompanyName'];
                $_SESSION['AgentName'] = $row['AgentName'];
                $_SESSION['AgentState'] = $row['AgentState'];
                session_write_close();
                header("location: index.php");
                exit();
            }
    

  11. Hello Everyone...

     

    So I've decided to upgrade my current login system that I use for my projects... It uses md5 only ... I've also decided to start using mysqli instead of mysql...

     

    I've spent the last few hours pouring through forums and tutorials on the subject of proper hashing and encryption, and honestly am more confused than when I started searching...

     

    So I was wondering if I could get some php experts from phpfreaks to give me advice on the method that they feel comfortable with using in their projects... and perhaps a tiny example :)

     

    Here's what I had been using...

     

        $Uname = clean($_POST['Username']);
        $Pword = clean($_POST['Password']);
        $Username = strtolower($Uname);
        $Password = md5($Pword);
        
        $result = mysql_query("SELECT * FROM Agents WHERE AgentUsername = '$Username' AND AgentPassword = '$Password'") or die(mysql_error());
        $rowCounter = mysql_num_rows($result);
        if($rowCounter == 1) 
        {
            session_regenerate_id();
            $row = mysql_fetch_assoc($result);
            $_SESSION['AgentID'] = $row['AgentID'];
    

  12. Hello everyone...

     

    So if you're creating an application that will be accessed in multiple timezones, what is the best way of accomplishing that? The current system I have in place seems very clunky and quite a pain in the butt...

     

    Here's how I currently have it set up...

    • The entire application is set to GMT, date_default_timezone_set('UTC'); in the Config.php file
    • I store the user's timezone difference in the database in their preferences, so that when they log in, their time difference is then stored in a session variable, as either plus or minus a certain amount of hours
    • Then every time the user inserts or retrieves a record to/from the database, it adds or subtracts the user's time difference prior to insertion / retrieval

     

    Thank you in advance if you have a better method...

  13. I have been having problems with making a DIV clickable... To rule out any other possibilities, I created a test.php page and it still won't fire when I click on the DIV... The code follows... Can someone please tell me what I'm doing wrong?

     

    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <script src="http://code.jquery.com/jquery-latest.js"></script>
            <script>
                $("#TestDiv").click(function() {
                alert("Handler for .click() called.");
                });
            </script>
            <title>Test</title>
        </head>
        <body>
            <div id="TestDiv" style="width: 100px; border: 1px #000 solid;">
                 Click Here
            </div>
        </body>
    </html>
    

  14. Here's the code that I used...

     

    $BeginningDateTime = date('Y-m-d 00:00:00', strtotime($SelectedDay));
    $EndingDateTime = date('Y-m-d 23:59:59', strtotime($SelectedDay));
    $query = "SELECT OrderTickets.*, Appointments.* FROM Appointments LEFT JOIN OrderTickets ON Appointments.OrderTicketID = OrderTickets.OrderTicketID WHERE Appointments.ExaminerID = '{$_SESSION['ExaminerID']}' AND Appointments.AppointmentStartDateTime BETWEEN '$BeginningDateTime' AND '$EndingDateTime'";
    $result = mysql_query($query);
    while ($row = mysql_fetch_assoc($result))
    {
        $theBeginningTime = date('g:i a', strtotime($row['AppointmentStartDateTime']));
        $theEndingTime = date('g:i a', strtotime($row['AppointmentFinishDateTime']));
        $DatabaseResultsArray[$theBeginningTime] = array(
            $theBeginningTime => array($row['OrderTicketID'],$theEndingTime,$row['WhatsHappening'])
        );
    }
    foreach ($CalendarTimes as $value) 
    {
        $rowCounter += 1;
        echo '<tr class="'.OddOrEven2($rowCounter).'">';
        echo '<td class="time">'.$value.'</td>';
        echo '<td>';
        foreach ($DatabaseResultsArray as $subvalue => $key)
        {
            if ($value == $subvalue)
            {
                echo $key[$subvalue][0].'<br />';
                echo $key[$subvalue][1].'<br />';
                echo $key[$subvalue][2].'<br />';
            }
        }
        echo '</td>';
        echo '</tr>';
    }
    

  15. You query for the data you want, then you store all the records/row-arrays in a php array using the datetime of the appointment as the array index/key (so that you can find the correct record easily later.) As you are looping to produce the output for each time slot, you form a datatime value of that time slot and use that value to test for/retrieve the record/row for that time slot from the php array you created.

     

    That worked, thank you.

  16. Hello everyone...

     

    I'm hoping someone could help with me an issue I'm having... One that I seem to come across quite regularly, and yet have never come up with a good solution...

     

    In this particular case I have an array ... Here's a partial view of it:

    $CalendarTimes = Array
    (
        "12:00 am" => "12:00 am",
        "12:15 am" => "12:15 am",
        "12:30 am" => "12:30 am",
        "12:45 am" => "12:45 am",
        "1:00 am" => "1:00 am",
        "1:15 am" => "1:15 am",
        etc. etc. etc.
    

     

    Now let's say that I have a database table with appointment times... How do I match up the results of the query from the database to the corresponding values in the array? (without creating a loop inside of a loop, which is pretty much useless as I have found out)

     

    Here's my query and while loop:

    $BeginningDateTime = date('Y-m-d 00:00:00', strtotime($SelectedDay));
    $EndingDateTime = date('Y-m-d 23:59:59', strtotime($SelectedDay));
    $query = "SELECT OrderTickets.*, Appointments.* FROM Appointments 
        LEFT JOIN OrderTickets ON Appointments.OrderTicketID = OrderTickets.OrderTicketID 
        WHERE Appointments.ExaminerID = '{$_SESSION['ExaminerID']}' 
        AND Appointments.AppointmentStartDateTime BETWEEN '$BeginningDateTime' AND '$EndingDateTime'";
    $result = mysql_query($query);
    while ($row = mysql_fetch_assoc($result))
    {
        $theBeginningTime = date('H:i:s', strtotime($row['AppointmentStartDateTime']));
        $theEndingTime = date('H:i:s', strtotime($row['AppointmentFinishDateTime']));
    
    }
    

     

    P.S. I know about my deprecated mysql functions

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.