broj1 356 Humble servant Featured Poster

In first version you are missing the other condition ($_SESSION['iiio'] != "pending"). In that case the div is shown by default.

It looks like you are using Bootstrap so you can use the show and hidden classes provided by Bootstrap. I am using ternary expression here since it is most convenient:

<div class="<?php echo $_SESSION['iiio'] == "pending" ? 'show' : 'hidden';?>"
<a href="https://www.paymentgateway.com">
<button align="right" id="completeReg" name="completeReg" class="btn btn-danger my-cart-btn my-cart-b" >Complete RegistrationComplete Registration</button>
</a>
</div>

If you are not using Bootstrap then create the two classes yourself:

.show {
    display: block;
}

.hidden {
    display: none;
}
Mr.M commented: Perfect +6
broj1 356 Humble servant Featured Poster

EDIT: I noticed after posting that the javascript functions are meant to be in a separate JS file. Disregard my 1. remark, sorry.

Had a quick look at the code and there are two obvious error:

  1. The Javascript functions are outside the <html></html> and outside the <body></body> pairs which is not OK. You should put them just before the closing </body> tag.
  2. On line 48 document.getElementById('tb2') an element with ID='tb2' does not exist

The correct code would be (nicely formated):

<!DOCTYPE html> <html lang="en"> <head> <title>Finance</title> <meta charset="UTF-8"> <meta name="finance" content="width=device-width, initial-scale=1.0"> <script src="insertrow.js"></script> <script src="calc.js"></script> <style>
table {
    padding-top: 15px;
}

button{
    margin-left: 15px;
    cursor: pointer;
}
</style> 
</head>
<body> 
<h1>Financial Keeps</h1> 

<button onclick="insertRow()">Add</button> 
<button onclick="deleteRow()">Delete</button> 
<button>Save</button> 
<p><b>Starting Amount: <input type="text" id="tb1" name="tb1" onkeyup="calc(this)"/></b></p> 
<p>To subtract an amount place a minus (-) sign infront of the dollar amount.</p> 

<table id="myTable"> 
<tr> <th>Bill Info</th> <th>Bill Amt</th> <th>Due Date</th> <th></th> </tr> 
<tr> 
<td><input type="text" id="text"/></td> 
<td><input type="number" id="number" onkeyup="calc(this)" /></td> 
<td><input type="text" id="text" /></td> 
<td><input type="checkbox" id="checkbox" /></td> 
</tr> 
</table> 

<p><b>Ending Amount: <span id="update">0</span></b></p> <input type="hidden" id="total" name="total" value="0" /> 
<script>
function insertRow() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(table.rows.length)

    var cell1=row.insertCell(0);
    var t1=document.createElement("input");
        t1.id = "text";
        cell1.appendChild(t1);

    var cell2=row.insertCell(1);
    var x = document.createElement("input");
        x.setAttribute("type","number");
        cell2.appendChild(x);

    var cell3=row.insertCell(2);
    var y = document.createElement("input");
        y.setAttribute("type", "text");
        cell3.appendChild(y);

    var cell4=row.insertCell(3);
    var z = document.createElement("input");
        z.setAttribute("type", "checkbox");
        cell4.appendChild(z);;
}

function deleteRow() {
    document.getElementById("myTable").deleteRow(2);
}   

