Jump to content

Drongo_III

Members
  • Posts

    579
  • Joined

  • Last visited

Posts posted by Drongo_III

  1. I realise this is an outside chance but...

     

    A client has approached me to build a site with a car valuation system where the user enters their reg number and the system returns their valuation. This can be seen here - http://www.glass.co.uk/?gclid=CI6KsY-diq8CFYImtAodUWWR9w .

     

    Anyone got any idea if an api of some sort exists to facilitate this? Or any idea how they do it?

     

    Do they just buy in an auction price database?

     

    If anyone could shed any light it would be massively appreciated.

     

    Thanks,

     

    Drongo

  2. I am still improvng my skills too but I found this guy's video tutorials a really good introduction to OOP -

     

    In answer to your questions

     

    1) Depends what you want to do. To create simple templates on these CMSs you don't really need to know OOP. If however you intend to try and develop new modules you will need to know OOP - in my opinion.

     

    2) I would get a basic understanding of php then start looking at frameworks.

     

    Hope this helps slightly. Sure some of the more experienced will offer more detailed advice.

  3. Hi Guys

     

    Probably a simple answer to this.

     

    Writing a script where I have a foreach to escape data in a multi dimensionsal array - destined for the database.

     

    I want to preserve the the escaped values in the array so I've passed in the value by referece. See code below:

     

    foreach($myarray as $key=>$value){
    
    foreach($value as $k=>$v){
    
    $v =   $mysqli->real_escape_string(&$v);
    echo  $v ."<br/>";
    
    }
      
      }
    

     

     

    I've switched on error_reporting(E_STRICT), because i read it was good practice to build your scripts with this on.

     

    Anyway - when i pass by reference I get a message as follows:

     

    Deprecated: Call-time pass-by-reference has been deprecated in C:\wamp\www\wh\C.php on line 105

     

    So if pass by reference is deprecated, what's the alternative?

     

    I realise i could pass the new values to a new array. But does this mean i shouldn't pass by reference anymore?

     

    Many thanks and sorry for going round the planet to ask such a simple question.

     

    Drongo

     

     

  4. haha i have my moments...few and far between as they are...

     

    Erm stepping around the feud above. You might want to read up a bit on the convepts behind MVC. This will set you on the right path for understanding how to separate your themes from you 'business logic' .

     

    Before anyone decides to level their cannons at me this is just a suggestion :) *ducks for cover*

     

    Words of f***ing wisdom! Thank you for reinforcing my original comments! Love MVC :P

  5. Aha! Thank you Akay I understand it now :)

     

    If the SQL is a static string that has absolutely no user data effecting it at all, then SQL injection is not possible.

    Say that you are building a query to use in PDO, but you are using a variable to determine which table to select from, and that variable comes from user data. This means that if you do not escape this user data, then the SQL query can be polluted and SQL injection is still possible even though you are using PDO.

    If the SQL query is clean, then you are good to go.

  6. Please tell me to get out of this thread if it seems like i am hijacking it. Just trying to undertand PDO a better.

     

    I read your link but I'm slightly confused about the quote below (taken from the pdo php manual page):

     

     

    The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

     

    I might be being slow in interpreting this but in one part of that explanation it says PDO guards against sql injectionss and you don't need to escape the data. But then it says "(however, if other portions of the query are being built up with unescaped input, SQL injection is still possible)".

     

    So is this saying if you use a combination of mysql_query and PDO you're open to attack (which would seem reasonable)?

     

    Or is it saying that when you're building the query you still need to escape the data you use in your parameters?

     

    I don't quite understand this and would very much like to ensure i'm adopting the best practice...

     

     

    Sorry to jump in on this one. But on the subject of PDO - is it right that it automatically escapes all your data so you don't need to mysql_real_escape_string ?

     

    To expand this a little further, the basic logic is to escape all user data before inserting into a db using your RDBMS escape string function, and to use htmlentities() upon grabbing data from a db. This converts things like quotes etc into their HTML entities before being executed. IMO, the safest way to work with databases is to use PDO, which separates the SQL and the user data.

     

    no, it executes the SQL and the PHP data separately, so escaping isn't an issue.

    If you need a further explanation, read here

  7. Sorry to jump in on this one. But on the subject of PDO - is it right that it automatically escapes all your data so you don't need to mysql_real_escape_string ?

     

    To expand this a little further, the basic logic is to escape all user data before inserting into a db using your RDBMS escape string function, and to use htmlentities() upon grabbing data from a db. This converts things like quotes etc into their HTML entities before being executed. IMO, the safest way to work with databases is to use PDO, which separates the SQL and the user data.

  8. Not to worry. Based on what you said i've worked it out:

     

    $rows[] = $row[0];
    

     

    Thanks

     

    Hi Guys

     

    Using mysqli_fetch_array(), which i had anticipated would simply return a numeric array with all the results from the simple query. However, it keeps coming out as a multidimensional array, which isn;t what i want.

     

    Is this just how it works or have i done something wrong?

     

    Code

     

    $mysqli = new mysqli("localhost", "root", "", "ik");
    		if ($mysqli->connect_errno) {
    			echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    		}
    
    
    
    	$qry = "SELECT amount FROM teams";
    	$result = $mysqli->query($qry);
    
    	while($row = mysqli_fetch_array($result, MYSQLI_NUM))
    		{
    		$rows[] = $row;
    		//echo $row . "<br/>";
    		}
    
    		print_r($rows);
    
    

     

     

    Result

     

    Array
    (
        [0] => Array
            (
                [0] => 3
            )
    
        [1] => Array
            (
                [0] => 25
            )
    
        [2] => Array
            (
                [0] => 26
            )
    
        [3] => Array
            (
                [0] => 31
            )
    
        [4] => Array
            (
                [0] => 34
            )
    
        [5] => Array
            (
                [0] => 44
            )
    
        [6] => Array
            (
                [0] => 50
            )
    
        [7] => Array
            (
                [0] => 56
            )
    
        [8] => Array
            (
                [0] => 65
            )
    
        [9] => Array
            (
                [0] => 221
            )
    
        [10] => Array
            (
                [0] => 222
            )
    
        [11] => Array
            (
                [0] => 225
            )
    
        [12] => Array
            (
                [0] => 2210
            )
    
        [13] => Array
            (
                [0] => 2600
            )
    
    )

  9. I think i follow what you're saying but even if i do simply echo $row i get "Array" as the result. So it's a multidimensional array regardless.

     

    Can you suggest the best way to simply get a numeric array of results?

     

    Thanks for your help btw!

     

     

     

    For each record, mysqli_fetch_array() returns an array, with the contents of each field in an element. You're putting each array returned by mysqli_fetch_array() into a new element of another array, thereby creating a multidimensional array.

  10. Hi Guys

     

    Using mysqli_fetch_array(), which i had anticipated would simply return a numeric array with all the results from the simple query. However, it keeps coming out as a multidimensional array, which isn;t what i want.

     

    Is this just how it works or have i done something wrong?

     

    Code

     

    $mysqli = new mysqli("localhost", "root", "", "ik");
    		if ($mysqli->connect_errno) {
    			echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    		}
    
    
    
    	$qry = "SELECT amount FROM teams";
    	$result = $mysqli->query($qry);
    
    	while($row = mysqli_fetch_array($result, MYSQLI_NUM))
    		{
    		$rows[] = $row;
    		//echo $row . "<br/>";
    		}
    
    		print_r($rows);
    
    

     

     

    Result

     

    Array
    (
        [0] => Array
            (
                [0] => 3
            )
    
        [1] => Array
            (
                [0] => 25
            )
    
        [2] => Array
            (
                [0] => 26
            )
    
        [3] => Array
            (
                [0] => 31
            )
    
        [4] => Array
            (
                [0] => 34
            )
    
        [5] => Array
            (
                [0] => 44
            )
    
        [6] => Array
            (
                [0] => 50
            )
    
        [7] => Array
            (
                [0] => 56
            )
    
        [8] => Array
            (
                [0] => 65
            )
    
        [9] => Array
            (
                [0] => 221
            )
    
        [10] => Array
            (
                [0] => 222
            )
    
        [11] => Array
            (
                [0] => 225
            )
    
        [12] => Array
            (
                [0] => 2210
            )
    
        [13] => Array
            (
                [0] => 2600
            )
    
    )

  11. not sure how you render your pages but you could do with a simple conditional and an include.

     

    So when they log in you set a session variable to signify they've been authenticated and logged in.

     

    Then you can just do something simple like

     

    
    if (!isset($_SESSION['loggedin'])){
    
    include('slide_login_header.php')
    
    }
    
    else {// either do nothing or include an alternate header]
    
    
    
    

  12. Hi Psycho

     

    Thanks for taking the time to provide that!

     

    It wasn't my intention to mislead...i was more looking for some advice on the best way to do this (oringally) but your going the extra mile and providing the code is obviously extremely welcome and it helps loads to see the process used by someone who knows their onions :)

     

    Thank you.

     

    Drongo

     

    Ideally i would want to pass the failed rows to an array so i can output it to the user.

     

    So would that require that each row is inserted one at a time? Rather than inserting them all as one statement?

     

    You know, I fond it frustrating when I provide a solution based upon the requirements given only to have them changed :(

     

    No, it would not require you to insert them individually, it would only require two queries. First run one qeury to find the duplicate records, then run a second query to insert the new records.

     

    I don't think you ever stated what the unique field it, I will assume it is the 'teamnum' field. Anyway, if you need to determine which ones are duplicates, then you don't even need to use one of the ON DUPLICATE KEY methods. None of this is tested, but the process should work

    //Process the array into insert values
    $values = array(); //Array to hold insert values
    $teamNums = array(); //Array to hold team numbers
    
    //Process data into the temp arrays
    foreach($myarray as $record)
    {
        $teamNums[] = $record[2];
        $values[$record[2]] ="('{$record[0]}','{$record[1]}','{$record[2]}','{$record[3]}','{$record[4]}','{$record[5]}')";
    }
    
    //Run query to find existing duplicates
    $query = "SELECT `teamnum`
              FROM `teams'
              WHERE `teamnum` IN (" . implode(',', $teamNums) . ")";
    $result = mysql_query($query);
    
    //process existing team nums into temp array
    $existingTeamNums = array();
    while($row = mysql_fetch_assoc($result))
    {
        $existingTeamNums[] = $row['teamnum'];
    }
    
    //Calculate array of existing records
    $existingRecords = array_diff_keys($values, $existingTeamNums);
    
    //Calculate array of new records to insert
    $insertRecords = array_diff_keys($values, $existingTeamNums);
    
    //Create query to insert new records
    $query = "INSERT INTO teams
                  (company, teamname, teamnum, amountraised, country, president)
              VALUES " . implode(', ', $insertRecords);
    

  13. Hi Psycho

     

    That helps a lot.  And now you've tidied up the query i see how it could have been more efficient!

     

    Ideally i would want to pass the failed rows to an array so i can output it to the user.

     

    So would that require that each row is inserted one at a time? Rather than inserting them all as one statement?

     

     

    Well, what DO you want to happen for the records where the value is not unique? Do you want to update the record with the new values or skip it?

     

    By, the way, your loop is more complicated than it needs to be. Simply store the "values" for the query in an array and do an implode at the end to add the commas. Plus, if your values are in an array, you should be using a foreach() loop, not a for() loop

     

    //Process the array into insert values
    $values = array();
    foreach($myarray as $record)
    {
        $values[] ="('{$record[0]}','{$record[1]}','{$record[2]}','{$record[3]}','{$record[4]}','{$record[5]}')";
    }
    
    //Create query to IGNORE duplicates on unique field
    $sql = "INSERT INTO teams
                (company, teamname, teamnum, amountraised, country, president)
            VALUES " . implode(', ', $values) . "
            ON DUPLICATE KEY IGNORE";
    
    //Create query to UPDAtE duplicates on unique field
    //Include any fields you want updated in a comma separated list
    $sql = "INSERT INTO teams
                (company, teamname, teamnum, amountraised, country, president)
            VALUES " . implode(', ', $values) . "
            ON DUPLICATE KEY UPDATE
                amountraised=VALUES(amountraised)" ;

  14. Hi Guys

     

    Just need some advice to go in the right direction.

     

    I'm working on a csv upload script (part of a bigger thing i'm building), so i read in the csv to a multipdimensional array and then build a query that inputs all rows in one query - i read this is the most efficient way to import multiple rows of data at once(rather than multiple insert statements). Just for illustration here's the code i use to build the query so you understand what i'm on about:

     

    $sql = "INSERT INTO teams (company, teamname, teamnum, amountraised, country, president) VALUES ";
    
    	// $rows is a count of the rows in the csv
    
    	for($i=1; $i<$rows; $i++){
    
    		$sql.="('{$myarray[$i][0]}','{$myarray[$i][1]}','{$myarray[$i][2]}','{$myarray[$i][3]}','{$myarray[$i][4]}','{$myarray[$i][5]}')";
    		echo $i . "<br/>";
    
    		if($i >= 1 && $i < $rows - 1)
    			{
    				$sql.= ",";
    			}
    	}
    

     

    Anyway, the issue is that one of the fields("teamnum") needs to be unique - so i've set this as unique on the table in mysql.

     

    But when i run my query it doesn't import anything if one of the records isn't unique. What i really want is for it to import the ones it can and catch the ones it cant import to present to the user.

     

    So my question is - to acheive the above would i need to rewrite the query so that it inserts each row one at a time, instead of all together?

     

    Or can someone point me in the right direction for a better solution?

     

    Probably something very simple i've missed i am sure...

     

    Thanks chaps!

     

     

  15. Cheers marc that;s good to know.  I can see keeping curly braces in mind can probably come in very handy!

     

     

    Do curly braces tell php to interpret that part first?

     

    Lol, I guess some one will just have to call up Rasmus Lerdorf for a full explanation. But also be aware of the use of curly braces in variables in order to separate it for from the rest of the text. For instance:

     

    $begin = "connec";
    $dona = "educa";
    $dona = "presenta";
    $dona = "evolu"
    
    // normally you would do:
    $myVar = 'The word' . $dona . 'tion could have a different beginning but always ends the same way.';
    
    // but alternatively you can do (greedy token parsing):
    $myVar = "The word {dona}tion could have a different beginning but always ends the same way.";
    

    So in order to separate $dona from "tion" you use the curly braces, thus avoiding php from reading the string as $donation. Figured I would point this out for informational purposes considering it is probably closely related to the use of concatenation and curly braces in the array.

  16.  

    Ahhh....i was trying to use braces but i wasn't wrapping the whole variable.  haha that makes me wonder about something else...

     

    Do curly braces tell php to interpret that part first?

     

     

     

    Err... mind explaining to me why you wrapped it in double quotes and then concatenated?

     

    That is actually a very good question, I am tempted to say it has something to do with greedy token, but that wouldn't make any sense. If anyone knows please share!

     

    But alternatively you can use braces like so (it's more readable in my opinion):

    "INSERT INTO 2012hitting (hr) VALUES ('{$myArray[0][3]}')"

     

    Or you can just asign the array value before hand and insert a regular string like so:

    $myValue = $myArray[0][2];
    $sql = "INSERT INTO 2012hitting (hr) VALUES ('$myValue')";

  17. Well that sounds like a pretty decent explanation to me :)

     

    I was more concerned there was some fundamental syntax thing i had completely overlooked.

     

    It's good to know how to make it work though so thank you very much!

     

     

     

     

     

     

    To be honest I don't know the actual reason. You can place a single postion into a "" string:

     

     

    $a[] = 'ss';
    echo <<<_END
    $a[0]
    _END;
    

     

     

    But when you chuck in another dimension with the extra set of square brackets, php trips up.

     

     

    So as your query in $sql is essentailly a string, by breaking the string and joining it to the array pos, then joining the rest of the query to the end the $sql... $sql then becomes the string you wanted it to be in the first place.

     

     

    However i'm pretty sure there is a better explanation.. and I would actually like to know it too... i notice you have Adam reading this thread.. hopefully he will be able to give a better explanation to the one i gave :)

     

     

    (you can actually write less code there by placing the query directly into the mysqli:

     

     

     

       $mysqli->query( "INSERT INTO teams (company) VALUES ('".$myarray[1][1]."')" );
    

  18. Hi Guys

     

    Clearly I still have lots to learn...

     

    I am trying to insert (using mysqli) multi-dimensional array values into the database, but when i do the value that gets stored  ends up as "$Array[1][1]".

     

    Here's the test query i am running:

     

    $sql = "INSERT INTO teams (company) VALUES ('$myarray[1][1]')";
    $mysqli->query($sql);
    

     

    So do i need to break the data out of the multidimensional array for the insert? Or is there some syntax thing i've missed?

     

    Or worse still do i actually need to do:

     

    $value1 = $myarray[0][0]; 
    

     

     

     

    Any help would be very much appreciated!

     

    Drongo

×
×
  • 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.