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 exec the post. See also example here.

curl_exec($ch);
curl_close($ch);

Also check for errors using curl_error.

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

Sory, did not understand the question. Maybe this article can help?

broj1 356 Humble servant Featured Poster

Must be an issue with quotes. Try something like this:

curl -i -H "Accept: application/json" -d '{"username": "divmesselibrary", "password": "677Sure1@"}'

or:

curl -i -H "Accept: application/json" -d "{\"username\": \"divmesselibrary\", \"password\": \"677Sure1@\"}"
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

Post the code you have so far and describe where exactly the problem is.

Also, please read this.

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

Sory to come back so late, was quite busy. The approach actually works for me. This is a script, adapted from the example 3 of the PHPExcel examples:

<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');

define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

/** Include PHPExcel */
// Use correct path here
$excelClass = '../../PHPExcel/Classes/PHPExcel.php';
require_once $excelClass;

$objPHPExcel = new PHPExcel();

// Set document properties
echo date('H:i:s') , " Set document properties" , EOL;
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                             ->setLastModifiedBy("Maarten Balliauw")
                             ->setTitle("Office 2007 XLSX Test Document")
                             ->setSubject("Office 2007 XLSX Test Document")
                             ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                             ->setKeywords("office 2007 openxml php")
                             ->setCategory("Test result file");

// set textual link and hyperlink by a formula
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'TEXT')
                              ->setCellValue('A2', 'LINK')
                              ->setCellValue('B1', "http://www.daniweb.com")
                              ->setCellValue('B2', '=HYPERLINK("http://www.daniweb.com")');

// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Formulas');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

// Save Excel 2007 file
$callStartTime = microtime(true);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

//
//  If we set Pre Calculated Formulas to true then PHPExcel will calculate all formulae in the
//    workbook before saving. This adds time and memory overhead, and can cause some problems with formulae
//    using functions or features (such as array formulae) that aren't yet supported by the calculation engine
//  If the value is false (the default) for the Excel2007 Writer, then MS Excel (or the application used to
//    open the file) will need to recalculate values itself to guarantee …
broj1 356 Humble servant Featured Poster

You might want to try the HYPERLINK() formula. Haven't tested this, just looked up some info on the net. See also this link.

broj1 356 Humble servant Featured Poster

The error message is saying that the value of $row['callback_function'] is an array and can not be cast to string.
In order ot find out what the value is when the error occurs you have to do some simple debugging (if you are not using a proper debugger). Put this code immediatelly after line 16 in the above code:

if(is_array($row['callback_function'])) die(print_r($row['callback_function'], 1));

This will stop the execution once it gets to the point where casting to string is not possible (the value to cast is an array) and display the value. Post the value here.

Also read this and this.

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.

broj1 356 Humble servant Featured Poster

You have to debug ajax calls which is easier with tools like Firebug. But anyway, I think you should check the UPDATE query from the updateMemberAjx() function. You can try to display the query instead of the success message by assigning the query to a variable in each case statement like:

case 'first_name':
    $GLOBALS['MySQL']->res("UPDATE `pd_profiles` SET `first_name`='{$sVal}' WHERE `id`='{$iId}'");
    // assign the query to a temp variable
    $temp = "UPDATE `pd_profiles` SET `first_name`='{$sVal}' WHERE `id`='{$iId}'"

and changing line 098 from:

echo 'Successfully saved';

to:

echo $temp;

This way the query will be diplayed upon an update. You can copy it and test in phpmyadmin whether it contains any errors.

broj1 356 Humble servant Featured Poster

The error is in the paramaters of the mysql_query function. The first parameter should be the query (string type), and the second (optional) parameter is the link (of type resource type). You have wrong sequence ot these parameters.

And the mantra: ditch the deprecated mysql_* functions and replace them with the new PDO or at least mysqli_* functions.

broj1 356 Humble servant Featured Poster

Do you already have an upload form? If not, you can find nice tutorial here. Make sure that everything is happening within the restricted area (i.e. a user has to be logged in to upload photos), to keep things secure.

An elegant solution would be to use AJAX, so users can upload photos without leaving a page or to put checkboxes to each photo in order to enable users to load more photos at once.

Hopefuly I understood your question right. If not please clarify it.

broj1 356 Humble servant Featured Poster