var x = 0;
var y = 0;
var z = 0;
function calc(obj) {
    var e …
broj1 356 Humble servant Featured Poster

I tried your code and the table gets generated OK. I get this:

Age Beg Bal Interest    Deposits    Ending Bal
45.00   2000.00 324.65  1200.00 3524.65
46.00   3524.65 521.09  1200.00 5245.75
47.00   5245.75 742.58  1200.00 7188.33
48.00   7188.33 992.31  1200.00 9380.63
49.00   9380.63 1273.87 1200.00 11854.50
50.00   11854.50    1591.33 1300.00 14745.83
51.00   14745.83    1949.42 1200.00 17895.25
52.00   17895.25    2352.98 1200.00 21448.23
53.00   21448.23    2807.99 1200.00 25456.22
54.00   25456.22    3321.00 1200.00 29977.22
55.00   29977.22    3899.41 1200.00 35076.63
56.00   35076.63    4551.56 1300.00 40928.19
57.00   40928.19    5287.01 1200.00 47415.20
58.00   47415.20    6116.02 1200.00 54731.22
59.00   54731.22    7050.72 1200.00 62981.95
60.00   62981.95    8104.58 1200.00 72286.52
61.00   72286.52    9292.77 1200.00 82779.30
62.00   82779.30    10632.44    1300.00 94711.74
63.00   94711.74    12143.04    1200.00 108054.78
64.00   108054.78   13846.03    1200.00 123100.81
65.00   123100.81   15766.11    1200.00 140066.92

What browser and what environment are you using? Is Javascript enabled? Do you get any errors in the console? Have you looked at the generated HTML source?

broj1 356 Humble servant Featured Poster

Sory I ment to put the die statement after line 60, that is before line 63, so the insert query gets displayed. This way you test the insert query is constructed correctly.

It is actually hard o test your case since there are some include statements. But if nothing else helps I will do this. In that case post complete script and at least the form_functions.inc.php script

broj1 356 Humble servant Featured Poster

Test the insert statement. Put this simple debug code just before line 60:

die($q);

This will echo the insert query on screen and stop the script. Now inspect the query whether it is OK and copy and test it in phpmyadmin (or whatever you use).

Also, you check if user exists:

$q = "SELECT email, username FROM users WHERE email='$e' OR username='$u'";

and the if it does not exist if ($rows === 0), you do an insert, which is OK. But your oter condition if($rows === 2) is strange since if user is registered, you should find one row only, shouldn't you?

broj1 356 Humble servant Featured Poster

As I remember immediately after installation you should be able to access http://localhost and get the default XAMPP page (or WAMP if you use it), but not https://localhost. Regarding to info.php I don't think it exists by default (but I might be wrong). You have to create it and put phpinfo() function in it, as far as I know.

I also searched for some info on ERR_CONNECTION_RESET. What I found was a bunch of different articles most of them relating to some network configuration issues, like this one: https://www.youtube.com/watch?v=9orMZyky-UI. I do not know how this might help you.

broj1 356 Humble servant Featured Poster

Does your server certificate CN (common name) and the ServerName directive in the virtual host configuration match? But I don't think this would prevent you to at least load the homepage. Can you also try with http instead of https?

Also, do you have Skype running at ht e same time? It is known that Skype takes over port 80 and I believe port 443 also. In that case you change ports either in Skype (recommended, if you ask me) or in Apache virtual host config.

broj1 356 Humble servant Featured Poster

The log does not show any errors only few notices. How do you access your local server (waht is the local URL)? Do you have entries in the hosts file for your virtual hosts?

broj1 356 Humble servant Featured Poster

Have you checked Apache log files? If you use xampp they should be in C:\xampp\apache\logs.

broj1 356 Humble servant Featured Poster

Now, it is hard to tell which double quote is causing the error. I prefer to write queries in a bit cleaner form, using single quotes for mysql string values and double quotes for PHP string. This way you can omit all the concatenations and use variables within double quotes. Like this:

$query = "INSERT INTO booking SET 
    Firstname = '$Firstname', 
    address1 = '$address1', 
    days = '$days', 
    months = '$months', 
    bookingtime = '$bookingtime', 
    address2 = '$address2', 
    lastname = '$lastname', 
    cdays = '$cdays', 
    cmonths = '$cmonths', 
    duration = '$duration', 
    datefrom = '$datefrom', 
    dteCallTimeTo = '$to', 
    meettype = '$meettype', 
    county = '$county', 
    cnumber = '$cnumber', 
    fee = '$fee', 
    pcode = '$pcode', 
    comments = '$comments', 
    user_id = $userid";

Now debugging is much easier. You can also display the query and test it. Put this temporary debug code on line 2 above (just before the insert statement):

die($query);

This will display the query and stop the script. You can inspect the displayed query and/or paste it into phpmyadmin to test it. You can also post it here.

broj1 356 Humble servant Featured Poster

You use to as the field name but to is also a mysql reserved word. So if you realy want to use it for a field name, enclose it in backticks like this:

..., `to` = "' .$to. ...

Better practice is to completely avoid using keywords for field names. And keep this link handy:

https://dev.mysql.com/doc/refman/5.1/en/keywords.html

And drop the ** deprecated mysql** extension. It is ages old, unsuported and on it's way to become history soon. Use PDO or at least mysqli and youur future as a web developer will be brighter.

broj1 356 Humble servant Featured Poster

Just noticed. The above example will work only if you have OR operators. To take into account other operators the explode will not work. A function can be prepared for that.

broj1 356 Humble servant Featured Poster

I hope this is what you want (see comments in the code):

// test data
$mainArray = array(
    '823584X80X998.NAOK' => array('question_properties' => array('qid' => 998,  'name' => 'F8')),
    '823584X80X1001.NAOK' => array('question_properties' => array('qid' => 1001, 'name' => 'F10'))
);
// $string = '((823584X80X998.NAOK == "1"))';
$string = '((823584X80X1001.NAOK == "1" or 823584X80X1001.NAOK == "2" or 823584X80X1001.NAOK == "3"))';

// get rid of the (( and ))
$string = str_replace(array('(', ')'), '', $string);
// explode if there are any ORs
$tempArray1 = explode(' or ', $string);
// save values (1, 2, 3)
$savedValues = array();
foreach($tempArray1 as $val1) {
    $tempArray2 = explode('==', $val1);
    // this will be the key for searching in the main array
    $searchKey = trim($tempArray2[0]);
    // ad a value to the saved values array
    $savedValues[] = $tempArray2[1];
}
// to check if OR has to be echoed
$savedValuesCount = count($savedValues);
if(array_key_exists($searchKey, $mainArray)) {
    echo "((";
    foreach($savedValues as $key2 => $savedVal) {
        // echo replacement
        echo $mainArray[$searchKey]['question_properties']['name'] . '==' . $savedVal . '';
        // echo OR if needed
        if($key2 < $savedValuesCount -1) {
            echo ' or ';
        }
    }
    echo '))';
} else {
    // in case key does not exist
    echo "Search key $searchKey does not exist in the main array";
}
broj1 356 Humble servant Featured Poster

Just to clarify - the string can actualy be one of the values below:

$stringExample = '((823584X80X998.NAOK == "1"))';
$stringExample = '((823584X80X1001.NAOK == "1" or 823584X80X1001.NAOK == "2" or 823584X80X1001.NAOK == "3"))';

If that is true, you have to:
- get rid of all the parentheses
- explode by OR operators
- explode each by == operators
- save values on the right of the == operators
- figure out the value of the key
- find that key in the array and get the name value
- assemble and echo the thing

Please confirm if I understood the question correctly.

broj1 356 Humble servant Featured Poster

You can get some user agent strings here.

broj1 356 Humble servant Featured Poster

Noone noticed that little glitch :-). The checkbox value attribute is what gets carried over in request. The text that you want displayed next to the checkbox is just a HTML (not the value attribute).

