Jump to content

Search the Community

Showing results for tags 'pdo'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Hi I have one problem , I need to search any string data . Below my code. When I click, no results as well as no error Index.php <?php include_once '../templete/header.php'; ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Search</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <form action="search.php" method="get" > <table border="0" cellpadding="0" cellspacing="0"> <tr> <td><input type="text" name="query" id="text" /> </td> <td><input type="submit" name="submit" id="search" value="Search" /></td> </form> </body> </html> Search.php <?php include_once '../templete/header.php'; include_once '../inc/connection.inc.php'; ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Search</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <table> <tr> <td>Name</td> <td>Address</td> </tr> <?php $query = $_GET['query']; $stmt = $dbh->prepare("SELECT * FROM CompanyInfo WHERE (Name LIKE '%".$query."%') OR (Address LIKE '%".$query."%')"); $stmt->setFetchMode(PDO::FETCH_ASSOC); //$stmt->execute(); if(isset($stmt)) { while($row = $stmt->fetch()); ?> <tr> <td><?php echo $row['Name'];?></td> <td><?php echo $row['Address'];?></td> </tr> <?php } ?> </table> </body> </html> Pls help me Maideen
  2. Hello, I've followed the whole series of Log in and registration system on the phpacademy channel on Youtube: http://www.youtube.com/playlist?list=PLE134D877783367C7 After reading some comments and doing some research I found that it uses md5 and old mysql_ function, which for some reason are 'deprecated' or not secure. I'm still not sure. Also, after doing some searching I came across: http://www.sunnytuts.com/article/login-and-registration-with-object-oriented-php-and-pdo which is another tutorial that is quite similar to the one on phpacademy, but it uses PDO and Object oriented programming and bcrypt instead of md5(). The problem is that I don't know OOP and I use procedural programming. So is it worth learning OOP and using bcrypt() instead of md5() or PDO instead of mysql? I mean, am I ok with using the code from phpacademy, or do I need to follow the other one and also learn OOP. Thank you very much.
  3. if i delete this code everything works $number_of_rows = $completed_offer_stmt->fetch(PDO::FETCH_COLUMN); if (!$number_of_rows){ print "No results"; } $query_1 = "SELECT * FROM offer_pending WHERE status = 1 ORDER BY date_modified DESC LIMIT 10"; $completed_offer_stmt = $dbh->prepare($query_1); $completed_offer_stmt->execute(); $number_of_rows = $completed_offer_stmt->fetch(PDO::FETCH_COLUMN); if (!$number_of_rows){ print "No results"; } while($completed_offer = $completed_offer_stmt->fetch(PDO::FETCH_ASSOC)){ $query_2 = "SELECT * FROM offers WHERE id= :completed_offer_id"; $offers_stmt = $dbh->prepare($query_2); $offers_stmt->bindParam(':completed_offer_id', $completed_offer['offer_id']); $offers_stmt->execute(); $offers = $offers_stmt->fetch(PDO::FETCH_ASSOC); print "{$offers['name']} {$offers['points']}"; }
  4. if (isset($_POST[''.$row['id'].'']) === true) { $query = "SELECT did, check FROM admin_flag WHERE did = ? AND check = 1"; $stmt = $db->prepare($query); $stmt->bindValue(1, $row['id']); $stmt->execute(); if ($stmt->rowCount() < 1) { $query2 = "UPDATE users SET user_flag = user_flag - 1 WHERE username = ?"; $stmt2 = $db->prepare($query2); $stmt2->bindValue(1, $row['user']); $stmt2->execute(); if ($stmt2->rowCount() > 0) { $query1 = "INSERT INTO admin_flag (did, check) VALUES (?, 1)"; $stmt1 = $db->prepare($query1); $stmt1->bindValue(1, $row['id']); $stmt1->execute(); if ($stmt1->rowCount() < 1) { echo 'Insert Inactive.'; } } else { echo 'Update Flag inactive.'; } //header('Location: view_all_cancels.php'); } else { echo 'User flag already removed for this trade.'; } } Briefly, In the admin side of things, if a host cancels a trade, the user is flagged. I can then remove a user flag via this button. BUT when I run it, it doesn't check the database correctly for a row count on the first query, secondly then it doesn't insert the values on the third query. Even though when I am testing it it should get to that else. Any help?
  5. I've been trying to improve my php skills by reading and going through the examples (step by step in order) from the book "PHP Advanced and Object-Oriented Programming". I'll try to explain it the best that I can the problem I have followed with some code. I think I'll will start with code: I have to grab the data for after all it's an edit page: <?php # edit_page // This page both displays and handles the "edit the page" form. // Need the utilities file: require('includes/utilities.inc.php'); try { // Validate the page ID: if (!isset($_GET['id']) || !filter_var($_GET['id'], FILTER_VALIDATE_INT, array('min_range' => 1))) { throw new Exception('An invalid page ID was provided to this page.'); } // Fetch the page from the database: $query = 'SELECT id, title, content, DATE_FORMAT(dateUpdated, "%e %M %Y") as dateUpdated FROM pages WHERE id=:id'; $stmt = $pdo->prepare($query); $result = $stmt->execute(array(':id' => $_GET['id'])); // If the query ran OK, fetch the record into an object: if($result) { $stmt->setFetchMode(PDO::FETCH_CLASS, 'Page'); $page = $stmt->fetch(); } else { throw new Exception('An invalid page ID was provided to this page'); } } catch(Exception $e) { // catch generic Exceptions $pageTitle = 'Error!'; include('includes/header.inc.php'); include('views/error.html'); } Then I have to setup my Quickform2 form // Creat a new QuickForm2 form: // set_include_path(get_include_path() . PATH_SEPARATOR . '/usr/local/pear/share/pear/'); require('HTML/QuickForm2.php'); $form = new HTML_QuickForm2('editPageForm' ); // Add the title field: $title = $form->addElement('text', 'title'); $title->setLabel('Page Title'); $title->addFilter('strip_tags'); //$title->addRule('required', 'Please enter a page title'); // Add the content field: $content = $form->addElement('textarea', 'content'); $content->setLabel('Page Content'); $content->addFilter('strip_tags'); $content->addFilter('trim'); //$content->addRule('required', 'Please enter the page content'); // Set defaults for the form elements $form->addDataSource(new HTML_QuickForm2_DataSource_Array(array( 'title' => $page->getTitle(), 'content' => $page->getContent() ))); // Add the submit button: $submit = $form->addElement('submit', 'submit', array('value' => 'Edit This Page')); and then I have to validate and submit the edited data to the database (This is where I run into problems) // Check for a form submission: if (!isset($_SERVER) && $_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form submission // Validate the form data: if ($form->validate()) { $query = 'UPDATE pages SET creatorId=:creatorId, title=:title, content=:content, dateUpdated=NOW() WHERE id=:id'; // Insert into the database: //$query = 'INSERT INTO pages (creatorId, title, content, dateAdded) VALUES (:creatorId, :title, :content, NOW())'; $stmt = $pdo->prepare($query); $result = $stmt->execute(array(':creatorId' => $user->getId(), ':title' => $title->getValue(), ':content' => $content->getValue(), ':id' => $page->getId())); // Freeze the form upon success: if ($result) { $form->toggleFrozen(true); $form->removeChild($submit); } } // End of form validation IF. } // End of form submission IF. This is the error it gives: Details (not for public consumption): An invalid page ID was provided to this page. Notice: Undefined variable: page in C:\xampp\htdocs\php_test\chapter-09-CMS-with-OOP\edit_page.php on line 56 Fatal error: Call to a member function getTitle() on a non-object in C:\xampp\htdocs\php_test\chapter-09-CMS-with-OOP\edit_page.php on line 56 I think it might have something to do with the url being different (edit_page.php?id=5) vs (edit_page.php) when it kicks out the error. I don't know if I have my query right or the POST right or what have you. This is the first time I really have been using PDO for previously I've been using mysqli to go back and forth to the MySQL database. I believe I have it right? Anyways, I apologize if I didn't make myself clear and I can always reply with more information if needed. I have gone to the author's forums, check the Quckform2 documentation, php.net manual and have done a bunch of Google searches to no avail to fix the problem. Well at least I know now how to catch an error, but now the thing is how to fix them. Thanks, John
  6. Here's what I've currently got. $query = "SELECT * FROM deposits WHERE completed = 5 AND host = ? ORDER BY id DESC LIMIT 10"; $stmt = $db->prepare($query); $stmt->bindValue(1, $user_data['username']); $stmt->execute(); $fetchmethod = $stmt->fetch(PDO::FETCH_ASSOC); /*$query1 = "SELECT * FROM users WHERE username = ?"; $stmt1 = $db->prepare($query1); $stmt1->bindValue(1, $fetchmethod['user']); $stmt1->execute(); $fetch = $stmt1->fetch(PDO::FETCH_ASSOC); */ That was before the while loop, hence I've ruled out which I need to include with the first query as if I don't, then the following loop only lists 'one' item. echo '<table>'; while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { /* if ($row['method'] == "RS07") { $coins = $fetch['coins']; } else if ($row['method'] == "EOC") { $coins = $fetch['eoc_coins']; } */ echo '<tr> <td><font size="2" color="black">| ID: '.$row['id'].' |'.$row['user'].' | '.$row['method'].' | Deposit: '.$row['value'].'<font size="1">M/Gp</font> | Now has '.$coins.'<font size="1">M/Gp</font> |</font></td> </tr>'; } echo '</table><br/><br/><br/><br/>'; I need to combine these tables, so I can use an array in the echo'd table to be able to provide which type of coins are being used with the method, and relay that users current coins with the method.
  7. Hi, im still in the early learning stages, banging my head against walls looking for clues. Iv been reading the manual to no avail. im building a user log in system based on the phpAcadamy tutorial 'Register & Login'. They use mysql_connect in the tutorial, but I am using a PDO connection to mysql. 1) the function user_id_from_username should return the `user_id` entry for the posted $username. mine does not, im confused about how to simply return the entry, and i just need a little bit of guidance and explanation. 2) the login function works, BUT i need it to return $user_id if TRUE, so that i can set the session. here is my code: function user_id_from_username(PDO $db, $username) { $stmt = $db->prepare('SELECT `user_id` FROM `users` WHERE `username` = 1'); $stmt->bindParam(1, $username); $stmt->execute(); return ($stmt->fetchColumn()); } //??? I NEED THIS FUNCTION TO RETURN THE `user_id` ENTRY FOR $username function login(PDO $db, $username, $password) { $user_id = user_id_from_username($db, $username); $password = md5($password); $stmt = $db->prepare('SELECT COUNT(`user_id`) FROM `users` WHERE `username` = ? AND `password` = ?'); $stmt->bindParam(1, $username); $stmt->bindParam(2, $password); $stmt->execute(); return (bool) $stmt->fetchColumn(); } //??? I NEED THIS FUNCTION TO RETURN $user_id IF TRUE (to set session) //---------------------login.php----------------------- if (empty($_POST) === false) { $username = $_POST['username']; $password = $_POST['password']; if (empty($username) === true || empty($password) === true) { $errors[] = 'You need to enter a username and password.'; } else if (user_exists($db, $username) === false) { $errors[] = 'We can\'t find that username. Have you registered?'; } else if (user_active($db, $username) === false) { $errors[] = 'You haven\'t activated your account!'; } else { $login = login($db, $username, $password); if ($login === false) { $errors[] = 'That username/password combination is incorrect.'; } else { die($login); } } print_r($errors); } So, according to this login script, after a successful login (good username and password, and active account) it should output the $user_id integer: "die($login)". It prints the error array correctly, it logs in ok, except for this next step. Thanks in advance!
  8. Hello, I just came across a problem... This if my first post on this website since I just found out about it. Hopefully I could get some help from here since you seem to be the real deal and uses PDO! I want to echo out the title, category & content from database. I know how to do this, but not how to make them editable for me. Hard to explain but this is an example: (This is how it looks now when I'm echoing out the title,category & content using a while loop.) TitleCategoryContent (I want them to appear like this so I can fix them up to look nice in a container) Title Category Content here Here's my code http://pastebin.com/Lg5YebgZ Thanks in advanced
  9. This is my first time converting code in php. I really have no idea what I'm doing and can't tell if i'm doing it right or not. I would appreciate it very much if you could help me. Thanks! From process_new_user.php mysqli if ($insert_stmt = $mysqli-> prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) { $insert_stmt-> bind_param('ssss', $username, $email, $password, $random_salt); $insert_stmt-> execute(); // Execute the prepared query. echo "<script>"; echo "alert(\"New User Successfully Added!\");"; echo "window.location = \"users.php#current_user\";"; echo "</script>"; } else { echo "alert(\"Uh Oh! Something went terribly wrong.\");"; echo "</script>"; } pdo (attempt) if ($params = array(':username' => $username, ':email' => $email, ':password' => $password, ':random_salt' => $random_salt); $insert_stmt->prepare("INSERT INTO members (username, email, password, salt) VALUES (:username, :email, :password, :random_salt)")) { $insert_stmt-> execute($params); // Execute the prepared query. echo "<script>"; echo "alert(\"New User Successfully Added!\");"; echo "window.location = \"users.php#current_user\";"; echo "</script>"; } else { echo "alert(\"Uh Oh! Something went terribly wrong.\");"; echo "</script>"; } from process_delete_user.php (i converted as much of this as i could. But the last part I have no idea.) original mysqli foreach($id as $check) { $conn = new mysqli(host, user, password, database); if($conn == false){ echo "connection has failed"; } $sql=("DELETE FROM $table WHERE id ='$check'"); $res=mysqli_query($conn, $sql); if($res == true){ echo "<script>"; echo "alert(\"User Successfully Deleted!\");"; echo "window.location = \"users.php#delete_user\";"; echo "</script>"; } else { echo "<script>"; echo "DELETE failed".mysqli_error($conn); // echo "window.location = \"users.php#delete_user\";"; echo "</script>"; } mysqli_close ($conn); } PDO (attempt) foreach($id as $check) { $conn = new PDO(host, database, user, password); if($conn == false){ echo "connection has failed"; } $sql->prepare("DELETE FROM :table WHERE id = :check"); $sql->exectute(array(':username' => $table, ':check' => $check); $res=mysqli_query($conn, $sql); if($res == true){ echo "<script>"; echo "alert(\"User Successfully Deleted!\");"; echo "window.location = \"users.php#delete_user\";"; echo "</script>"; } else { echo "<script>"; echo "DELETE failed".mysqli_error($conn); // echo "window.location = \"users.php#delete_user\";"; echo "</script>"; } mysqli_close ($conn); }
  10. Today, I decided to stop with mysqli, and change to PDO. I'm reading this tutorial. Here's my full code: <?php class User { public $username; protected $db; protected $user; public function __construct($db) { $this->db = $db; try { $this->db; echo "Connected to the database."; } catch(PDOException $e) { echo $e->getMessage(); } } } $pdo = new PDO("mysql:host=localhost;dbname=dbdaev", "root", ""); $pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $user = new User($pdo); The error: Expected result: The database is actually named dbdev, not dbdaev, but I wanted to try the try{} catch{}. Why doesn't it show the expected result?
  11. I am tring to learn about PDO people have said its easy and the best way to interact with the database, but im not finding it easy. can any help? Should i have my connection in its own class and extend it to the rest of my classes or should i use a global variable to connect? or is there another way better? i read up about the try and catch method not very good either. my database is mysql
  12. Hey all, I'm just starting to get on the PDO bandwagon with PHP. One thing I do a lot is to fetch the result of a query straight into a variable using list. Something like list($name) = mysql_fetch_row(mysql_query("SELECT name FROM names WHERE userID='1'")); Is there a similar thing I can do with PDO rather than having to loop through with a while or similar. Thanks in advance.
  13. This is mysql code im trying to run: SELECT i.id, i.courseid, i.title, i.info, i.lasteditedby, u.id, u.forename, u.surname FROM courseinformation as i JOIN users AS u ON (i.lasteditedby = u.id) WHERE i.courseid = :courseid ORDER BY i.id desc LIMIT 2; Im getting this error : /* SQL Error (1064): 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 ':courseid ORDER BY i.id desc LIMIT 2' at line 1 */ My aim is to get id, courseid, title, info, lasteditedby from CourseInformation table, and then Id, forename and surname from user table. Where the userid is the same as lasteditedby. I really can't see what sql syntax is wrong as i've used :courseid in other pdo sql querys that ive run for reference, this is my php code with that sql in $courseid = 'G11111'; $sql = "SELECT i.id, i.courseid, i.title, i.info, i.lasteditedby, u.id, u.forename, u.surname FROM courseinformation as i JOIN users AS u ON (i.lasteditedby = u.id) WHERE i.courseid = :courseid ORDER BY i.id desc LIMIT 2"; $sql->bindParam(":courseid", $courseid); $sql->execute(); foreach ($db->query($sql) as $row) { echo '<div class="announceTitle">'; echo $row['title'].'<br />'; echo $row['forename'].' '.$row['surname'].'<br />'; echo '</div> <div class="announceText">'; echo $row['info']; echo '</div> <br /> <br />'; } Could anyone please point me in the direction as to what is wrong? Thanks for reading
  14. this is the code with bind_result: function getUserDetails($username=NULL, $id=NULL) { if($username!=NULL) { $column = "user_name"; $data = $username; } elseif($id!=NULL) { $column = "id"; $data = $id; } global $db; $query = $db->prepare("SELECT id, username, permissions, forename, surname, password, email, courseid, choiceid, lastlogin, active FROM users WHERE $column = :column"); $query->bindParam(":column", $data); $query->execute(); $query->bind_result ($id, $username, $permissions, $forename, $surname, $password, $email, $courseid, $choiceid, $lastlogin, $active); while ($query->fetch()){ $row = array('id' => $id, 'userlevel' => $permissions, 'username' => $username, 'forename' => $forename, 'surname' => $surname, 'password' => $password, 'email' => $email, 'courseId' => $courseid, 'choiceId' => $choiceId, 'lastlogin' => $lastlogin, 'active'=> $active); } return ($row); } I've been trying to convert this to work with PDO, as I've found out that PDO doesnt support bind_result. I've read arround about using fetch assoc but im not entirely sure how to implement it I've tried this: function getUserDetails($username=NULL,$id=NULL) { if($username!=NULL) { $column = "user_name"; $data = $username; } elseif($id!=NULL) { $column = "id"; $data = $id; } global $db; $query = $db->prepare("SELECT id, username, permissions, forename, surname, password, email, courseid, choiceid, lastlogin, active FROM users WHERE $column = :column"); $query->bindParam(":column", $data); $query->execute(); $results = array(); while ($row = $query->fetch(PDO::FETCH_ASSOC)) { $results[] = $row; } return ($results); } This is a sample of how im trying to use the code $username = '123'; $userdetails = getUserDetails($username); echo $userdetails['surname']; Could anyone please give me a poke in the direction I should be going? I have searched around but I'm just getting more confused.
  15. [edit] i believe ive posted this in the wrong section D: please could a mod delete or move it! thanks! ----------------------- Hi Im trying to get : - title, newstext, authorId from indexNews - id, forename, surname from users where authorId is id im using pdo, which is where im stuck here is what I've done so far : try { $sql = "SELECT i.title, i.newstext, i.authorId, u.id, u.forename, u.surname FROM indexNews as i JOIN users AS u ON (i.authorId = u.id)"; //$sql = "SELECT * FROM indexNews"; foreach ($db->query($sql) as $row) { echo '<div class="announceTitle">'; echo $row['i.title'] .' - '. $row['i.authorId'] . '<br />'; echo $row['u.surname'].' '.$row['u.forename'].'<br />'; echo '</div> <div class="announceText">'; echo $row['i.newstext']; echo '</div> <br /> <br />'; } } catch(PDOException $e) { echo $e->getMessage(); } when i run this i get : line 100 is echo $row['i.title'] .' - '. $row['i.authorId'] . '<br />'; i think that the issue might be with the array? but i'm not sure. I've tried googling and have been looking for a tutorial, but haven't found an answer. could anyone give me some hints as to where i'm going wrong? Thanks for your time
  16. Hey I have a simple articles table with IDs. I want to get the highest and lowest ids from the latest 10 results. For example, if there are 11 ids, the result should be 2 and 11 and if there are 4 ids, should be 4 and 1 and so on. I use PHP PDO statements. $aid = $DBH->prepare("SELECT id FROM articles ORDER BY id DESC LIMIT 10"); $aid->execute(); $row = $aid->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST); $lowest_article_id = $row[0]; $row = $aid->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_FIRST); $highest_article_id = $row[0]; The above will always return 11 if there are 11 records and 10 if there are 10 records. So, the query ignores the PDO::FETCH_ORI_LAST and PDO::FETCH_ORI_FIRST part of the query. Thanks
  17. How can I tell if a given installation has PDO installed? I'm using a hosting service and they have PHP 5.3.19 but I suspect they don't have PDO. I'm just not sure how to tell if it is there. I'm new to php but not to database work. I was trying to perfect some mysql_query code when I stumbled on the existence of PDO, which is apparently the preferred method of doing database access these days. I had a look at the PDO tutorial and found it very familiar. I reworked one of my programs to use PDO but now that I'm executing it for the first time, I'm getting an error message that makes me think PDO isn't installed because it doesn't comprehend the -> operator. Here's the error message: Parse error: syntax error, unexpected '>' in /home/foo/public_html/topic_proposal_theme.php on line 106 And here's the statement that is executing: $stmt->execute(array(':date_proposed' ==> $date_proposed, ':proposer' ==> $proposer, ':title' ==> $title, ':discuss' ==> $discuss, ':prepare' ==> $prepare, ':comments' ==> $comments)); The funny thing is that this isn't the very first PDO statement or use of the -> operator in the progam. There are other statements in an include that gets the database connection; that include is situated several lines before the code that is failing. If PDO really wasn't there, I'd expect to see this error either the first time it encountered the -> operator or every time. So maybe I'm completely wrong in assuming PDO isn't there. Maybe there is something else wrong. But I've imitated the PDO tutorial examples pretty carefully so I'm not seeing my error if I've made a simple typo.
  18. I'm letting the admin users be able to create tables for polls and this is the query i have: $aquery = $con->prepare("ALTER TABLE `$table` ADD `$field` $enum DEFAULT '$def' NOT NULL"); the $table and $enum fields are both coming from another table so they are safe, but the $def and $field variables are both coming from the user. How can i check to be sure they are safe to use. I've tried this $aquery->bindParam(':field', $field); $aquery->bindParam(':def', $def); but that doesn't work
  19. Sorry if this is not the correct sub-forum, I just went through most sections and didn't really know the best place. I want to learn object oriented php but can't seem to find any resources which are written in good english. I was wondering if someone knows of any reliable resources for learning pdo? I've already looked on php.net but I wanted more of a tutorial based website written for novices. I hope someone can throw me a few links. Kind regards, L2c
  20. Hi There, I'm rather new to php so please bare with me! After many attempts i still have been unable to return success, even existing usernames still come up as free. this is the code i've been attempting to use; <?php }else{ $usr = new Users; $usr->storeFormValues( $_POST ); if( $_POST['password'] == $_POST['confpass'] ) { //passwords do match// } else { echo "Passwords do not match"; exit; } $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $stmt = $con->prepare("SELECT COUNT (*) FROM users WHERE username = :username"); if ($stmt->fetchColumn() > 0) { echo "username is taken"; }else{ echo "username is free"; } } Thanks, I Appreciate it!
  21. i'm building a project for the first time with PDO this is how i configured it index.php <?php require_once (dirname(__FILE__) . '/inc/main.php'); userlogin(); $HTMLOUT = ''; $stmt = $db->query("SELECT row_id, name, mobile FROM location LIMIT 3"); // $stmt->execute(array($id, $name)); $stmt->setFetchMode(PDO::FETCH_OBJ); $db = null; $stmt = null; ?> inc/main.php <?php require_once (dirname(__FILE__) . '/pdo_conn.php'); require_once (dirname(__FILE__) . '/mail/class.Mail.php'); error_reporting(E_ALL); function userlogin() { global $db; unset($GLOBALS["CURUSER"]); $ip = getip(); $nip = ip2long($ip); $id = 0 + get_cookie('uid'); $fetch_user_details = $db->prepare("SELECT * FROM users WHERE user_id = :bitches_id LIMIT 1"); $fetch_user_details->bindParam(':bitches_id', $id, PDO::PARAM_INT); $fetch_user_details->execute(); $fetch_user_details->setFetchMode(PDO::FETCH_OBJ); $row = $fetch_user_details->fetch(); $user_id = $row->user_id; $user_ip = $row->user_last_ip; $update_user_details = $db->prepare("UPDATE users SET user_last_access = UNIX_TIMESTAMP(), user_last_ip = :last_ip WHERE user_id = :u_id LIMIT 1"); $update_user_details->bindParam(':last_ip', $user_ip, PDO::PARAM_STR, 15); $update_user_details->bindParam(':u_id', $user_id, PDO::PARAM_INT); $update_user_details->execute(); $GLOBALS["CURUSER"] = $row; } function is_logged_in() { global $CURUSER; if (!$CURUSER) { header("Location: domain.net/login.php?403"); exit(); } } ?> inc/pdo_conn.php <?php $db = new PDO('mysql:host=localhost;dbname=abc;charset=UTF-8', 'abc', 'xam'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); ?> until a few days ago it worked, but when i starting to expand my project i started to get this error PHP Fatal error: Call to a member function prepare() on a non-object in /root/inc/main.php" the error reffers to this line $fetch_user_details = $db->prepare("SELECT * FROM users WHERE user_id = :bitches_id LIMIT 1");
  22. Please some1 help me with this code. i've tried soo many times to retrieve the rooms that are not booked. if no rooms have been booked for a specified period match with the user input, then the room is available for booking. and now my PDO Mysql code is spinning in my head... <?php /** * @author S34N * @copyright 2012 */ class Connection { Public function dbConnect() { return new PDO("mysql:host=localhost; dbname=waterfall", "root", "6354"); } } class Date_a { private $db; public function __construct() { $this->db = new Connection(); $this->db = $this->db->dbConnect(); } public function Query($arr, $dep) { try { if (!empty($arr) && !empty($dep)) //Check_In between booked dates Check_out User Prompted arrival date User Departure Date { $st = $this->db->prepare("SELECT `schedule`.`Check_In` , `schedule`.`RoomNo` , `schedule`.`Check_Out` FROM schedule WHERE (Check_In BETWEEN ? AND ? || Check_Out BETWEEN ? AND ?)"); $st->bindParam(1, $arr); $st->bindParam(2, $dep); $st->bindParam(3, $arr); //("SELECT `schedule`.`Check_In` , `schedule`.`RoomNo` , `schedule`.`Check_Out` FROM schedule WHERE ((Check_In >= ?) AND (Check_Out <= ?))"); $st->bindParam(4, $dep); //("SELECT `schedule`.`Check_In` , `schedule`.`RoomNo` , `schedule`.`Check_Out` FROM schedule WHERE ((? NOT BETWEEN Check_In AND Check_Out) AND (? NOT BETWEEN Check_In AND Check_Out))"); $st->execute(); //("SELECT `schedule`.`Check_In` , `schedule`.`RoomNo` , `schedule`.`Check_Out` FROM schedule WHERE ((Check_In BETWEEN ? AND ?) || (Check_Out BETWEEN ? AND ?) || (? BETWEEN Check_In AND Check_Out) || (? BETWEEN Check_In AND Check_Out))"); if($st->rowCount() >= 1) { $num = $st->rowCount(); echo $num; echo "Booked !"; } else { $status = "Available"; $num = 0; echo $status; } } else { echo "Empty input."; } $this->db = null; //Close Database Connection } catch (PDOException $e) { echo $e->getMessage(); //Returns error message. } } } ?>
  23. Hello Masters... Freaks I have a PDO Persistent Connections question. 1. If I connect to mySQL using PDO persistent connections turned as so.... $db = new PDO("mysql:host=localhost";"dbname=$this->dbName"; "$this->mySQLuser", "$this->mySQLpassword",array(PDO::ATTR_PERSISTENT => true,PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )); 2. Then I rerun this script (I rerun this script because it is a class that is auto loaded). 4. Will PDO reconnect to mySQL? Will PDO reconnect if the connection parameters change? The whole idea is to create db class that connects to mySQL using a user name and password that changes depending on the state of the user (logged in, not activated, not logged in). (Thought this would improve security because of the changing of the mySQL privliges based on user state, but Im a noob so I really dont know if it helps) Here is my full script. <?php class db { private $dbName='vulnVult'; public $tableName='users'; protected $mySQLuser='anon'; private $mySQLpassword="$this->mySQLuser".'password'; private $db; function __construct($PDO) { try { $db = new $PDO("mysql:host=localhost";"dbname=$this->dbName"; "$this->mySQLuser", "$this->mySQLpassword",array(PDO::ATTR_PERSISTENT => true,PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )); //Following Logic Sets MySQL user type if ($_SESSION['userID']) { $query= 'SELECT `activated` from `users` where'."$SESSION['userID']".'=`userID`'; $stmt = $db->query($query); $row = $stmt->rowCount(); if ($row = 1) { $this->mySQLuser='registered'; } else { $this->mySQLuser='notActivated'; } } else { $this->mySQLuser='anon' } // return a new PDO object with the corrct MySQL user type. Persistent Connection is On. return new $PDO("mysql:host=localhost";"dbname=$this->dbName"; "$this->mySQLuser", "$this->mySQLpassword",array(PDO::ATTR_PERSISTENT => true,PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )); } catch (PDOException $e) { echo "<br />There was a problem connecting to the database : ".$e->getMessage()."<br />"; die(); } } } $db = new db(PDO); ?>
  24. I am trying to change from using mysql to PDO, I heard it is very secure, but I think in-order to implement PDO, one needs to learn Object Oriented Programming for PHP. Is this true? And, if so Where can I find, the simplest and easiest to understand tutorials on the web for pdo, or oop.
  25. I have a website streaming project going on,but there's one thing that stops me from really starting it "HOW TO ADD FILE PATH INTO A MYSQL DB?" since I know it will slow down the sgbd to directly add the file in a longblob field,I need some help on how to retrieve those file path(manually?) Let's say a user enters 'die hard 4' in the search form,Do I concatenate the user's input to a query like $query = 'SELECT * FROM T_DIRECTORIES WHERE DIRECTORIES LIKE 'user_input%'; Then do 'scandir($query); Since I will name my directories as the files it contains
×
×
  • 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.