Jump to content

leke

Members
  • Posts

    39
  • Joined

  • Last visited

Posts posted by leke

  1. Hi, I'm trying to insert data into two different tables using, but am getting an error I can't figure out. If I move the $mysqli->commit(); into the foreach loop, I get at least one returned row before the rest fail. The error current error message is Array ( [0] => Error: Couldn't insert into english! ). Any idea what is causing this?

    <?php 
    
    $file_array = file('../grammar/conjunctions.txt');
    $csv = array_map('str_getcsv', $file_array);
    
    // DB
    $mysqli = new mysqli('localhost', 'root', '******', 'angos');
    
    $mysqli->autocommit(false);
    $error = array();
    
    foreach($csv as $value)
    {
        $angos_query = $mysqli->query("INSERT INTO angos (angos, grammar) VALUES ('$value[0]', 'con')");
        $id = $mysqli->insert_id; // grab the currant angos table id
        if($angos_query == false)
        {
            array_push($error, "Error: Couldn't insert into angos!");
        }
        
        $english_query = $mysqli->query("INSERT INTO english (angos_id, english) VALUES ('$id', '$value[1]')");
        if($english_query == false)
        {
            array_push($error, "Error: Couldn't insert into english!");
        }
        
        if(!empty($error))
        {   
            $mysqli->rollback();
        }
        
    }
    
    $mysqli->commit();
    
    print_r($error);
    // print_r($csv);
    
    ?> 
    

    More info SQL:

    CREATE TABLE angos 
    	(
            id int unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, 
            angos varchar(255) not null, 
            grammar varchar(3) not null, 
            updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            CONSTRAINT unique_input UNIQUE (angos)
        ) engine=InnoDB;
    
    CREATE TABLE english 
    	(
            id int unsigned not null primary key,
            angos_id int unsigned,
            english varchar(255),
            grammar_note varchar(500),
            CONSTRAINT fk_angos_source FOREIGN KEY (angos_id) REFERENCES angos(id) ON DELETE CASCADE ON UPDATE CASCADE
        ) engine=InnoDB;
    
  2. so why are you formatting yours as YYYY-M-D

    To be honest, I didn't really give it much thought :D I was just going with something that works quick, then I usually play with it and make some changes to the formatting based on problems I might foresee. I usually go with year month day as it's usually the most computer friendly format (along with being quite readable and international), but I also see I made an error in the comment writing mm-dd instead of m-d.

  3. You could try htmlentities() to see what was in there.

    htmlentities didn't show any newline evidence, but I noticed in the source output, the elements are formatted with a newline so I guess they hang around when using file(). 

  4. Hi, For some I can't match these two strings...

     

    $timestamp = mktime() + CURR_TIME_OFFSET * 3600;
    $d = date('j', $timestamp);  
    $m = date('n', $timestamp);  
    $y = date('Y', $timestamp);
    $isCancelledCheck = (string) "$y-$m-$d";
    echo "Date: $isCancelledCheck is a " . gettype($isCancelledCheck) . "<br>";
    
    $db_read = file('cancelled_dates.txt'); // read YYYY-MM-DD lines of file to an array.
    
    foreach($db_read as $key => $val) {
        // iterate through each element of db_read
        if ($val == $isCancelledCheck){
            echo "<br> $val == $y-$m-$d";
        } else {
            echo "<br>Skipped $val";
        }    
    }
    
    print_r($db_read);
     

     

     

    which returns...


     

    Date: 2013-3-4 is a string

    Skipped 2013-4-4 is a string
    Skipped 2013-3-4 is a string
    Skipped 2012-3-4 is a string
    Skipped 2013-3-5 is a string
    Skipped 2013-2-4 is a string

     

    Array ( [0] => 2013-4-4 [1] => 2013-3-4 [2] => 2012-3-4 [3] => 2013-3-5 [4] => 2013-2-4 )

     

    How come the string 2013-3-4 is not matched here?

     

    Thanks.

  5. I have a file with four lines of text (no empty lines).

    Apocalypto (2006)

    Doubt (2008)

    The Skin I Live In (2011)

    Tucker and Dale vs Evil (2010)

    and I want to grab four random keys from it...

    php > $movie_title_file = "4-movies.txt";
    php > $access_movie_title_db = file_get_contents($movie_title_file);
    php > $movie_title_db = explode("\n", $access_movie_title_db);
    php > $random_index = array_rand($movie_title_db,4);
    php > shuffle($random_index);
    php > print_r($random_index);
    Array
    (
    [0] => 4
    [1] => 1
    [2] => 0
    [3] => 2
    )
    

    as you can see, the results range form 0 to 4. That's five though and if I wanted to use the results to print out the index key to that line, then

    echo $movie_title_db[$random_index[0]];

    would print nothing because the $movie_title_db only has 0 to 3 (or 4) items.

     

    How come array_rand works like this?

     

    Thanks :)

  6. One of my preg_replace lines doesn't work and I can't figure out why. It's very similar to another line which works fine.

     

    $quote = '<ol>
    
    <li>
    <span class="bold quote_actor">
    Delia Surridge:
    </span>
    
    <span class="line">
    Is it meaningless to apologize?
    </span>
    </li>
    <li>
    <span class="bold quote_actor">
    V:
    </span>
    
    <span class="line">
    Never.
    </span>
    </li>
    <li>
    <span class="bold quote_actor">
    Delia Surridge:
    </span>
    
    <span class="line">
    I'm so sorry.
    </span>
    </li>
    
    </ol>';
    
    $quote = preg_replace("'<ol>(.*?)<li>'", '', $quote); // first 2 tags
    $quote = preg_replace("'\s+'", ' ', $quote); // more than one space
    $quote = preg_replace("'</li>(.*?)<li>'", '<br /><br />', $quote); // separate quote lines
    $quote = preg_replace("'</li>(.*?)</ol>'", "\n", $quote); // last 2 tags
    echo $quote;

    So, everything works fine except

     $quote = preg_replace("'<ol>(.*?)<li>'", '', $quote); // first 2 tags

    ...which doesn't do its job. How come? It's very similar to

    $quote = preg_replace("'</li>(.*?)</ol>'", "\n", $quote); // last 2 tags
    

    Which works just fine.

     

    Thanks.

  7. How can I store the returned result of a function that outputs an array, so I can pass parts of it to other functions? As you can se, this function will have different output each time it is called as a function.

     

    Thanks.

     

    <?php
    
    $apikey = '1234567890';
    $movie_title_file = "5000-movies.txt";
    $access_movie_title_db = file_get_contents($movie_title_file);
    $movie_title_db = explode("\n", $access_movie_title_db);
    
    function getMovieObject() {
    
    global $apikey, $movie_title_file, $access_movie_title_db, $movie_title_db;
    $random_index = array_rand($movie_title_db,1);
    $query = $movie_title_db[$random_index]; // end result is a film title to query.
    $url_title = urlencode($query); // make sure to url encode an query parameters
    // Taken from the RT API...
    
    // construct the query with our apikey and the query we want to make
    $endpoint = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=' . $apikey . '&q=' . $url_title;
    // setup curl to make a call to the endpoint
    $session = curl_init($endpoint);
    // indicates that we want the response back
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    // exec curl and get the data back
    $data = curl_exec($session);
    // remember to close the curl session once we are finished retrieveing the data
    curl_close($session);
    
    // decode the json data to make it easier to parse the php
    $search_results = json_decode($data);
    if ($search_results === NULL) die('Error parsing json');
    $movies = $search_results->movies;
    
    return $movies;
    }
    

  8. I've managed to follow it to

    	
    if ( $password_hash == $row["password"] ) { // changed
    	$auth = $row['userlevel'];
    
    	if ($register) {
    		$_SESSION['authdata'] = array(
    			'login'     => $row['username'], 
    			'password'  => $row['password'], 
    			'userlevel' => $row['userlevel'], 
    			'uid'       => $row['uid'],
    		);

    All the data here is correct until it leaves the function. Then the $_SESSION['authdata'][...] data disappears (resets to $auth = 0;). But all the conditions were met, so I have no idea why it resets.

  9. I'm modifying php event calendar and tried to add support for sha1 salted passwords. The check seems to return true, but the code to display the calendar fails if I use the new code (no error, just goes back to the original screen). Could someone have a look at the new and old functions responsible for the login? I've commented the changed lines with // changed.

    I've also modified  the calendar not to show unless $auth was true. Also included at the end. This is the one that doesn't evaluate $auth for some reason after the login.

     

    Thanks.

     

    function auth($login = '', $passwd = '') 
    {
    
    session_start();
    $auth     = 0;
    $register = false;
    $authdata = null;
    
    if (isset($_SESSION['authdata'])) {
    	$authdata = $_SESSION['authdata'];
    }
    
    # return false if login neither passed to func, nor in session
    if (empty($login) && empty($authdata['login'])) {
    	return 0;
    }
    
    # get login passed to function
    if (!empty($login)) {
    	$username = $login;
    	$pw       = $passwd;
    	$salt = $pw; // changed
    	$password_hash = sha1($salt.sha1($pw.$salt)); // changed
    	$register = true;
    } else {
    	$username = $authdata['login'];
    	$pw       = $authdata['password'];
    }
    
    mysql_connect(DB_HOST, DB_USER, DB_PASS) or die(mysql_error());
    mysql_select_db(DB_NAME) or die(mysql_error());
    
    $sql = "
    	SELECT * FROM " . DB_TABLE_PREFIX . "users 
    	WHERE username = '" . $username . "'";
    $result = mysql_query($sql) or die(mysql_error());
    $row = mysql_fetch_assoc($result);
    
    # validate login, and register session data if appropriate 
    if ( $password_hash == $row["password"] ) { // changed
    	$auth = $row['userlevel'];
    
    	if ($register) {
    		$_SESSION['authdata'] = array(
    			'login'     => $row['username'], 
    			'password'  => $row['password'], 
    			'userlevel' => $row['userlevel'], 
    			'uid'       => $row['uid'],
    		);
    	}
    } else {
    	# if passwords didn't match, delete authdata session data 
    	unset($_SESSION['authdata']);
    }
       	return $auth;
    }

    function OLD_auth($login = '', $passwd = '') 
    {
    session_start();
    $auth     = 0;
    $register = false;
    $authdata = null;
    
    if (isset($_SESSION['authdata'])) {
    	$authdata = $_SESSION['authdata'];
    }
    
    # return false if login neither passed to func, nor in session
    if (empty($login) && empty($authdata['login'])) {
    	return 0;
    }
    
    # get login passed to function
    if (!empty($login)) {
    	$username = $login;
    	$pw       = $passwd;
    	$register = true;
    } else {
    	$username = $authdata['login'];
    	$pw       = $authdata['password'];
    }
    
    mysql_connect(DB_HOST, DB_USER, DB_PASS) or die(mysql_error());
    mysql_select_db(DB_NAME) or die(mysql_error());
    
    $sql = "
    	SELECT * FROM " . DB_TABLE_PREFIX . "users 
    	WHERE username = '" . $username . "'";
    $result = mysql_query($sql) or die(mysql_error());
    $row = mysql_fetch_assoc($result);
    
    # validate login, and register session data if appropriate 
    if ( $pw == $row["password"] ) {
    	$auth = $row['userlevel'];
    
    	if ($register) {
    		$_SESSION['authdata'] = array(
    			'login'     => $row['username'], 
    			'password'  => $row['password'], 
    			'userlevel' => $row['userlevel'], 
    			'uid'       => $row['uid'],
    		);
    	}
    } else {
    	# if passwords didn't match, delete authdata session data 
    	unset($_SESSION['authdata']);
    }
       	return $auth;
    }
    

     

    ...code to display the calendar...

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title></title>
    <?php javaScript() ?>
    <link rel="stylesheet" type="text/css" href="css/default.css">
    </head>
    <body>
    
    <br><br>
    
    <table cellpadding="0" cellspacing="0" border="0" align="center">
    
    <?php 
    
    if(!$auth){
    echo "<tr><td><span style=\"font-size:xx-large; text-align:center; color:red; padding:100px;\">Please login to see the availability calendar.</span></td></tr>";
    } else {
    echo "<tr><td>";
    echo $scrollarrows;
    echo '<span class="date_header"> '; 
    echo $lang['months'][$m-1];
    echo ' '; 
    echo $y;
    echo '</span></td><!-- form tags must be outside of <td> tags --><form name="monthYear"><td align="right">';
    
    monthPullDown($m, $lang['months']); 
    yearPullDown($y);
    
    echo '<input type="button" value="GO" onClick="submitMonthYear()"></td></form></tr><tr> <!-- This is the calendar layout --><td colspan="2" bgcolor="#000000">';
    
    echo writeCalendar2($m, $y);
    echo "</td></tr>";
    }
    ?>
    
    <tr>
    <td colspan="2" align="center">
    <?php echo footprint($auth, $m, $y) ?></td>
    </tr>
    </table>
    
    </body>
    </html>

  10. I was wondering if it was good practice to use switch without break for this example...

    <input type="checkbox" name="box1" value="1" />
    <input type="checkbox" name="box2" value="1" />
    <input type="checkbox" name="box3" value="1" />
    <input type="checkbox" name="box4" value="1" />
    
    $box1	= $_POST['box1'];
    $box2	= $_POST['box2'];
    $box3	= $_POST['box3'];
    $box4	= $_POST['box4'];
    
    switch ($i = '1') {
        case $box1:
            // do something;
        case $box2:
            // do something;
        case $box3:
            // do something;
        case $box4:
            // do something;
        default:
        	echo "All checkboxes where left unchecked";
    }
    ?>

    Or perhaps there would be a better way?

    Thanks.

  11. No error returned, but the date returned is just January 01st 1970 - 12:00am (without UTC). If I remove the . ' UTC', the correct date is shown.

     

    Here is some more code that is related to the date...

    
    // Format the time/Date
    date_default_timezone_set('UTC');
    $inputTime = date('c');
    $inputTime = $inputTime . ' (UTC)';
    
    // Send all data so far, to an array.
    $entry_array = array();
    array_push($entry_array, $inputTime, $userName, $message_br);
    
    // write the array to CSV file.
    $fp = fopen('messages.txt', 'a');
    fputcsv($fp, $entry_array, "|");
    fclose($fp);
    
    session_destroy();
    

  12. Trying to validate a form for empty input using empty() but when I introduced it to my code, I get the error...

    Fatal error: Call to undefined function  empty() in /srv/disk1/940225/www/domain.co.cc/contact_db/sanitize.php on line 13

    Here is where I introduced it...

    $message = $_POST['message']; 
    
    if( !isset($message) || empty($message) ) {
    ...

    What am I doing wrong here?

    Thanks.

  13. The double colon is the Scope Resolution Operator http://php.net/manual/en/keyword.paamayim-nekudotayim.php

     

    Did you mean to use it that way?

    Nope. I used it as a delimiter in my text file db.

    I've still been working on the code. I have it down a bit better now...

    <?php
    $txt1 = file('txt1.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 
    $txt2 = file('txt2.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 
    
    $storage1 = array(); 
    $storage2 = array(); 
    
    foreach ($txt1 as $line){
        array_push($storage1, list($part1, $part2) = explode('::', $line));
    }
    
    foreach ($txt2 as $line){
        array_push($storage2, list($part1, $part2) = explode('::', $line));
    }
    ?>

    ...I just have to figure out how to check every $storage1[v][0] against  $storage2[v][0] for equality.

    ;)

  14. I'm trying to compare 2 files, each with data separated by ::. I'm trying to make a comparison that if the data to the left of the separator from one file is not found in the same column of the other file, then it is copied to an array.

    For example:

    file1.txt

    abc::def

    ggg::hhh

    mmm::ppp

     

    file2.txt

    abc::def

    zzz::aaa

    bbb::ccc

     

    So...

    ggg::hhh

    mmm::ppp

    is copied from file1.txt because ggg and mmm was not found on the same side in file2.txt

     

    ...but I'm not getting any error message with this. The operation just hangs.

    <?php
    $dic1 = file('file1.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 
    $dic2 = file('file2.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 
    $titleText = array(); // Storing results into this array.
        
    foreach ($dic1 as $dic1line){
        list($dic1field1, $dic1field2) = explode('::', $dic1line);
            foreach ($dic2 as $dic2line){
                list($dic2field1, $dic2field2) = explode('::', $dic2line);
                if ($dic1field1 != $dic2field1) { // Found a non match in DB.
                    array_push($titleText, "$dic1field1 :: $dic1field2\n"); // Store all finds in array.  
                }
            }
    }
    
    // Finish outputting anything left over.
    if (empty($titleText)) { // $value was not found -- array is empty.
        echo 'All matched, or something else.';
    } else {
        $arrayOut = implode("", $titleText); // output the results found in the search.
        echo $arrayOut;
    }
    
    unset($value);
    ?>
    

     

    Anyone know how to do this?

    Thanks.

  15. Hi, Anyone know what's wrong with this? There is meant to be a SQL syntax error, but it looks ok to me ::)

     

    $postedThreadId = 18;

    $postOrderPlusOne = "UPDATE threadId SET MAX(postOrder) + 1 FROM post_table WHERE postOrder = $postedThreadId";

     

    Error:

    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'MAX(postOrder) + 1 FROM post_table WHERE postOrder = 18' at line 1

     

    Thanks :-*

  16. This line:

     

    if (strlen($password) < 5 || > strlen($password) 26) {

     

    It should be strlen($password) > 26

     

    And also this line:

     

    if ($password == $userName {

     

    You're missing a parenthesis.

    Dang, I was reading the wrong line! Thanks also for spotting the other error :)

  17. Here goes ;)

    <?php
    session_start();
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type" />
    <title></title>
    </head>
    <body>
    <br />
    
    <?php
    
    $username = $_POST['userName'];
    $password = $_POST['password'];
    
    // Sanitise /////////////////////////////////////////
    
    // Verify if captcha was entered correctly
    if ($_SESSION['key'] == $_POST['verify']) {
    // success continue the script.
    } else {
    echo '<p class="fail">Wrong captcha entered. <br />Use the browser\'s back button to correct your mistake.</p>';
    exit;
    }
    
    // Empty username input?
    if ($username) {
    // success continue the script.
    } else {
    echo '<p class="fail">You cannot submit empty userName. <br />Use the browser\'s back button to correct your mistake.</p>';
    exit;
    }
    
    // Wrong username length?
    if ( ( strlen($username) < 2 || strlen($username) > 26 ) ) {
    echo '<p class="fail">Username must be between 2-26 characters long. <br />Use the browser\'s back button to correct your mistake.</p>';
    exit;
    }
    
    // Empty password input?
    if ($password) {
    // success continue the script.
    } else {
    echo '<p class="fail">You cannot submit empty password. <br />Use the browser\'s back button to correct your mistake.</p>';
    exit;
    }
    
    // Wrong Password length?
    if (strlen($password) < 5 || > strlen($password) 26) {
    echo '<p class="fail">Password must be between 5-26 characters long. <br />Use the browser\'s back button to correct your mistake.</p>';
    exit;
    }
    
    // Same username and pssword?
    if ($password == $userName {
    echo '<p class="fail">Username and Password cannot match. <br />Use the browser\'s back button to correct your mistake.</p>';
    exit;
    }
    
    
    // Connect to DB /////////////////////////////////////////////////////////
    $conn = mysql_connect("localhost",  "admin", "password");
    mysql_select_db("forum", $conn);
    if (!$conn) {
        die('<p class="fail">Could not connect to DB: </p>' . mysql_error());
    }
    echo '<p class="success">Connected to DB successfully.</p>';
    
    // INSERT data
    $sql = "INSERT INTO login_table values ('$userName', SHA1('$password') )";
    if (mysql_query($sql, $conn)) {
    echo '<p>Registered as: ' . $username . '.<br />Click here to start using the forum.</p>'
    } else {
    echo '<p class="fail">Error: Failed to INSERT INTO MySQL.</p>';
    }
    
    
    ?>
    
    </body></html>

    It reports the error now on line 51. I've been doing some editing to the file. Thanks.

  18. Hi, I can't figure out what I'm doing wrong because I don't understand why I'm getting...

     

    Parse error: syntax error, unexpected T_LNUMBER in /home/leke/public_html/test/forum/registration_script.php on line 37

     

    ...which the php manual is to do with integers.

     

    Line 37 is:

    if ( ( strlen($username) < 2 || strlen($username) > 26 ) ) {

     

    $username = $_POST['userName'];
    
    // Wrong username length?
    if ( ( strlen($username) < 2 || strlen($username) > 26 ) ) {
    echo '<p class="fail">Username must be between 2-26 characters long.</p>';
    exit;
    }

     

    Is there a problem on that line?

     

    Thanks.

  19. I have 2 pieces of different code that get run at different times, but act on the same text file.

    (The first example writes data and the second rewrites data with some expired data removed from the rewrite.)

     

    The first code example appends data to a new line each time it is run except when it is run just after the second code example has ran. When run after the second example, the first code example will append the data to the last line of the text file instead of appending to a new line.

    Why is this?

     

    Here is the first code example...

    <?php
    
    $message = "Hello, World! \nGoodbye!";
    $message_br = str_replace("\n", '<br />', $message); // couldn't use nl2br because i needed to remove the \n completely. 
    $userName = "Anon";
    $coordinates = "1234567890";
    $locationType = "geo";
    $dateDay = "23";
    $dateMonth = "2";
    $dateYear = "2011";
    $timeHour = "9";
    $timeMins = 45;
    $timeAMPM = "AM";
    
    // Format the time/Date
    date_default_timezone_set('UTC');
    $inputTime = date('c', mktime((int)$timeHour, (int)$timeMins, 0, (int)$dateMonth, (int)$dateDay, (int)$dateYear));
    
    // Send all data so far, to an array.
    $entry_array = array();
    array_push($entry_array, $inputTime, $locationType, $coordinates, $userName, $message_br);
    
    // write the array to CSV file.
    $fp = fopen('messages.txt', 'a');
    fputcsv($fp, $entry_array, "|");
    fclose($fp);
    
    ?>
    

     

    Here is the second...

    <?php
    
    $one_day = 60*60*24;
    $timestamp = time();
    date_default_timezone_set('UTC');
    $expiry_date = date('c', $timestamp+$one_day); 
    
    $future_date = array();
    $delete_line = array();
    
    // Open existing data in the text file.
    $lines = file('messages.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 
    foreach ($lines as $line){
      list($field1, $field2, $field3, $field4, $field5) = explode('|', $line);
      if ($field1 < $expiry_date){ 
        array_push($delete_line, $line); // add to the to-be-deleted array.
      }
      else { array_push($future_date, $line); }
    }
    
    $array2string = implode("\n", $future_date); // convert array data to string.
    
    // write the data to CSV file.
    $fp = fopen('messages.txt', 'w');
    fwrite($fp, $array2string);
    fclose($fp);
    
    ?>
    

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