broj1 356 Humble servant Featured Poster

Enclose each row (and ID and a delete button) within form tags and add a hidden input that holds the value. You will have as many forms as there rows. When you delete (submit), the value in the hidden input field will get over to the next script. And you do not need a name attribute in the list item element.

<h1>YOUR COURSES</h1>
<ol>
<?php
$con=mysqli_connect("localhost","FYP","123","FYP");
$sql= mysqli_query($con, "SELECT C_Code FROM F_COURSES WHERE F_ID=".$_SESSION['userid']);
while($row = mysqli_fetch_array($sql)){

    // I added a little bit of a styling to the form to display correctly
    echo "<li><form method='post' action='delete.php' style='display:inline;'>" . $row['C_Code'] . "<input type='submit' value='Delete'>";

    // this line adds a hidden input
    echo "<input name='course' type='hidden' value='" . $row['C_Code'] . "'></form></li>";
}
?>
</ol>

I hope having a form inside a list item element isn't bad coding. But I've seen that arround.

SoMa_2 commented: Thank you it work +0
broj1 356 Humble servant Featured Poster

OK. Please mark s solved.

broj1 356 Humble servant Featured Poster

->setCellValue('B'.$rowNumber,'=HYPERLINK($row->prodoto)')

I think you should use double quotes so $row->prodoto gets parsed (and also enclose the variable in curly braces to be on the safe side):

->setCellValue('B'.$rowNumber,"=HYPERLINK({$row->prodoto})")
broj1 356 Humble servant Featured Poster

By looking at your query you want to display all the questions from the questions table. Am I correct? In this case you have to rearrange code a little bit. First start the form, then start the table, then loop through rows using a while loop and in each iterration display a row and at the end close the table and the form. Something like (see comments in the code):

// first start the form
echo '<form method="post" action="#">';

// then start the table
echo "<table>";

// db connection
...

// query the database
$sql = mysqli_query($con, "SELECT `question`, `question_type` FROM  `questions`");

// loop through result - each db row is one table row
// note the curly bracket for a loop block
 while ($row = mysqli_fetch_assoc($sql)) {

    if ($row['question_type'] == 1) {
        $type = "radio";   
    } else {
        $type ="checkbox";
    }

    // start table row and cell
    echo '<tr><td>';

    // input element
    echo '<input type="'. $type .'" value= "' . $row['question'] . '">';

    // end table cell and row
    echo '</td></tr>';

} // <-- note the end of the while loop