And what is the actual problem? Describe where you got stuck and post possible error messages.

broj1 356 Humble servant Featured Poster

The problem might be occuring at the time of saving pictures in the database (there are two photos in the folder but only one in the database). Post the code for saving the data into the database (I have a feeling that the insert query should be within the for loop).

broj1 356 Humble servant Featured Poster

Here is what I do: echo implode(', ', (array)$topuid);, with this code, the $topuid will be cast into an array for implode.

Casting is a good idea. You also have to cater for the query to work when the $topuid is empty.

$inCondition = $topuid != "" ?  " and user_id NOT IN ($idtopuid)" : "";
$userquery = mysql_query("select * from user where user_id != '{$_SESSION['userid']}'" . $inCondition . " order by rand() limit 0,5");

Note that I embeded variables directly into the doublequoted string.

broj1 356 Humble servant Featured Poster

It seems that the $topuid variable is not an array (the implde function expects an array). Can you check it out? You can put this code just before line 3 in the above code:

die(print_r($topuid, 1));

This will display the value of the variable and stop the script. Please post the value here.

broj1 356 Humble servant Featured Poster

You are welcome. Please mark as solved if no more questions. Happy coding.

broj1 356 Humble servant Featured Poster

You can store number of images per row in an array (this is untested, just a concept):

// between lines 17 and 18 - initialize variables
$rowNo = 1;
$imagePerRow = array();

// between lines 44 and 45 - assign current value for that row
imagePerRow[$rowNo] = $x;

// on line 49 - increase row counter
$rowNo++;

To make it more efficient, store only a number for the last row, since all other rows have 4 images. The last row will have 4 or less images.

broj1 356 Humble servant Featured Poster

Your array has two main elements:

  1. settings - an array of common settings
  2. books - an array of book data (each element here contains the same book data)

Therefore you have to use an if condition and check for the main key to access other values. I tested it with this code:

$array = (parseInfo($barcode));

// this is to format the output nicely
echo "<pre>";

// print_r($array);

foreach ($array as $key => $values) {

    /*
    echo  'AUTHOR FL: ' . $author_fl  = $values['show']['showCovers'];
    echo  'BOOK_ID: ' . $book_id  = $values['books'];
    echo  'TITLE: ' . $title  = $values['settings']['title'];
    $covers = $values['settings']['covers']; // Author (last, first)
    $author_lf = $values['settings']['author_lf']; // Author (last, first)
    $author_fl = $values['settings']['author_fl'];  // Author (first, last)
    echo  'AUTHOR_CODE: ' . $author_code  = $values['amazonchoice']['author_code'];
    $ISBN  = $values['amazonchoice']['ISBN'];
    $publicationdate  = $values['amazonchoice']['publicationdate'];
    $entry_stamp = $values['amazonchoice']['entry_stamp'];
    $entry_date = $values['amazonchoice']['entry_date'];
    $copies  = $values['amazonchoice']['copies'];
    $notes = $values['amazonchoice']['notes'];
    $language_main  = $values['amazonchoice']['language_main'];
    */

    // MY TEST

    echo "--------------<br> $key <br>--------------<br>";
    echo print_r($values, 1);

    if($key == 'settings') {
        echo '*** [show][showCovers] ***<br>' . print_r($values['show']['showCovers'], 1);
        echo '*** [settings][title] ***<br>' . print_r($values['title'], 1);
    } else {
        echo '*** [books] ***<br>' . print_r($values['books'], 1);
    }
}

echo "</pre>";

And as I said, some values are emty so nothing gets displayed.

matrixdevuk commented: You could simply do `echo "<pre>" . print_r($array, true) . "</pre>";` -1
broj1 356 Humble servant Featured Poster

So where did you get stuck? I managed to access any element of the above array.

broj1 356 Humble servant Featured Poster

The values you are trying to display have no values so you see nothing. To prove that add some static texts to the echo statement, like this:

