Jump to content
Larry Ullman's Book Forums

Search the Community

Showing results for tags 'mysqli'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Single Editions
    • Modern Javascript: Develop and Design
    • The Yii Book
    • Effortless Flex 4 Development
    • Building a Web Site with Ajax: Visual QuickProject
    • Ruby: Visual QuickStart Guide
    • C++ Programming: Visual QuickStart Guide
    • C Programming: Visual QuickStart Guide
    • Adobe AIR: Visual QuickPro Guide
  • PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide
    • PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (5th Edition)
    • PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (4th Edition)
    • PHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide (3rd Edition)
    • PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (2nd Edition)
    • PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (1st Edition)
  • PHP for the Web: Visual QuickStart Guide
    • PHP for the Web: Visual QuickStart Guide (5th Edition)
    • PHP for the Web: Visual QuickStart Guide (4th Edition)
    • PHP for the Web: Visual QuickStart Guide (3rd Edition)
    • PHP for the World Wide Web: Visual QuickStart Guide (2nd Edition)
    • PHP for the World Wide Web: Visual QuickStart Guide (1st Edition)
  • Effortless E-commerce with PHP and MySQL
    • Effortless E-Commerce with PHP and MySQL (2nd Edition)
    • Effortless E-Commerce with PHP and MySQL
  • PHP Advanced: Visual QuickPro Guide
    • PHP Advanced and Object-Oriented Programming: Visual QuickPro Guide (3rd Edition)
    • PHP 5 Advanced: Visual QuickPro Guide (2nd Edition)
    • PHP Advanced: Visual QuickPro Guide
  • MySQL: Visual QuickStart Guide
    • MySQL: Visual QuickStart Guide (2nd Edition)
    • MySQL: Visual QuickStart Guide (1st Edition)
  • Other
    • Announcements
    • Newsletter, Blog, and Other Topics
    • Forum Issues
    • Social

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Found 14 results

  1. Please I need your help, I am new to PHP and I need your help in inserting multiple select array into the database in the form of this.This is what I want to achieve. My table has 5 columns (id, examno, subjects, grades, results). I want results column to be inform of subjects grades, subjects grades.........depending on the numbers of subjects and grades users select (e.g English C6, Mathematics C6) all in one column results. This is my html codes <form action="insert.php"> <div class="form-group"> <label>Exam Number</label> <input type="text" class="form-control" name="examno" id="examno"> </div> <table width="100%" cellpadding="0" cellspacing="0" border="0" class="table table-borderless" id="example"> <tr> <td width="12%"><label class="control-label">S/NO</label></td> <td width="53%"><label class="control-label">SUBJECTS</label></td> <td width="35%"><label class="control-label">GRADE</label></td> </tr> <tr> <td>1</td> <td> <select name="subjects[]" class="form-control" id="subject"> <option value="" selected="selected">Select subject</option> <option value="English">English</option> <option value="Mathematics">Mathematics</option> </select> </td> <td> <select name="grades[]" class="form-control"> <option value=""> Select</option> <option value="A1">A1</option> <option value="B2">B2</option> </select> </td> </tr> </table> <input type="submit"> </form> I have about 8 subjects and grades to be inserted like that Also this is my insert.php if(isset($_POST['submit'])){ $examno = mysqli_real_escape_string($conn, $_POST['examno']); foreach($_POST['subjects'] as $row=>$subjects){ $subjects = mysqli_real_escape_string($conn, $subjects); $grades = mysqli_real_escape_string($conn, $_POST['grades'][$row]); $results = $subjects." ".$grades; } $sql = "INSERT INTO qualifications(examno, subjects, grades, results) VALUES('".$examno."', '".$subjects."', '".$grades."', '".$results."')"; $result = mysqli_query($conn, $sql); if($result){ header("location:declaration.php"); // user will be taken to the success page } else{ echo "Oops. Something went wrong. Please try again"; } } Nothing was inserted into the subjects, grades, and results. Please help me as I am new to php/mysqli
  2. I believe that I have followed the code to create a "Forget Password" link. However, I am getting an error that seems to indicate that I am asking for a password hash twice - Fatal error: Cannot redeclare get_password_hash() (previously declared in /hermes/bosnacweb04/bosnacweb04aj/b717/nf.xxxxxxxxxxxx/public_html/xxxxxxxxxxxx/TBRMobile/mysqli.inc.php:28) in /hermes/bosnacweb04/bosnacweb04aj/b717/nf.xxxxxxxxxx/public_html/xxxxxxx/TBRMobile/mysqli.inc.php on line 33 ---- I have x'd out certain areas of this error on purpose. My config file and mysqli file are almost exact. I do not use a header file.
  3. I am looking to recreate the following function from PDO to MySQLi but having some problems, I've been over the PHP website to read the functions. I'm trying to modularize my code in like the MVC pattern. public function bind($param, $value, $type=''){ if(is_null($type)){ switch(true){ case is_int($value): //Thinking something like, for integer etc $type = mysqli_stmt::bind_param(i); $type = PDO::PARAM_INT; break; case is_bool($value): $type = PDO::PARAM_BOOL; break; default: $type = PDO::PARAM_STR; } } $this->stmt->bindvalue($param,$value,$type); } Is it as simple as just replacing PDO version line to : $type = mysqli_stmt::bind(i); or just putting $type = i; Then in my class I am trying to call the bind function: $database ->bind($stmt,$ype,$variables); $database->execute(); Any help would be much appreciated Regards My Setup Chrome Windows XP Wamp SublimeText
  4. I created various websites (based on Larry's code) that worked fine for years, but after my web hosting company upgraded to PHP Version 5.6.27, I repeatedly receive this error message: "An error occurred in script '.../mysql_connect.php' on line 8: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead" I was able to suppress that error message on one website by prepending the "@" symbol to the expression, but strangely it did not work on another site. I'd like to know why (as a quick fix), and whether I can do something to suppress error messages for an entire site instead of using "@" multiple times. I'd also love to know how to change my code to work with PDO (preferably) or MySQLi; my web host supports both. It would be great to see an example of PHP handling data with old MySQL code and PHP working with PDO or MySQLi, to see how to "translate" it, so to speak. However, I don't want to use PDO if that requires me to learn Object-Oriented PHP; all my sites are based on procedural PHP. The above error message is generated in response to this mysql_connect.php code: <?php error_reporting(0); // didn't suppress error message ini_set('display_errors',0); // didn't suppress error message DEFINE ('DB_USER', '***'); DEFINE ('DB_PASSWORD', '***'); DEFINE ('DB_HOST', '***'); DEFINE ('DB_NAME', '***'); if ($dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD)) { // this is the line generating the error message if (@!mysql_select_db (DB_NAME)) { trigger_error("Could not select the database!\n<br />MySQL Error: " . mysql_error()); exit(); } } else { trigger_error("Could not connect to MySQL!\n<br />MySQL Error: " . mysql_error()); exit(); } function escape_data ($data) { if (ini_get('magic_quotes_gpc')) { $data = stripslashes($data); } if (function_exists('mysql_real_escape_string')) { global $dbc; $data = @mysql_real_escape_string (trim($data), $dbc); } else { $data = @mysql_escape_string (trim($data)); } return $data; } ?> Thank you!
  5. I am working on the Admin area for the coffee shop site, and I am encountering an error when the query to get all products to list them on the page. I cut and paste the query because it was so complicated, thinking I would make a syntax error. I am getting an error anyway! An error occurred in script 'C:\vhosts\clever-coffee.net\html\admin\add_inventory.php' on line 94: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given Array( [0] => Array ( [function] => my_error_handler [args] => Array ( [0] => 2 [1] => mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given [2] => C:\vhosts\clever-coffee.net\html\admin\add_inventory.php [3] => 94 [4] => Array ( [_GET] => Array ( ) [_POST] => Array ( ) [_COOKIE] => Array ( [SESSION] => 115cadb3f0e62db701dc0055e125b213 [PHPSESSID] => 115cadb3f0e62db701dc0055e125b213 ) [_FILES] => Array ( ) [_SERVER] => Array ( [HTTP_HOST] => clever-coffee.net [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; rv:40.0) Gecko/20100101 Firefox/40.0 FirePHP/0.7.4 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5 [HTTP_ACCEPT_ENCODING] => gzip, deflate [HTTP_REFERER] => http://clever-coffee.net/html/admin/add_coffee.php [HTTP_COOKIE] => SESSION=115cadb3f0e62db701dc0055e125b213; PHPSESSID=115cadb3f0e62db701dc0055e125b213 [HTTP_X_INSIGHT] => activate [HTTP_CONNECTION] => keep-alive [HTTP_CACHE_CONTROL] => max-age=0 [PATH] => C:\Program Files\ActiveState Komodo Edit 9 nightly\;C:\ProgramData\Oracle\Java\javapath;C:\ImageMagick;C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\PROGRA~1\IBM\CLIENT~1;C:\PROGRA~1\IBM\CLIENT~1\Shared;C:\PROGRA~1\IBM\CLIENT~1\Emulator;c:\Program Files\Java\jdk1.7.0_45\bin;C:\Program Files\Java\jdk1.7.0_51\/bin;C:\Apache Subversion 1.8.8\bin;C:\limejs\bin;C:\DevStack\MariaDB10\bin;c:\DevStack\php;c:\DevStack\php\ext;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\GnuWin32\bin;c:\drush;C:\PostgreSQL;C:\PostgreSQL\bin;C:\MinGW\bin;C:\devtools\bin\Ruby200\bin;C:\Windows\system32\WindowsPowerShell\v1.0\;C:\Python27\;C:\Python27\Scripts;C:\ImageMagick;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\PROGRA~1\IBM\CLIENT~1;C:\PROGRA~1\IBM\CLIENT~1\Shared;C:\PROGRA~1\IBM\CLIENT~1\Emulator;c:\Program Files\Java\jdk1.7.0_45\bin;C:\Program Files\Java\jdk1.7.0_51\/bin;C:\Apache Subversion 1.8.8\bin;C:\limejs\bin;C:\DevStack\mysql-5.6.19\bin;C:\DevStack\mysql-5.6.19\;C:\DevStack\mysql-5.6.19\Doctrine extensions for PHP\;c:\DevStack\php;c:\DevStack\php\ext;C:\Program Files\nodejs\;C:\Users\vmielke\AppData\Roaming\npm;C:\ProgramData\chocolatey\bin;C:\devtools\bin;\Git\bin;\Git\cmd;C:\devtools\bin\ruby\bin;C:\Users\vmielke\.gems;C:\Users\vmielke\.gems\bin [SystemRoot] => C:\Windows [COMSPEC] => C:\Windows\system32\cmd.exe [PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.RB;.RBW [WINDIR] => C:\Windows [SERVER_SIGNATURE] => [SERVER_SOFTWARE] => Apache/2.4.16 (Win32) OpenSSL/1.0.2d PHP/5.5.14 [SERVER_NAME] => clever-coffee.net [SERVER_ADDR] => 127.0.0.1 [SERVER_PORT] => 80 [REMOTE_ADDR] => 127.0.0.1 [DOCUMENT_ROOT] => C:/vhosts/clever-coffee.net [REQUEST_SCHEME] => http [CONTEXT_PREFIX] => [CONTEXT_DOCUMENT_ROOT] => C:/vhosts/clever-coffee.net [SERVER_ADMIN] => admin@clever-coffee.net [SCRIPT_FILENAME] => C:/vhosts/clever-coffee.net/html/admin/add_inventory.php [REMOTE_PORT] => 58816 [REMOTE_USER] => vmielke [AUTH_TYPE] => Basic [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => GET [QUERY_STRING] => [REQUEST_URI] => /html/admin/add_inventory.php [SCRIPT_NAME] => /html/admin/add_inventory.php [PHP_SELF] => /html/admin/add_inventory.php [PHP_AUTH_USER] => vmielke [PHP_AUTH_PW] => password [REQUEST_TIME_FLOAT] => 1441830236.003 [REQUEST_TIME] => 1441830236 ) [connect] => mysqli Object ( [affected_rows] => -1 [client_info] => mysqlnd 5.0.11-dev - 20120503 - $Id: bf9ad53b11c9a57efdb1057292d73b928b8c5c77 $ [client_version] => 50011 [connect_errno] => 0 [connect_error] => [errno] => 1054 [error] => Unknown column 'sc.size' in 'order clause' [error_list] => Array ( [0] => Array ( [errno] => 1054 [sqlstate] => 42S22 [error] => Unknown column 'sc.size' in 'order clause' ) ) [field_count] => 0 [host_info] => 127.0.0.1 via TCP/IP [info] => [insert_id] => 0 [server_info] => 5.5.5-10.0.17-MariaDB [server_version] => 50505 [stat] => Uptime: 116256 Threads: 1 Questions: 1928 Slow queries: 0 Opens: 25 Flush tables: 1 Open tables: 88 Queries per second avg: 0.016 [sqlstate] => 00000 [protocol_version] => 10 [thread_id] => 375 [warning_count] => 0 ) [page_title] => Add Inventory [message] => [affected] => 0 [_SESSION] => Array ( ) [query3] => (SELECT CONCAT("G", ncp.id) AS sku, ncc.category, ncp.name, FORMAT(ncp.price/100, 2) AS price, ncp.stock FROM non_coffee_products AS ncp INNER JOIN non_coffee_categories AS ncc ON ncc.id=ncp.non_coffee_category_id ORDER BY category, name) UNION (SELECT CONCAT("C", sc.id),gc.category, CONCAT_WS(" - ", s.size, sc.caf_decaf, sc.ground_whole), FORMAT(sc.price/100, 2), sc.stockFROM specific_coffees AS sc INNER JOIN sizes AS s ON s.id=sc.size_id INNER JOIN general_coffees AS gcON gc.id=sc.general_coffee_id ORDER BY sc.general_coffee_id, sc.size, sc.caf_decaf, sc.ground_whole) [result] => ) ) ) [1] => Array ( [file] => C:\vhosts\clever-coffee.net\html\admin\add_inventory.php [line] => 94 [function] => mysqli_fetch_array [args] => Array ( [0] => [1] => 1 ) ))
  6. Good to be here people. I am not being able to insert my first tasks. Is this a suprise? The error in my logs says: mysqli_fetch_array() /Applications/MAMP/htdocs/myphp/databases/add_tasks.php:64 I have really looked everywhere that I can; no joy. Can someone please help me
  7. I am using a live site and the error message shouldn't be displayed on my website but it is. I don't know why. The error message it shows online is Could not connect to MySQL: Access denied for user 'moreaw32_grah2'@'localhost' (using password: YES) . When other errors occur on my site it does not show the detailed message. I don't want it to show the details of my database like my user name which it does show. Here is the line of code in my connection script. $dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error()) What can I do to prevent this.
  8. Hi Larray and all, I have edited this script to fit my project, which I cut off the first name and last name. I added the username field which looks like this: <form action="" method="post"> <fieldset> <legend>Sign Up </legend> <label>Choose a username</label> <input type="text" name="username" size="20" maxlength="20" value=" <?php if (isset($trimmed['username'])) echo $trimmed['username']; ?>" /> <label>Email</label> <input type = "text" name="email" size="30" maxlength="60" value ="<?php if(isset($trimmed['email'])) echo $trimmed['email']; ?>" /> <label>Select a password</label> <input type="password" name="password1" size="20" maxlength="20" value="<?php if(isset($trimmed['password1'])) echo $trimmed['password1']; ?>" /> <label>Confirm password</label> <input type="password" name="password2" size="20" maxlength="20" value="<?php if(isset($trimmed['password2'])) echo $trimmed['password2']; ?>" /> <input type = "submit" name="submit" value="Sign Up "/> </fieldset> </form> I followed the script 18.6 strickly, plus do the username validation like this (of course, I also initiate the $errors = array(); too: //validate the username if (preg_match('/^\w\S{2,20}$/', $trimmed['username']) ) { $u = mysqli_escape_string($dbc, $trimmed['username']); } else { $errors[] = 'Please enter a username'; } Assume that other variable validations are okay. I code like this: if($u && $e && $p){//OK // Check for unique username and email $q = "SELECT user_id from users where username='$u' AND email='$e'"; $r = mysqli_query($dbc, $q) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $q"); if(mysqli_num_rows($r) == 0 ){ // Create the activation code $a = md5(uniqid(rand(), TRUE)); //Defined variable for language ID $l = $_SESSION['lid']; //retrieved already in the header //Insert into database, table users $q = " INSERT INTO users (lang_id, username, pass, email, active, registration_date) VALUES ('$l','$u', SHA1('$p'), '$e', '$a', NOW() ) "; $r = mysqli_query($dbc, $q) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $q"); if (mysqli_affected_rows($dbc) == 1) { // everything's ok //Send the email: $body = "Thank you for your registration at askpro.com. To activate your account, please click on the link below \n\n"; $body .= BASE_URL. 'activate.php?e='.urlencode($e). "&a=$a"; mail($trimmed['email'], 'Registration Confirmation', $body, 'From: info@website.com'); //Finish the page echo '<h3>Thank you for registering! A confirmation email has been sent to your address. Please click on the link in that email in order to activate your account.</h3>'; include ('includes/footer.html'); // Include the HTML footer. exit(); // Stop the page. } else { $errors[]='You could not be registered due to a system error. We apologize for any inconvenience.'; } }else{ $errors[] = 'either the username or email has already been registered. If you have forgotten your password, use the link above to have your password sent to you.</'; } }else { // If one of the data tests failed. echo 'Error:<br />'; foreach ($errors as $msg) { // Print each error. echo "- $msg <br />"; } $error[] = 'Please try again'; } } The question is that: -/ When I enter value and click the 'sign up' button with the intention that I enter a duplicate email, i.e., email@website.com, it returned error like this: MySQL error: Duplicate entry 'email@website.com ' for key 3 --------------------------------------------------------- Query: SELECT user_id FROM users WHERE (username = 'dsfdsf' AND email = 'e') -/ Then I change the query to: $q = "SELECT user_id from users where username='$u' OR email='$e'"; It returns NO error, but it does not insert anything into the database, and no 'thank you message' is printed. Can you help me to figure this out? Am I doing anything wrong? Thank you. P/S: This is my users table:
  9. I am writing a little script to read files in a folder (photos) returning an array of file name and file size. Can mysqli handle a prepared statement inserting an array? Would be nice to insert 500 photo names at once rather than typing them all in. Ps.. Not for a public site, just a script i run on a home server to build a site. Tx
  10. In this example why does the procedural way fail with this error: Error: Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given in /Users/joel/Sites/people_test/public_html/index.php on line 14 PHP: $dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() ); $q = "SELECT first_name, last_name FROM person LIMIT 0,30"; $r = mysqli_query($dbc, $q); Procedural: while($data = mysql_fetch_assoc($r)) { $rows[] = $data; } //prints out null echo json_encode($rows); OOP: while($data = $r->fetch_assoc()) { $rows[] = $data; } echo json_encode($rows); I thought I was doing the procedural way right from reading the PHP.net fetch_assoc() procedural and oop examples. Obviously I'm missing something. Could use some help seeing what it is.
  11. SOLVED for solution see the last part of my first post _______________________________________________________________________ hi , i read chapter 3 and try to pass session_set_save_handler with an object, here's the code for my session handler class: <?php class MySessionHandler implements SessionHandlerInterface { protected $conn = NULL; public function open($savePath, $sessionName) { if(is_null($this->conn)) { $dsn = 'mysql:host=localhost;dbname=php_advanced'; $username = 'root'; $password = 'password'; try { $this->conn = new PDO($dsn, $username, $password); $this->conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { $this->conn = NULL; die('error in open function ' . $e->getMessage()); } } return TRUE; } public function close() { echo '<p>close</p>'; $this->conn = NULL; return TRUE; } public function read($id) { echo '<p>read</p>'; $query = 'SELECT data FROM session_table WHERE session_id = :id'; try { $pdo = $this->conn->prepare($query); $pdo->bindValue(':id', $id); $pdo->execute(); // Kalo query berhasil nemuin id.. if($pdo->rowCount() == 1) { list($sessionData) = $pdo->fetch(); return $sessionData; } return FALSE; } catch(PDOException $e) { $this->conn = NULL; die('error in read function => ' . $e->getMessage()); } } public function write($id, $data) { echo '<p>write</p>'; $query = 'REPLACE INTO session_table(session_id, data) VALUES(:id, :data)'; try { $pdo = $this->conn->prepare($query); $pdo->bindValue(':id', $id); $pdo->bindValue(':data', $data); $pdo->execute(); // return the value whether its success or not return (bool)$pdo->rowCount(); } catch(PDOException $e) { $this->conn = NULL; die('error in write function => ' . $e->getMessage()); } } public function destroy($id) { echo '<p>destroy</p>'; $query = 'DELETE FROM session_table WHERE session_id = :id LIMIT 1'; try { $pdo = $this->conn->prepare($query); $pdo->bindValue(':id', $id); $pdo->execute(); $_SESSION = array(); return (bool)$pdo->rowCount(); } catch(PDOException $e) { $this->conn = NULL; die('error in destroy function => ' . $e->getMessage()); } } public function gc($maxLifeTime) { echo '<p>garbage collection</p>'; $query = 'DELETE FROM session_table WHERE DATE_ADD(last_accessed INTERVAL :time SECOND) < NOW()'; try { $pdo = $this->conn->prepare($query); $pdo->bindValue(':time', $maxLifeTime); $pdo->execute(); return TRUE; } catch(PDOException $e) { $this->conn = NULL; die('error in gc function => ' . $e->getMessage()); } } } $SessionHandler = new MySessionHandler(); session_set_save_handler($SessionHandler); session_name('my_session'); session_start(); i remove the session_write_close on purpose. This probably sounds stupid, but i want to get the session error to learn more.. here's session script(using Larry's code): <?php require('session_class.php'); ?><!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>DB Session Test</title> <link rel="stylesheet" href="style.css"> </head> <body> <?php // Store some dummy data in the session, if no data is present: if (empty($_SESSION)) { $_SESSION['blah'] = 'umlaut'; $_SESSION['this'] = 3615684.45; $_SESSION['that'] = 'blue'; // Print a message indicating what's going on: echo '<p>Session data stored.</p>'; } else { // Print the already-stored data: echo '<p>Session Data Exists:<pre>' . print_r($_SESSION, 1) . '</pre></p>'; } // Log the user out, if applicable: if (isset($_GET['logout'])) { session_destroy(); echo '<p>Session destroyed.</p>'; } else { // Otherwise, print the "Log Out" link: echo '<a href="session_link.php?logout=true">Log Out</a>'; } // Reprint the session data: echo '<p>Session Data:<pre>' . print_r($_SESSION, 1) . '</pre></p>'; // Complete the page: echo '</body> </html>'; // Write and close the session: // session_write_close <<<<<--- I REMOVE THIS ON PURPOSE TO GET ERROR ?> but i dont get any error, then i try to use Larry's mysqli script to connect db and it produces error.. can anyone explain why if im using PDO it doesn't generate error? i'm even dont use register_shutdown_function('session_write_close'); in my session class destructor (on purpose) NOTE : I'm doing this on purpose because i want to learn more. the error im expecting is like when im using mysqli connection(connection closed by php at the end of script then session try to write and close but no connection available) : Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 66 Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 66 Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 67 Warning: mysqli_close() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 33 UPDATE i just tried to pass session_set_save_handler with function callback(using pdo as connection) and it produces error i expected, but still if using MySessionHandler class it doesn't produce any error. The codes in the MySessionHandler class is similar with my new session handler functions. here's the script <?php $conn = NULL; function open_session() { echo '<p>open session</p>'; global $conn; $_dsn = 'mysql:host=localhost;dbname=php_advanced'; $_username = 'root'; $_password = 'monyetsahur'; $conn = new PDO($_dsn, $_username, $_password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return TRUE; } function close_session() { echo '<p>close session</p>'; global $conn; $conn = NULL; return TRUE; } function read_session($sid) { echo '<p>read session</p>'; global $conn; $query = 'SELECT data FROM session_table WHERE session_id = :sid'; $pdo = $conn->prepare($query); $pdo->bindValue(':sid', $sid, PDO::PARAM_STR); $pdo->execute(); if($pdo->rowCount() == 1) { list($session_data) = $pdo->fetch(); echo '<pre>'; print_r($session_data); echo '</pre>'; return $session_data; } else { return ''; } } function write_session($sid, $data) { echo '<p>write session</p>'; global $conn; $query = 'REPLACE INTO session_table(session_id, data) VALUES(:sid, :data)'; $pdo = $conn->prepare($query); $pdo->bindValue(':sid', $sid, PDO::PARAM_STR); $pdo->bindValue(':data', $data, PDO::PARAM_STR); $pdo->execute(); return (bool)$pdo->rowCount(); } function destroy_session($sid) { echo '<p>destroy session </p>'; global $conn; $query = 'DELETE FROM session_table WHERE session_id = :sid'; $pdo = $conn->prepare($query); $pdo->bindValue(':sid', $sid, PDO::PARAM_STR); $pdo->execute(); // clean the session array; $_SESSION = array(); return TRUE } function clean_session($expire) { echo '<p>clean session</p>'; global $conn; $query = 'DELETE FROM session_table WHERE DATE_ADD(last_accessed, INTERVAL :expire SECOND) < NOW()'; $pdo = $conn->prepare($query); $pdo->bindValue(':expire', $expire, PDO::PARAM_INT); $pdo->execute(); return $pdo->rowCount(); } session_set_save_handler('open_session', 'close_session', 'read_session', 'write_session', 'destroy_session', 'clean_session'); session_name('my_session'); session_start(); SOLVED: SOLVED sorry guys my mistake actually its a pretty easy answer why MySessionHandler class doesnt produce error wihtout session_write_close() in the end of script, session_set_save_handler() by default will register session_write_close() to register_shutdown_function() so if u want to make your own shutdown function for session then use : session_set_save_handler($SessionClass, FALSE) if u do this then u must provide session_write_close() in your class destructor source : http://php.net/manual/en/function.session-set-save-handler.php thanks for the tips and your attention
  12. Hi Larry I found your book in my pursue for learning more about PHP. I learn procedural programming with PHP and PDO for Database related operations from the first book I bought. With your book I see you are using mysqli and you cover PDO in chapter 8. I know that: 1. Mysqli provides database specific functions. 2. PDO is an abstraction layer, which means you can easily use your database functions no matter which database you are using. 3. If you go to the OOP rute then PDO is the standard for database functions. I know that there are more things, but to make a long story short, for a beginner...who's making his way into PHP and as a starting point with 5.3 flavor and up . * Should I stick to PDO? * Is mandatory to learn mysqli too? I wish you would have used PDO from a very begining in your book. Still have a lot to learn and assimilate. Apart from that...thanks and you got a new reader Víctor
  13. I have been seeing more and more 'mysqli' stuff around instead of 'mysql' commands. I finally searched it and came up with that it is 'improved'. I did not feel the need to know much more after reading that 'mysql' would be deprecated by the release of PHP 6, so I looked into converting to 'mysqli'. In a simple search, I found this converter tool on a wiki page by mysql.com: http://forge.mysql.com/wiki/Converting_to_MySQLi. I backed up one of my directories and tested it locally. I was given this list of results of which files it altered, how many mysql_* functions were found, etc. (what I find ironic is that I put the converter in the directory I converted, and I got only warnings for files in that directory). Anyways, when I went to see how my scripts ran on Firefox, they turned out identical. However, as I check the source, I have yet to find an actual adjustment. Did this 'converter tool' work? How should I convert to mysqli? Thank you in advance, Lingolatz
  14. Hey all, First time poster, several time owner (my bookshelf sags under the VisualQuickPro section) Trying to port over some code from mysql to mysqli, but ran into a snag (actually I just can't get my head around it...) I am used to, on an "includes()" function file (functions.inc), including my db connection scripts and several db related functions. For example, I have a section at the beginning of the functions.inc file: (note the code here is stripped and cleaned to be clearer) $connect = mysql_connect($tbl_hostname, $tbl_username, $tbl_password) ; $selectdb = mysql_select_db($tbl_database, $connect) ; Further down I call a function: function user_exists($user) { $total = mysql_query("SELECT COUNT(`user_id`) FROM `user` WHERE `user_name` = '{$user}'"); return (mysql_result($total, 0) == '1') ? true : false; } and it worked fine, however when I try to use mysqli I run into problems. Re-working the functions.inc file it now includes: $connect = mysqli_connect('localhost', 'root', 'password', 'users_db') ; and the function looks like: function user_exists($user) { $total = mysqli_query($connect, "SELECT COUNT(`user_id`) FROM `user` WHERE `user_name` = '{$user}'"); $row= mysqli_fetch_array($total); return ($row['COUNT(`user_id`)'] == '1') ? true : false; } But I keep getting a "Undefined variable: connect in the file... etc, etc" My question (to which I couldn't find a clear answer) - Do I need to include the database connector line inside every function calling to the db? function user_exists($user) { $connect = mysqli_connect('localhost', 'root', 'password', 'users_db'); $total = mysqli_query($connect, "SELECT COUNT(`user_id`) FROM `user` WHERE `user_name` = '{$user}'"); $row= mysqli_fetch_array($total); return ($row['COUNT(`user_id`)'] == '1') ? true : false; } Thanks for any pointers. -t
×
×
  • Create New...