// end the table
echo '</table>';

// end the form
echo '</form>';

// close connection
mysqli_close($con);
?> 

In your code you were missing the curly brackets alltogether to enclose the block of code to loop through.

BTW: if the type is either a checkbox or radio, shouldn't the question be displayed in a label element not as the value?

Also if you use radio, it is usually …

broj1 356 Humble servant Featured Poster

Uncaught exception 'PHPExcel_Calculation_Exception' with message 'Worksheet!B12 -&gt; Formula Error: Unexpected operator '&gt;'' in /web/ì/admin/Classes/PHPExcel/Cell.php:300

It seems that PHPExcel tries to calculate the value in the cell and it can't since there is an invalid operator in there. Can you post what the value of $row->prodoto is when it throws the error.

broj1 356 Humble servant Featured Poster

Did my answer from your other thread not help you? I have provided a tested working example there.

diafol commented: He complained "Nothing helped him" - all yours broj :) +15
broj1 356 Humble servant Featured Poster

The if statement has an error. Instead of assignment operator = you should use comparison operator ==, like:

if ($row['question_type'] == 1)

In the form html code you are missing some quotes (altough this should not be critical):

echo '<td>'. '<input type="'.$type.'" value= "'.$row['question'] . '" </td>';
broj1 356 Humble servant Featured Poster

As I said I would use the approach I posted in my previous post. There are many things in your code that I think are redundant, like

/*** check if the users is already logged in ***/
if(isset( $_SESSION['user_id'] ))
{
    $message = 'Users is already logged in';
}

If the user is already logged in just redirect them to their page.

/*** check the username is the correct length ***/
elseif (strlen( $_POST['username']) > 20 || strlen($_POST['username']) < 4)
{
    $message = 'incorrect length';
}
/*** check the password is the correct length ***/
elseif (strlen( $_POST['password']) > 20 || strlen($_POST['password']) < 4)
{
    $message = 'incorrect length';
}
/*** check the username has only alpha numeric characters ***/
elseif (ctype_alnum($_POST['username']) != true)
{
/*** if there is no match ***/
    $message = "Username must be alpha numeric";
}
/*** check the password has only alpha numeric characters ***/
elseif (ctype_alnum($_POST['password']) != true)
{
/*** if there is no match ***/
    $message = "Password must be alpha numeric";
}

Why do you have to do all these checks above? Just check if username and password are correct.

For redirection based on groupe you can use this short code:

$redirections = array(
    1 => 'acceuil.html',
    2 => 'acceuil2.html',
    3 => 'acceuil3.html'
)

...
header("Location: {$redirections[$groupe]}");