foreach ($array as  $values) {

    echo  'AUTHOR FL: ' . $author_fl  = $values['show']['showCovers'];
    echo  'BOOK_ID: ' . $book_id  = $values['books'];
    echo  'TITLE: ' . $title  = $values['settings']['title'];
    $covers = $values['settings']['covers']; // Author (last, first)
    $author_lf = $values['settings']['author_lf']; // Author (last, first)
    $author_fl = $values['settings']['author_fl'];  // Author (first, last)
    echo  'AUTHOR_CODE: ' . $author_code  = $values['amazonchoice']['author_code'];
    $ISBN  = $values['amazonchoice']['ISBN'];
    $publicationdate  = $values['amazonchoice']['publicationdate'];
    $entry_stamp = $values['amazonchoice']['entry_stamp'];
    $entry_date = $values['amazonchoice']['entry_date'];
    $copies  = $values['amazonchoice']['copies'];
    $notes = $values['amazonchoice']['notes'];
    $language_main  = $values['amazonchoice']['language_main'];
}

You can always test json/arrays or other php functions online on Functions online, e.g. this is the link for json_decode.

broj1 356 Humble servant Featured Poster

Your text contains an apostrophe (') which is also used in mysql as a string delimiter. In order to store an apostrophe into the DB you have to escape it usually using a database escape function (mysql_real_escape_string in your example):

$insert = mysql_query("insert into offer(
descr
)
values(
'".mysql_real_escape_string($descrr)."'
)")
or die(mysql_error($con));

All in all using deprecated mysql_* functions is a bad idea. Switch to PDO.

broj1 356 Humble servant Featured Poster

It is not clear what the coupon class is expected to do. It seems that there is some code missing. The only method defined in it is the Voucher method. The method fires calls to some other methods and properties of the class but they are not defined anywhere. The class is also not the extension of some other class.

You should design a function or a class (if you are OK with OOP) yourself. Figure out and define what the functionality should be the code it, staring with simple functionality and adding the complexity if needed.

broj1 356 Humble servant Featured Poster

On line 14 you are calling the Voucher method which expects two parameters: the object of the Registry class (first parameter) and the voucher code (second parameter). You supplied only one parameter, which should be the second one. Hence it is of wrong type. Supply both parameters (and both of correct type) and you should be OK.

broj1 356 Humble servant Featured Poster

You are welcome. Please mark the thread as solved if no more questions. Happy coding :-)

broj1 356 Humble servant Featured Poster

Sorry, my typo. Line 22 of my code should be:

if($result->num_rows != 0) {
...

(no parentheses after the num_rows).

Also change the action of the form to the same script:

<form method="post" action="#">
broj1 356 Humble servant Featured Poster

You are mixing mysql_* and mysqli_* functions as well as object oriented and procedural style. The code below is mysqli_* OOP style, and is not tested, just to give you an idea. See the comments.

// check if form submitted and if code field is not empty
if(isset($_POST['submit']) && $_POST['code'] != '') {

    // only now connect to the DB since you know you need it
    $db=new mysqli('localhost','root','','shop');
    if(mysqli_connect_errno()){
        echo 'Could not connect to database:Plz try After Some time..';
        exit();
    }

    // clean the user input (see the correct code for the clean function below)
    $code = clean($_POST['code'], $db);

    // after cleaning (trim) the code could be empty so check for this
    if($code != "") {

        // use a WHERE clause
        $qry="SELECT code FROM code WHERE code='$code'";
        $result = $db->query($qry);

        // check if you got any rows (code was found)
        if($result->num_rows() != 0) {
            echo "sucess,discount granted";
        } else {
            // code was entered but not found in the database
            echo "fail (code is not valid)";
        }

        // Free result set
        $result->close();

    } else {
        echo "fail (no code entered)";
    }

    // close the connection
    $db->close();
}

The clean function also has to be corrected in order to use the $db object:

//Function to sanitize values received from the form. Prevents SQL injection
// you have to pass the DB object to the function to use it
function clean($str, $db) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return $db->real_escape_string($str);
}

Please note this post has …

broj1 356 Humble servant Featured Poster

Please mark the thread as solved if no more questions. And yes, do not use deprecated mysql_* functions in production. Happy coding.

broj1 356 Humble servant Featured Poster

There are errors in your code above:

Line 199 - missing ; at the end of the line:

echo $state

Line 229 - missing a statement (or at least ;)

if ($_POST['type'] == "login") ;

This is why you get nothing shown. Errors were proably logged into some error log on the server.

You can also comment out lines 176 to 182 to eliminate possible database connection errors since you do not do any database interaction in the script anyway.

matrixdevuk commented: I was just about to lose hope and complain that nobody found it. Thank you for keeping me sane. +5