You can scale your application by changing or adding groups and the script will still work without a lot of maintenance; you will only have to update the $redirections array.

 /*** …
broj1 356 Humble servant Featured Poster

There are still some errors that somehow sneaked into my code :-). This is what happens when there is no time to test. These are the errors:

// wrong
$conn->setAttribute(PDO::ATTlR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// correct
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// wrong
$conn->exec($sql);
// correct
$stmt->execute();

So this part of code should be (tested, and it works):

$servername = "localhost";
$dbname = "test";
$dbusername = "test";
$dbpassword = "";

try {
    // You initialize the connection here using OOP style
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
    // here you say that you will use exception mode for
    // error handling this is basically the try/catch block
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    // the SQL statement uses placeholders for values
    // that will be replaced with values of variabes;
    // the colon (:) is denoting the placeholders
    $sql = "INSERT INTO Posts (Title, Author, Content)
            VALUES (:title, :author, :content)";
    // prepare a statement (that is why it is named $stmt)
    $stmt = $conn->prepare($sql);
    // bind real values to placeholders
    // e.g. placeholder named :title receives a value of $title etc
    $stmt->bindParam(':title', $title, PDO::PARAM_STR);
    $stmt->bindParam(':author', $author, PDO::PARAM_STR);
    $stmt->bindParam(':content', $content, PDO::PARAM_STR);
    // now execute the prepared statement
    $stmt->execute();
    // if exception happens (basically if error occurs) handle it
} catch(PDOException $e) {
    echo $sql . "<br>" . $e->getMessage();
}

Sory for the errors in my posts. Speed does not always help.

broj1 356 Humble servant Featured Poster

Cool. Please mark the tread solved. Happy coding :-)

broj1 356 Humble servant Featured Poster

OK, seems this error is since empty can not be used this way. You can use the if block that I posted in my previous post if you wish (recommended).

And yes, you should add the prepare line before binding. Hopefuly all will work OK. Anyway, if you get errors post them here.

broj1 356 Humble servant Featured Poster

Looking at your code I have got these questions:

  1. What is the purpose of verification2.php script?
  2. What is the user identifier you want to use for user redirection?

I would do only one script for adding user and one script for login. The following is an example flow for login:

  1. check if form was submited
  2. if yes, check for the user data in the database
  3. if match is found redirect to a user area (a page for authenticated users)
  4. if match is not found display an error message and the form with username already filled-in

The code would be something like:

<?php
// begin session on the very beginning of the script
session_start();

// initialize the username variable for filling in the form after incorrect login
$username = '';

// initialize the array for storing error messages
$messages = array();

// check if form was submitted and if yes, do all the stuff
if(isset($_POST['submit'])) {

    $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
    // no need to filter password since you will hash it
    // actually by filtering it you might unvalidate it

    // hash the password (hashing is not the same as encrypting)
    $password = sha1( $_POST['password'] );
    /*** connect to database ***/
    /*** mysql hostname ***/
    $mysql_hostname = 'localhost';
    /*** mysql username ***/
    $mysql_username = 'root';
    /*** mysql password ***/
    $mysql_password = '';
    /*** database name ***/
    $mysql_dbname = 'ges_tache';
    try
    {
        $dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
        /*** set the error mode to excptions ***/
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        /*** prepare …
broj1 356 Humble servant Featured Poster

First I have to admit there are errors in my code. e.g. I forgot to copy the prepare statement which is most important here. So the right code is (see explanations in comments):

$servername = "localhost";
$dbname = "mydbname";
$dbusername = "mydbusername";
$dbpassword = "mydbpassword";

try {
    // You initialize the connection here using OOP style
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);

    // here you say that you will use exception mode for 
    // error handling this is basically the try/catch block
    $conn->setAttribute(PDO::ATTlR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // the SQL statement uses placeholders for values
    // that will be replaced with values of variabes;
    // the colon (:) is denoting the placeholders
    $sql = "INSERT INTO Posts (Title, Author, Content)
        VALUES (:title, :author, :content)";

    // prepare a statement (that is why it is named $stmt)
    $stmt = $conn->prepare($sql);

    // bind real values to placeholders
    // e.g. placeholder named :title receives a value of $title etc
    $stmt->bindParam(':title', $title);
    $stmt->bindParam(':author', $author);
    $stmt->bindParam(':content', $content);

    // now execute the prepared statement
    $conn->exec($sql);

// if exception happens (basically if error occurs) handle it
} catch(PDOException $e) {
    echo $sql . "<br>" . $e->getMessage();
}

// unset the connection (to free resources)
$conn = null;

You also have a very nice and complete tutorial here.

It is strange that you get an error trimming the user input. It is quite important to do it since users sometimes add spaces on beginning or end without knowing and noticing it. Maybe you should change that line of code …

broj1 356 Humble servant Featured Poster

You have an error in the displayRet() function in the line that displays temperature (missing the > in the br tag):

"<br /Temperature: " + inc["temperature"] +

It should be

"<br />Temperature: " + inc["temperature"] +
broj1 356 Humble servant Featured Poster

This is my version of ajax function. See comments in the code.

$("document").ready(function () {
    $(function () {
        //setup ajax error handling
        $.ajaxSetup({
            error: function (x, status, error) {
                if (x.status == 403) {
                    alert("Sorry, your session has expired. Please login again to continue");
                    window.location.href = "/Account/Login";
                }
                else {
                    alert("An error occurred: " + status + "nError: " + error);
                }
            }
        });
    });


    $("#Jform").submit(function (e) {
        // so the form does not get submitted
        e.preventDefault();
        data = $('#Jform').serialize();
        $.ajax({
            type: "POST",
            // I think this is correct datatype
            dataType: "json",
            url: "processJson.php",
            data: data,
            success: function (msg) {
                // I don't thimk you need to parse, since msg is already a JSON
                displayRet(msg);
            },
            error: function (msg) {
                console.log(msg);
                $("#the-return").html("ERROR: " + msg);
            }
        });
    });
});

Also, you are appending to the jsonStorage.txt so it keeps growing and getting big. Is that what you want?

broj1 356 Humble servant Featured Poster

To execute the code only after form submission the whole thing has to be wrapped in an if block:

<?php
if(isset($_POST['submit'])) {

    $title = $_POST['title'];
    $author = $_POST['author'];
    $content = $_POST['content'];

    if(empty(trim($_POST["title"])) || empty(trim($_POST["author"])) || empty(trim($_POST["content"]))) {
            echo "You forgot to enter some required data";
    } else {

        $servername = "localhost";
        $dbname = "mydbname";
        $dbusername = "mydbusername";
        $dbpassword = "mydbpassword";

        try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO Posts (Title, Author, Content)
            VALUES (:title, :author, :content)";
            $stmt->bindParam(':Title', $title);
            $stmt->bindParam(':Author', $author);
            $stmt->bindParam(':Content', $content);
            $conn->exec($sql);
        } catch(PDOException $e) {
            echo $sql . "<br>" . $e->getMessage();
        }
        $conn = null;
    }
}
?>

I rearranged your code to include changes from my previous posts.

broj1 356 Humble servant Featured Poster

And for security reasons use prepared statements.

Prepared statements are a feature of a database (like mysql). Variables that are passed to a query get prepared first so a possibility of an injection of bad code is minimized. This is a preferrable way of inserting user supplied data into the database. Your code will look something like:

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO Posts (Title, Author, Content)
    VALUES (:title, :author, :content)";
    $stmt->bindParam(':Title', $title);
    $stmt->bindParam(':Author', $author);
    $stmt->bindParam(':Content', $content);
    $conn->exec($sql);
} catch(PDOException $e) {
    echo $sql . "<br>" . $e->getMessage();
}

As you can see in the query there are placeholders for variables and actual values are them bound to those placeholders. Also see this article.

broj1 356 Humble servant Featured Poster

Depending on what you want you might use the third parameter of the load method - a function that fires on complete.

Edit: I have just noticed that there is a displayRet(inc) function which is used for displaying data. It is in this function that you should check if the data represents an error or valid data and display information accordingly.

broj1 356 Humble servant Featured Poster

This is the PHP part. It is slightly rearanged so the connection and execution gets done only if there are all fields:

<?php
    $title = $_POST['title'];
    $author = $_POST['author'];
    $content = $_POST['content'];

    if(empty($_POST["title"]) || empty($_POST["author"]) || empty($_POST["content"])) {
        echo "You forgot to enter some required data";

    } else {

        // this is just for debugging
        // die($sql);

        $servername = "localhost";
        $dbname = "mydbname";
        $dbusername = "mydbusername";
        $dbpassword = "mydbpassword";

        try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO Posts (Title, Author, Content)
                VALUES ('$title', '$author', '$content')";

            $conn->exec($sql);
        } catch(PDOException $e) {
            echo $sql . "<br>" . $e->getMessage();
        }

        $conn = null;
    }
?>

And for security reasons use prepared statements.

broj1 356 Humble servant Featured Poster

Can you post the rest of the code. The error is comming from some lines after your snippet.

broj1 356 Humble servant Featured Poster

First: do not use GET for the form method, use POST. When using GET, passwords will be visible in the URL bar of the browser and will get written in the browser cache and history. This way anyone with basically no web dev skills will be able to see usernames and passwords.

Second: do not use mysql_* functions since they are deprecated, offer no advanced features that are important for security, and might be ditched at any time. You can use mysqli_* functions which are quite similar and safer, but preferably you should switch to PDO. The PDO has many advantages: it supports database features to greatest extent (i.e. prepared statements), it enables you to switch databases quite easily (i.e. from mysql/mariadb to postreSQL or Oracle etc) and uses nicely designed OOP approach.

Now, on this link you will find a nice login example, using PDO for database access, prepared statements for secure insertion and sha1 for password hashing, all nicely comented.

Mind you, if you google for php login example you will still find loads of examples using deprecated mysql_* functions. Do yourself a favor and avoid them or translate them at least to mysqli_* or better to PDO.

For enhancing security also read this article.

I hope this is not too much information in one short time for you. Nevertheless, it is worth investing some time into studying and clarifying these concepts as it will help you many …

cereal commented: +1 +13
broj1 356 Humble servant Featured Poster

OK, then let's do some simple debugging. Insert this line of code just after line 4 in your first snippet:

die($sql);

This will stop the script and display the query that is giving us hard time. Please post the displayed query here.

broj1 356 Humble servant Featured Poster

Yes, this is just an example when email would be required. What are the errors you want to check for, is something you have to decide.

Edit: I just realized that my example code contains errors, sory. It should be:

if (!isset($tempArray["email"]) || empty($tempArray["email"])) {
    $errors[] = 'Email field is empty';
}

Basically whenever there is an error, you add a string to the $errors array. Then you check if there are any error strings in the array, something went wrong and you display all the errors that occured. You can decide that you want to handle errors differently.

broj1 356 Humble servant Featured Poster

Depending on how your overall approach is to processing form data, but in general it is as easy as:

if(empty(trim($_POST["Title"])) || empty(trim($_POST["Author"])) || empty(trim($_POST["Content"]))) {
    echo "You forgot to enter some required data";
    // go back to the form
} else {
    // 
    // I HOPE YOU DO SOME FILTERING / SANITIZING HERE 
    // OR USE PREP. STATEMENTS
    // 
    $sql = "INSERT INTO Posts (Title, Author, Content)
    VALUES ('$title', '$author', '$content')";
}

Note that I also used the trim function to get rid of possible spaces which are also of no use in your database fields.

broj1 356 Humble servant Featured Poster

You have to define all the criteria for errors. You have already defined one criteria being file open error. I do not know what other errors you would like to catch. Maybe some missing data in the JSON or invalid data etc. See comments in my example:

// since there can be many types of errors save them in an array 
$errors = array();

$name = filter_input(INPUT_POST, "name", FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$gender = filter_input(INPUT_POST, "gender", FILTER_SANITIZE_STRING);
$temperature = filter_input(INPUT_POST, "temperature", FILTER_SANITIZE_STRING);
$terms = filter_input(INPUT_POST, "terms", FILTER_SANITIZE_STRING);

$tempArray = array("name" => $name, "email" => $email, "gender" => $gender, "temperature" => $temperature, "terms" => $terms);

// check if required fields exist (e.g. email)
if(isset($tempArray["email"]) && !empty($tempArray["email"])) {
    $errors[] = 'Email field is empty';
}

// check if encoding worked
$jsonVal = json_encode($tempArray);
if($jsonVal === false) {
    $errors[] = 'Encoding to JSON failed';
}

// Open file and test operation
$fileHandle = fopen('storage/jsonStorage.txt', "a");
if (!$fileHandle) {
    // check if file could be opened
    $errors[] = 'Could not open the file for writing';
} else {
    fwrite($fileHandle, $jsonVal);
    fwrite($fileHandle, "<br />\n");
}

// no errors
if (empty($errors)) {
    return $jsonVal;
// some errors
} else {
    $msg = '';
    foreach($errors as $e) {
        $msg .= "$e<br>";
    }
    return $msg;
}
broj1 356 Humble servant Featured Poster

The jquery load function does exactly that. It is the following function in the local.js:

$('#jsonReadButton').click(function () {
    alert('Click');
    $('#jsonReadArea').load('storage/jsonStorage.txt');
});

I added the alert function to check if the call gets through OK. If you get alert, then the JSON should be loaded into the div. If not, something is wrong with permissions, path or something similar.

broj1 356 Humble servant Featured Poster

I copied the files form the attached zip and everything works fine. Json gets displayed in the jsonReadArea div. Have you checked all permissions are OK?

broj1 356 Humble servant Featured Poster

The $result does not contain the rows from the database yet. It is just a special PHP type variable that enables fetching of rows. So you have to fetch rows, usually in a loop:

The following is an example using mysqli object oriented way:

$username = "USERNAME";
$password = "PASSWORD";
$hostname = "127.0.0.1:3306";
$database = "Strong_Links";

//connection to the database
$dbhandle = new mysqli($hostname, $username, $password, $database) or die "Unable to connect to MySQL"];
echo "";

// query the database
if(!$result = $dbhandle->query("SELECT content FROM web WHERE id = 'news1'")){
    die("query failed");
}

// loop over the result set
while($row = $result->fetch_assoc()){
    echo '<div>' . $row['content'] . '</div>';
}

You can use mysqli also in procedural way or maybe you would prefer PDO. Let us know if you need help with that.

broj1 356 Humble servant Featured Poster

Is the code

<a class="showallphoto" href="'.$base_url.'login.php?showallphoto=' . $messageid . '" style="cursor:pointer">

echoed by a PHP script? If yes, show the whole line. Also test if the link gets constructed OK (by inspecting the generated code, by hovering with the mouse over it and checking the status line etc).

broj1 356 Humble servant Featured Poster

This code:

public function get_validator(){
    return $this->response_code;
    return $this->response_msg;
}

should be probably broken into two methods:

 public function get_response_code() {
    return $this->response_code;
}

public function get_response_msg() {
    return $this->response_msg;
}

I have been using OOP approach for several years now, and must say that it helps a lot. I can easily reuse classes I have written in past, it is easy to modify existing functionalities, it is also easy to organize team work and the project code is a piece of cake to maintain. I have learnt a lot by studying some open source examples and on my own mistakes (especially designing functionalities covered by each class). Some good code examples can be found on PHPclasses and I have also looked at some on the PEAR site.

broj1 356 Humble servant Featured Poster

Sory, but I do not understand the problem. Could you describe it form start. What you have and what you want to achieve. And post relevant code as well as some relevant sample data.

broj1 356 Humble servant Featured Poster

If the path is in the $aInfo['photo'] row then the code would be:

echo '<img src="' . $aInfo['photo'] ">'

But you have to make sure the path is correct. Maybe you have to add something to make the path absolute (e.g. http://yoursite.com/images) or be sure that relative path is correct.

Maybe you could post sample database rows.

broj1 356 Humble servant Featured Poster

Joshuajames pointed out another error in your query which is you cant use array elements in the string the way you did. The correct way of using compound variables in a double quoted string would be using curly braces:

$insertedData = mysql_query($serverConnection, "INSERT INTO customertable(CustomerID, FirstName, SurName, Address, PhoneNum, Email, PurchaseProduct)
VALUES('{$_POST['Customer_ID']}', '{$_POST['First_Post']}', '{$_POST['Sur_Name']}', '{$_POST['Cus_Address']}', '{$_POST'[Phone_Num']}', '{$_POST['Cus_Email']}' '{$_POST['Product_Purchase']}')");

But Joshuajames's solution is cleaner. I would add to it two things:

  • clean/sanitize the variables comming from a user
  • do not use deprecated mysql_* functions, switch to newer and safer PDO or at least mysqli_*.

Example of sanitizing (in practice it depends on value):

$customer_id = mysql_real_escape_string($_POST[Customer_ID]);
$first_post =  mysql_real_escape_string($_POST[First_Post]);
$sur_name =  mysql_real_escape_string($_POST[Sur_Name]);
$cus_address =  mysql_real_escape_string($_POST[Cus_Address]);
$Phone_Num = mysql_real_escape_string($_POST[Phone_Num]);
$cus_email = mysql_real_escape_string($_POST[Cus_Email]); 
$Product_Purchase = mysql_real_escape_string($_POST[Product_Purchase]);

EDIT: take also a look at Szabi's post above since this is the way to go.

broj1 356 Humble servant Featured Poster

You have to add echo statement to every case instance in the function, something like:

function updateMemberAjx() {
    $sVal = $GLOBALS['MySQL']->escape($_POST['value']);

    $iId = (int)$_POST['id'];
    if ($iId && $sVal !== FALSE) {
        switch ($_POST['columnName']) {
            case 'first_name':
                $GLOBALS['MySQL']->res("UPDATE `pd_profiles` SET `first_name`='{$sVal}' WHERE `id`='{$iId}'");
                $temp = "UPDATE `pd_profiles` SET `first_name`='{$sVal}' WHERE `id`='{$iId}'";
                break;
            case 'last_name':
                $GLOBALS['MySQL']->res("UPDATE `pd_profiles` SET `last_name`='{$sVal}' WHERE `id`='{$iId}'");
                $temp = "UPDATE `pd_profiles` SET `last_name`='{$sVal}' WHERE `id`='{$iId}'";
                break;
            case 'email':
                $GLOBALS['MySQL']->res("UPDATE `pd_profiles` SET `email`='{$sVal}' WHERE `id`='{$iId}'");
                $temp = "UPDATE `pd_profiles` SET `email`='{$sVal}' WHERE `id`='{$iId}'";
                break;
            case 'status':
                $GLOBALS['MySQL']->res("UPDATE `pd_profiles` SET `status`='{$sVal}' WHERE `id`='{$iId}'");
                $temp = "UPDATE `pd_profiles` SET `status`='{$sVal}' WHERE `id`='{$iId}'";
                break;
            case 'role':
                $GLOBALS['MySQL']->res("UPDATE `pd_profiles` SET `role`='{$sVal}' WHERE `id`='{$iId}'");
                $temp = "UPDATE `pd_profiles` SET `role`='{$sVal}' WHERE `id`='{$iId}'";
                break;
            case 'date_reg':
                $GLOBALS['MySQL']->res("UPDATE `pd_profiles` SET `date_reg`='{$sVal}' WHERE `id`='{$iId}'");
                $temp = "UPDATE `pd_profiles` SET `date_reg`='{$sVal}' WHERE `id`='{$iId}'";
                break;
        }
        // echo 'Successfully saved';
        echo 'DEBUG: ' . $temp;
    }
    exit;
}

Please note that this is very simple and a bit clumsy way of debugging. Using right developer tools is the way to go.