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. <?php $db = new PDO('mysql:host=localhost;dbname=wordpress', 'root',''); //---------prepare $delete3 = $db->prepare("DELETE FROM wp_term_relationships WHERE object_id=:id"); $delete2 = $db->prepare("DELETE FROM wp_posts WHERE ID=:id"); $delete = $db->prepare("DELETE FROM wp_postmeta WHERE post_id=:id"); $select = $db->prepare("SELECT post_id FROM reference WHERE x_id=?"); $delete->bindValue(':id', $id, PDO::PARAM_STR); $delete2->bindValue(':id', $id, PDO::PARAM_STR); $delete3->bindValue(':id', $id, PDO::PARAM_STR); //---------- echo 'conected-----'; { $delfeed = '';} $array = explode(',',$delfeed); foreach($array as $deadman){ $select->execute(array($deadman)); $row = $select->Fetch(PDO::FETCH_ASSOC); $id = $row['post_id']; if ($id == null){} else { echo "$id"."\n"; $delete->execute(); $delete2->execute(); $delete3->execute(); } $id++; } echo 'done!'; ?> its a simple delete script but it doesnt delete, it does print the right $id's witch means is working till there but delete goes bananas,double checked table names ,colums... tryied working with question mark place holders insted of bind parameter but nothing
  2. I'm getting the dreaded " Invalid parameter number: number of bound variables does not match number of tokens" error and I've looked at this for days. Here is what my table looks like: | id | int(4) | NO | PRI | NULL | auto_increment | | user_id | int(4) | NO | | NULL | | | recipient | varchar(30) | NO | | NULL | | | subject | varchar(25) | YES | | NULL | | | cc_email | varchar(30) | YES | | NULL | | | reply | varchar(20) | YES | | NULL | | | location | varchar(50) | YES | | NULL | | | stationery | varchar(40) | YES | | NULL | | | ink_color | varchar(12) | YES | | NULL | | | fontchosen | varchar(30) | YES | | NULL | | | message | varchar(500) | NO | | NULL | | | attachment | varchar(40) | YES | | NULL | | | messageDate | datetime | YES | | NULL | Here are my params: $params = array( ':user_id' => $userid, ':recipient' => $this->message_vars['recipient'], ':subject' => $this->message_vars['subject'], ':cc_email' => $this->message_vars['cc_email'], ':reply' => $this->message_vars['reply'], ':location' => $this->message_vars['location'], ':stationery' => $this->message_vars['stationery'], ':ink_color' => $this->message_vars['ink_color'], ':fontchosen' => $this->message_vars['fontchosen'], ':message' => $messageInput, ':attachment' => $this->message_vars['attachment'], ':messageDate' => $date ); Here is my sql: $sql = "INSERT INTO messages (user_id,recipient, subject, cc_email, reply, location,stationery, ink_color, fontchosen, message,attachment) VALUES( $userid, :recipient, :subject, :cc_email, :reply, :location, :stationery, :ink_color, :fontchosen, $messageInput, :attachment, $date);"; And lastly, here is how I am calling it: $dbh = parent::$dbh; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); if (empty($dbh)) return false; $stmt = $dbh->prepare($sql); $stmt->execute($params) or die(print_r($stmt->errorInfo(), true)); if (!$stmt) { print_r($dbh->errorInfo()); } I know my userid is valid and and the date is set above (I've echo'd these out to make sure). Since the id is auto_increment, I do not put that in my sql (though I've tried that too), nor in my params (tried that too). What am I missing? I feel certain it is something small, but I have spent days checking commas, semi-colons and spelling. Can anyone see what I'm doing wrong?
  3. Here is my code so far (I say it's PDO but it pretty much isn't. What is the object here? The database connection? LOL!); $sql = " SELECT SUM(IF(`sent` != 'N' , 1 , 0 )) as 'Emails Sent', SUM(IF(`completed` NOT IN('N','paper') , 1 , 0 )) as 'Completed Electronically', SUM(IF(`completed` = 'paper' , 1 , 0 )) as 'Completed Manually', SUM(IF(`completed` != 'N' , 1 , 0 )) as 'Total Number Completed', SUM(IF(`remindercount` = '1' , 1 , 0 )) as 'Reminder Sent Once', SUM(IF(`remindercount` = '2' , 1 , 0 )) as 'Reminder Sent Twice', SUM(IF(`remindercount` = '3' , 1 , 0 )) as 'Reminder Sent Thrice' FROM `tokens_$survey_id` "; $statement = $dbh->prepare($sql); $statement->execute(); $result = $statement->fetch(PDO::FETCH_OBJ); foreach($result as $key => $value) { echo "<tr> <td>$key</td> <td>$value</td> </tr>"; } This is all well and good if the tokens_$survey_id table is actually there. Sometimes, for a genuine reason, there won't be a tokens table for that particular survey. How do I account for this? At the moment I get an error.. Warning: Invalid argument supplied for foreach() in /var/www/html/index.php on line 149 I tried this but I am not satisfied this is correct; if(!$result) { die(); } I don't want the code to die! If I take out the die() statement then this if is ignored for some reason I don't understand.
  4. I have written a Validation class that checks to see if a file being uploaded to the server meets certain conditions. That works a treat. The next step is to actually upload it to the server and I have an Upload class that can do that. Again, that works perfectly fine. Once the file uploads, I am passing the $location of that of that file to my DB class. The DB class is full of methods that prepare and then execute strings that are SQL queries that are required in other areas of my application. Nothing I have at the moment is suitable for just running an SQL file so I don't know what to do now.. My procedural code, that works, looks like this; $dbh2 = new PDO("mysql:host=localhost;dbname=DB360transfer", $login_user, $login_password); $sql = file_get_contents($path.$new_file_name); $qr = $dbh2->exec($sql); I'm not sure how to replicate this up in a PDO/OOP application. My DB Class script is attached. The run_from_file code starts on line 98. I've left in the other stuff as I suspect the answer has something to do with using the $this or the self:: - but really I have no idea. So my question is, what is the correct syntax for executing a file in OOP? DB.php
  5. I built a CMS system using CKEditor and KCFinder that store information od a databse via textarea/php. So far so good! The issue comes to when I want to store and display images that link to themselves. The way I am storing images is exactly the same: There is a textarea where I insert an image via KCFinder/CKEditor. The image is uploaded to the server and the path stored at the database. Later I try to pick up that path from the database to display the image and because I want the image to link to itself, I try to use the same method to insert the url on the link. Problem? The link is missing and the images are not displaying. Can anyone point me the error and suggest any solution? I would be so thankful! CODE: try { $DBH = new PDO('mysql:host=localhost;dbname=yourdb;charset=utf8', 'user', 'password'); $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $STH = $DBH->prepare('SELECT * FROM php_maskiner ORDER BY timestamp DESC'); $STH->execute(); $STH->setFetchMode(PDO::FETCH_OBJ); while($row = $STH->fetch()) { $title = $row->title; $entry = $row->entry; $images = $row->images; $img_url = $row->images; $img_pack = '<div class="mask3 span3"> <a rel="prettyPhoto" href="'.$img_url.'"><img src="'.$images.'"></a> </div>'; } $DBH = null; } catch (PDOException $e) { echo '<div class="alert alert-standard fade in"> <a class="close" data-dismiss="alert" href="#">×</a> <strong>Can\'t read the database!</strong> </div><br />'.$e; } <?php echo '<article class="span12 post"> '.$img_pack.' <div class="inside"> <div class="span8 entry-content"> <div class="span12"> <h2>'.$title.'</h2> <p>'.$entry.'</p> </div> </div> </div> </article>'; ?> Thanks in advance!
  6. I can't find out whats the problem here, would appreciate some input in how to think building my "if". The problem is that I don't seem to catch if an email exists, nor if user exists and neither can I create a new user :/. Appreciate your help alot! <?php // Start the session in case of errors to display within the page of user creation session_start(); $err_msg = array(); $errflag = false; // Check if the submit button was pressed if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['submit'] === 'Skapa') { // Crypt password $options = ['cost' => 10]; $username = strip_tags($_POST['uname']); $password = strip_tags(password_hash($_POST['pword'], PASSWORD_DEFAULT, $options)); $email = strip_tags($_POST['uname'], '@'); // Check so all the fields are filled if ($_POST['uname'] == '' || $_POST['pword'] == '' || $_POST['pwordcheck'] == '') { $err_msg[] = 'Please enter all fields<br>'; $errflag = true; } // See if passwords and confirm matches if ($_POST['pword'] !== $_POST['pwordcheck']) { $err_msg[] = 'Passwords doesn\'t match!<br>'; $errflag = true; } // Check password length, atleast 8 characters if (strlen($_POST['pword']) < 7) { $err_msg[] = 'Password must be atleast 8 characters long'; $errflag = true; } // Check if email exists include_once('../includes/db.inc.php'); $db = new PDO(DB_INFO, DB_USER, DB_PASS); $sql = "SELECT COUNT(*) AS count FROM movies WHERE email = :emailadress"; $stmt = $db->prepare($sql); $stmt->bindParam(':emailadress', $email); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ($row > 0) { $err_msg[] = 'Email already taken!'; $errflag = true; $db = NULL; } // Check if user exists include_once('../includes/db.inc.php'); $db = new PDO(DB_INFO, DB_USER, DB_PASS); $sql = "SELECT uname FROM users WHERE uname = :username"; $stmt = $db->prepare($sql); $stmt->bindParam(':username', $username); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ($row > 0) { $err_msg[] = 'User already exists'; $errflag = true; $db = NULL; } if ($errflag = false) { // Everything passed, create the user! include_once('../includes/db.inc.php'); $db = new PDO(DB_INFO, DB_USER, DB_PASS); $sql = "INSERT INTO users (uname, pword, email) VALUES (:username, :password, :emailadress)"; $stmt = $db->prepare($sql); $stmt->bindParam(':username', $username); $stmt->bindParam(':password', $password); $stmt->bindParam(':emailadress'); $stmt->execute(); $_SESSION['uname'] = $username; header('Location: ../template/header.php'); exit; } // If any error, send the user back and display messages if ($errflag == true) { $_SESSION['err_msg'] = $err_msg; session_write_close(); header('Location: ../user/create.php'); exit; } } else { $_SESSION['err_msg'] = $err_msg; session_write_close(); header('Location: ../user/create.php'); exit; } ?>
  7. $sqld = "SELECT * FROM orders WHERE `id`='$delete' AND `name`='$inf2[name]' AND `email`='$inf2[email]' LIMIT 1"; $csql = $db->query($sqld); $ccheck = $csql->fetch(PDO::FETCH_NUM); $cinf = $csql->fetch(PDO::FETCH_ASSOC); $quantity = $cinf[quantity]; $code = $cinf[code]; $stmt11 = $db->prepare('UPDATE feeds SET quantity=quantity-:quantity WHERE code=:code'); $stmt11->bindValue(':quantity', $quantity, PDO::PARAM_STR); $stmt11->bindValue(':code', $code, PDO::PARAM_STR); $stmt11->execute(); $id = $delete; $name = $inf2[name]; $stmt2 = $db->prepare("DELETE FROM orders WHERE id=:id AND name=:name"); $stmt2->bindValue(':id', $id, PDO::PARAM_STR); $stmt2->bindValue(':name', $name, PDO::PARAM_STR); $stmt2->execute(); OK, i have just been told i should start using PDO instead of mysql to update my tables. This code works to delete the order but doesn't update the feeds section. All this is new to me so far and i think i am getting the hang of it. Should i still be using the quantity=quantity-:quantity or is there another way to do it with PDO? Sorry, i posted this in the wrong forum. Hope someone here can help until it's moved
  8. What's up guys! Can somebody please explain the meaning of PDO::PARAM_INT in the following statement: $pdoStmt->bindValue(":num", $num, PDO::PARAM_INT); I have already created a PDO Statement object called $pdoStmt. This line will bind the value of $num to the placeholder called :num. I know that PDO::PARAM_INT is a Predefined Constant but what does it do in this case? Thanx
  9. Hi I'm trying to post and validate a form but it doesn't seem to work and it doean't display any errors Here's the code <?php include("config.php"); session_start(); ?> <?php // define variables and initialize with empty values $rateErr = $comErr = ""; $rating = $comment = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if ($_POST["rating"] == "") { $rateErr = "Rate the app"; } else { $rating= $_POST["rating"]; } if (empty($_POST["comment"])) { $comErr = "Missing"; } else { $comment = $_POST["comment"]; } if ($rateErr == "" && $comErr == "") { try { $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $sql = "INSERT INTO reviews (rating, content, appID, user) VALUES(:rating, :comment, :appID, :username)"; $stmt = $con->prepare( $sql ); $stmt->bindValue( ":rating", $rating); $stmt->bindValue( ":comment", $comment); $stmt->bindValue( ":appID", $_GET['id']); $stmt->bindValue( ":username", $_SESSION['username']); $stmt->execute(); return "Submitted successfully"; }catch( PDOException $e ) { return $e->getMessage(); } } } ?> <html> <head> </head> <body> <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <select name="rating"> <option value=""></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <span class="error"><?php echo $rateErr;?></span> <br /> <textarea rows="4" cols="50" name="comment" value="<?php echo htmlspecialchars($comment);?>"> Enter text here...</textarea> <span class="error"><?php echo $comErr;?></span> <input type="submit" name="submit" value="Submit"> </form> </body> </html>
  10. So I have this CMS that I have spent the last 5 years building and rebuilding and updating blah blah. It's a fairly extensive piece work and I am now looking at converting the entire system over to OOP. I am fairly new to OOP but understand the easy basics of it. I do fight with the concept of when to make a class and when to just make a normal function. I have many functions that I built specific to how my system works and some I suppose could be grouped into categories but then many others are just plain functions that only serve one purpose and may only be a few lines long. I will be using the spl_autoload_register() to load the classes as needed which is obviously much easier than including all the function pages that are needed. So for that reason I like the idea of making classes for everything but it just seems like more than is needed. So what I am looking for is some insight as to when and how to decide if a class should be made and whether to group functions by category to limit the amount of classes OR to just leave them as normal functions. Here is a example function for creating a thumbnail. I would guess that I could make a class called Thumb and put this in it, but what exactly would be the benefit of that based on the syntax of the function AND could you show me how you would convert this to OOP to make it worth while putting it in a class? // Creates a thumbnail function createThumb($img, $type, $dest = NULL, $xy = NULL) { if($type=="admin_product") { $thumb_width = $GLOBALS['admin_thumb_width']; $thumb_height = $GLOBALS['admin_thumb_height']; } elseif($type=="custom") { $thumb_width = ($dest !== NULL) ? $xy['x'] : (int)$_GET['width']; $thumb_height = ($dest !== NULL) ? $xy['y'] : (int)$_GET['height']; } $src_size = getimagesize($img); if($src_size['mime'] === 'image/jpg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/jpeg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/pjpeg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/png') {$src = imagecreatefrompng($img);} elseif($src_size['mime'] === 'image/gif') {$src = imagecreatefromgif($img);} $src_aspect = round(($src_size[0] / $src_size[1]), 1); $thumb_aspect = round(($thumb_width / $thumb_height), 1); if($src_aspect < $thumb_aspect)//Higher { $new_size = array($thumb_width, ($thumb_width / $src_size[0]) * $src_size[1]); $src_pos = array(0, (($new_size[1] - $thumb_height) * ($src_size[1] / $new_size[1])) / 2); } elseif($src_aspect > $thumb_aspect)//Wider { $new_size = array(($thumb_height / $src_size[1]) * $src_size[0], $thumb_height); $src_pos = array((($new_size[0] - $thumb_width) * ($src_size[0] / $new_size[0])) / 2, 0); } else//Same Shape { $new_size = array($thumb_width, $thumb_height); $src_pos = array(0, 0); } if($new_size[0] < 1){$new_size[0] = 1;} if($new_size[1] < 1){$new_size[1] = 1;} $thumb = imagecreatetruecolor($new_size[0], $new_size[1]); imagealphablending($thumb, false); imagesavealpha($thumb, true); imagecopyresampled($thumb, $src, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]); //$src_pos[0], $src_pos[1] 3rd and 4th of zeros position on above line if($src_size['mime'] === 'image/jpg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/jpeg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/pjpeg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/png') { if($dest !== NULL) { imagepng($thumb, $dest); } else { header('Content-Type: image/png'); imagepng($thumb); } } elseif($src_size['mime'] === 'image/gif') { if($dest !== NULL) { imagegif($thumb, $dest); } else { header('Content-Type: image/gif'); imagegif($thumb); } } imagedestroy($src); } Your insight is appreciated.
  11. Hey. Just recently got into developing with PDO and OOP, instead of the old MySQL_*, so I'm pretty new, and have some dumb questions. Right now I'm taking the first steps into making a blog (Nope, not a blogger - just need something to work on), and i came across a tutorial to create a database class. I have spend a little time on making such a class, and though I got it working just fine, I'm not really sure how useful and necessary it really is. Yeah, of course it saves you a couple of lines, but at the cost of getting used to using the class, instead of just raw PDO. Here is the class i just quickly made: <?php class database { private $host = DB_HOST; private $user = DB_USER; private $pass = DB_PASS; private $dbname = DB_NAME; public function __construct() { // Try connection or die. try { $this->db = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname, $this->user,$this->pass); } catch(PDOException $e) { die($e); } } public function getColumn($sql, $params) { // Get value of a single row $query = $this->db->prepare($sql); $query->execute($params); return $query->fetchColumn(); } public function fetch($sql, $params) { // Return fetch $query = $this->db->prepare($sql); $query->execute($params); return $query->fetch(); } public function update($sql, $params) { // Update $query = $this->db->prepare($sql); $query->execute($params); } public function getRows($sql, $params) { // Return number of rows $query = $this->db->prepare($sql); $query->execute($params); return($query->rowCount()); } public function insert($sql, $params) { // Insert $query = $this->db->prepare($sql); $query->execute($params); } } ?> I know it can get way more optimized, advanced and usefull, but it's just a quick example. Is it just dumb to spend time on a database class, or is it worth the time? Any advice appriciated. Thanks in advande!
  12. The idea is simple. A key you press (a letter) appears in updated page: keyj.php: <input id='k'></input> <script type="text/javascript"> document.getElementById('k').onkeypress=function() { <?php $db=new PDO('mysql:host=localhost;dbname=test;charset=utf8','$us','$ps'); $db->exec("UPDATE TXT SET texts=k.value"); $rl=$db->query("SELECT texts FROM TXT"); print_r($rl->fetchColumn()); ?> } </script> The intention is to have text on the screen via print_r. I successfully used it in another php to exchange information with MySQL and users screen (worked). Here - the more you type and the more k.value is the more text will be on screen (just from server). Unfortunately something went wrong.
  13. I have this function for a search engine using pdo public function GetPageurlByPagecontent() { $db = Database::getDB(); $query = "SELECT * FROM searchengine where pageurl Like Pagecontent"; $searchengine =$db->query($query); return $searchengine; } in the data base pagecontent = keyword pageurl is the url to match that keyword this is my form , I want the pagecontent to match the pageurl only when i do a search by the pagecontent dont even think this query work any ideas? <form action="searchhome.php" method="post" id="search"> <b>Enter Search Term:</b> <input type="text" name="term" size="50"> <b>Results:</b> <select name="results"> <option>10</option> <option>20</option> <option>50</option> </select><br> <input type="submit" value="Search"> </form> <br /> <br /> <?php if(isset($_POST['pageurl'])){ $c_name = $_POST['pageurl']; $pdb2 = new SearchDB(); $search= $pdb2->GetPageurlByPagecontent($c_name); ?> <h1> Results <?php echo $c_name ?> </h1> <?php foreach($search as $list): ?> <br /> <br /> <table> <tr> <td> <p><em> url </em>: <?php echo $list['pageurl'] ?> </p> </td> </tr> </table> <?php endforeach; ?> <?php }?>
  14. I’m moving my code from Procedural to OOP and am having an issue trying to run a basic query. Looks like the connection to the DB is made, but I must not be fully understanding Objects / scope of Objects yet.. I’m trying keep it simple so I can test this out and understand it before updating my code. My instal thoughts are: 1. Get OOP class set up for DB Connection. MySQL first as that’s what I’m using now. Then config MSSQL and Oracle classes for easy integration. 2. Get simple queries working using a basic function file with PDO (Like current code). 3. Convert my function files to classes. I’ve separated my code to 3 function files (categories) for some organization. The files aren’t huge, but they do range from 150 lines to just over 1000. Below is the code I’m testing with. Pretty simple and I hope straight forward. I’ve also tried sending in $dbConn as a variable versus have it as a global variable in the function.. I’ve read that’s the better way. But if anybody has thoughts on that too I would love to hear opinions / recommendations. thanx Index.php - testing page: /** * Start Includes sections */ require_once("../includes/db_conn/MYSQL_database.php"); require_once("../includes/functions.php"); /** * End Includes sections */ /** * Check DB Connection */ if (isset($config)){ echo"<pre>"; print_r($config); echo"<pre>"; }else{ echo'<script type="text/javascript">window.alert("config not set")</script>'; } echo"<hr>"; //if (isset($database)){echo "Database opened"; } else {echo "Database not opened";} /** * If connected to DB load page * Else echo not connected */ if (isset($database)){ //echo "Database opened"; /** * Run query to verify working. */ $customers = cust_list($dbConn); echo "<pre>"; print_r($customers); echo "</pre>"; } else { echo "Database not opened"; } MySQLDatabase Class: class MySQLDatabase { /** * MySql Connect to DB */ private $host; private $dbname; private $username; private $password; public $dbConn; function __construct($config){ $this->host = ($config['host']); $this->dbname = ($config['dbname']); $this->username = ($config['username']); $this->password = ($config['password']); } private function open_connection(){ try{ //$this->connection = new PDO('mysql:host=' . $host . ';dbname=' . $dbname, $username, $password); $this->dbConn = new PDO('mysql:host=' . $host . ';dbname=' . $dbname, $username, $password); echo "<script type=\"text/javascript\">window.alert(\"Connection Made\")</script>"; }catch(PDOException $e){ echo 'ERROR Inside the open_connection funtion: ' . $e->getMessage(); } } } /** * Create object */ $database = new MySQLDatabase($config); Functions File (will be moved to a Class next): function cust_list($dbConn){ //global $dbConn; try{ /** * Prepare */ $cust_list = $dbConn->prepare("select * from customer"); /** * Bind */ /** * Execute */ $cust_list->execute(); /** * Fetch from array */ $cust_list_array = $cust_list->fetchall(PDO::FETCH_ASSOC); /** * Return */ return $cust_list_array; } catch(PDOException $e){ echo"Inside cust_list " . $e->getMessage(); } } When sending in $dbConn I get: Notice: Undefined variable: dbConn in /Users/aaronjk/localhost/base_sites/php_base/public/index.php on line 34 Fatal error: Call to a member function prepare() on a non-object in /Users/aaronjk/localhost/base_sites/php_base/includes/functions.php on line 12 When setting $dbConn as global inside the function I get: Fatal error: Call to a member function prepare() on a non-object in /Users/aaronjk/localhost/base_sites/php_base/includes/functions.php on line 12 From What I've read I "Call to member function prepare() on a non-object in.. " is because I need the global connection $dbConn set in the called function, but I thought I was doing that.
  15. Hello, > Sorry for my English I use a translator frensh => english:) I have a problem for convertire my current code MySql in PDO, I want to keep the same structure. This is my MySql structure: <?php class Dbase{ private $_host = "localhost"; private $_user = "root"; private $_password = ""; private $_name = "dbase"; private $_conndb = FALSE; public $_last_query = NULL; public $_affected_rows = 0; public $_insert_keys = array(); public $_insert_values = array(); public $_update_sets = array(); public $_id; public function __construct(){ $this->connect(); } private function connect(){ $this->_conndb = mysql_connect($this->_host,$this->_user,$this->_password); if(!$this->_conndb){ die("Database connection failed:<br />".mysql_error()); }else{ $_select = mysql_select_db($this->_name,$this->_conndb); if(!$_select){ die("Database selection failed:<br />".mysql_error()); } } mysql_set_charset("UTF-8", $this->_conndb); } public function close(){ if(!mysql_close($this->_conndb)){ die("Closing connection failed."); } } public function escape($value){ if(function_exists("mysql_real_escape_string")){ if(get_magic_quotes_gpc()){ $value = stripslashes($value); } $value = mysql_real_escape_string($value); }else{ if(!get_magic_quotes_gpc()){ $value = addslashes($value); } } return $value; } public function query($sql){ $this->_last_query = $sql; $result = mysql_query($sql, $this->_conndb); $this->displayQuery($result); return $result; } public function displayQuery($result){ if(!$result){ $output = "Database query failed: ".mysql_error()."<br />"; $output .= "Last SQL query was: ".$this->_last_query; die($output); }else{ $this->_affected_rows = mysql_affected_rows($this->_conndb); } } public function fetchAll($sql){ $result = $this->query($sql); $out = array(); while($row = mysql_fetch_assoc($result)){ $out[] = $row; } mysql_free_result($result); return $out; } public function fetchOne($sql){ $out = $this->fetchAll($sql); return array_shift($out); } public function lastId(){ return mysql_insert_id($this->_conndb); } } I am trying to self resolve but and don't kan resolve, i try this but is not work: <?php class Dbase{ private $_pdo_host_dbname = "mysql:host=127.0.0.1;dbname=dbase"; private $_user = "root"; private $_password = ""; private $_conndb = FALSE; public $_last_query = NULL; public $_affected_rows = 0; public $_insert_keys = array(); public $_insert_values = array(); public $_update_sets = array(); public $_id; public function __construct(){ $this->connect(); } private function connect(){ try{ $this->_conndb = new PDO($this->_pdo_host_dbname,$this->_user,$this->_password); } catch { echo 'Connection failed'; } } public function escape($value){ if(get_magic_quotes_gpc()){ $value = stripslashes($value); } $value = $this->_conndb->quote($value); return $value; } public function query($sql){ $this->_last_query = $sql; $result = $this->_conndb->query($sql); $this->displayQuery($result); return $result; } public function displayQuery($result){ if(!$result){ $output = "Database query failed: ".$this->_conndb->errorInfo()."<br />"; $output .= "Last SQL query was: ".$this->_last_query; die($output); }else{ $this->_affected_rows = $this->_conndb->rowCount($this->_conndb); } } public function fetchAll($sql){ $result = $this->query($sql); $out = array(); while($row = $this->_conndb->fetch(PDO::FETCH_ASSOC)){ $out[] = $row; } return $out; } public function fetchOne($sql){ $out = $this->fetchAll($sql); return array_shift($out); } public function lastId(){ return $this->_conndb->lastInsertId($this->_conndb); } } Please help me
  16. does anyone know a class that can generate a menu with category and subcategory that connects to mysql with pdo ? thank you
  17. I have some code that I edited for importing csv into mysql using PDO to bind parameters. I thought it was working before, but tested it again and the issue I have is that only one line (the fourth line) of the csv file is getting imported. The first line is the header which are the table field names. The first method below is what's used to parse the csv files and bind the field names with the data. The second method, loops through. I need another pair of eyes, so if anyone can help me figure out my issue, I would greatly appreciated. public function getSQLinsertsArray($sqlTable) { $data = $this->getCSVarray(); $queries = []; $fieldsStr = ""; while(list($k, $field) = each($data)) { if(empty($fieldStr)) $fieldStr = implode(", ", array_keys($field)); //$valueStr = "'".implode("', '", $field)."'"; $placeholders = array_map(function($col) { return ":$col"; }, $field); $bind = array_combine($placeholders,$field); $queries[] = DB::inst()->query("INSERT INTO ".$sqlTable." (".$fieldStr.") VALUES (".implode(",", $placeholders).");",$bind); //error_log(var_export($queries,true)); } return $queries; } public function queryInto($sqlTable) { $queries = $this->getSQLinsertsArray($sqlTable); while(list($k, $query) = each($queries)) { $q = $query; } if($q > 0) { return true; } else { return false; } }
  18. Hello! I found out that some 'SELECT' SQL queries are very slow with pdo_sqlite (PHP 5.3 or PHP 5.4). The same query entered in the sqlite3 binary is way faster. Here is my project : http://we.tl/59fGSVnAXh (password : "sqlite-php") - bench.php - chaines_centre.db - inc_func.php - info_job.php The info_job.php page performs 5 'SELECT' queries in 10 seconds with my Apache server. A same query is perform in less than 0.2 seconds in the sqlite3 binary (so theoretically 1 second for the whole page). I tried to modify the query a bit, and the results are strange : Benchmark (bench.php) on the « $bdd->query(...); » instruction : Query 2 : select DateMonteeAuPlan, Debut, Fin, Statut from ReportJobs where NomJob = 'NSAVBASE' and NomChaine like 'DCLC257%' limit 20; => 0.00099992752075195 seconde(s) Query 3 : select DateMonteeAuPlan, Debut, Fin, Statut from ReportJobs where NomJob = 'NSAVBASE' and NomChaine = 'DCLC25736' order by DateMonteeAuPlan DESC limit 20; => 0 seconde(s) Query 1 : select DateMonteeAuPlan, Debut, Fin, Statut from ReportJobs where NomJob = 'NSAVBASE' and NomChaine like 'DCLC257%' order by DateMonteeAuPlan DESC limit 20; => 1.8629999160767 seconde(s) Why is there so much differences between two query quasi-identical? How can I improve this situation to get results as fast as the sqlite3 binary? Thanks if you took the time to look out my project files.
  19. [code] <html> <body> <?php include('connect.php'); $ud_NUMB=(int)$_POST["fNumb"]; $ud_PAID=$_POST["fPaid"]; echo $ud_NUMB; echo $ud_PAID; $sql = "UPDATE Teams SET Paid = :paid WHERE Numb = :numb"; $stmt = $db->prepare($sql); $stmt->bindParam(':paid', $_POST['fPaid'], PDO::PARAM_STR); $stmt->bindParam(':numb', $_POST['$fNumb'], PDO::PARAM_STR); $stmt->execute(); echo "\nPDO::errorCode(): "; print $stmt->errorCode(); ?> </br><p><a href='game.php'><H3>Back to main page</H3></a> </body> </html> [/code] My connect works fine, used in other scripts. $db is the connection. My echo of the two passed variables works fine. Example reply from echo is: 8Yes (didn't bother to put in spaces). The only reply on error is: PDO::errorCode(): 00000 I get the prompt to return to the website link at the end. No other error codes. But it does not update my record. It should change record with unique ID of 8 to show Yes in the Paid column. Can someone point me in the right direction here? Thanks
  20. Hi Guys Any ideas why nothing is being stored in my database? I have echoed out all the variables and they appear fine, likewise I am not getting any PDO errors from the try/catch, just nothing is being stored! <?PHP //for ($x=0; $x <=9; $x++) //{ // print_r($url); // print_r(" "); // print_r(""); // print_r ($response); // print_r(""); //} $var = '@activePropertyCount'; foreach($response as $data) { $mycount = $data->HotelList->$var; } // while( $mycount > -1) // { $mycount = 1; foreach($response as $data) { try { $host = 'localhost'; $dbname = 'HotelWifi'; $user = 'removed'; $pass = 'removed'; # MySQL with PDO_MYSQL $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); } catch(PDOException $e) { echo $e->getMessage(); } //print_r($data->HotelList->HotelSummary[$mycount-1]->hotelId); //print_r($data->HotelList->HotelSummary[$mycount-1]); $STH = $DBH->prepare("INSERT INTO HotelData (HotelID, HotelName, HotelCity, HotelCountry, LowRate, Long, Lat) values (:id,:name,:city,:country,:low,:long,:lat)"); $HotelID = $data->HotelList->HotelSummary[$mycount-1]->hotelId; $HotelName = $data->HotelList->HotelSummary[$mycount-1]->name; $HotelCity = $data->HotelList->HotelSummary[$mycount-1]->city; $HotelCountry = $data->HotelList->HotelSummary[$mycount-1]->countryCode; $LowRate = $data->HotelList->HotelSummary[$mycount-1]->lowRate; $Long = $data->HotelList->HotelSummary[$mycount-1]->longitude; $Lat = $data->HotelList->HotelSummary[$mycount-1]->latitude; $STH->bindParam(":id", $HotelID); $STH->bindParam(":name", $HotelName); $STH->bindParam(":city", $HotelCity); $STH->bindParam(":country", $HotelCountry); $STH->bindParam(":low", $LowRate); $STH->bindParam(":long", $Long); $STH->bindParam(":lat", $Lat); echo $HotelID . " " . $HotelName . " " . $HotelCity . " " . $HotelCountry . " " . $LowRate . " " . $Long . " " . $Lat; try { $STH->execute(); print_r($STH); } catch(PDOException $e) { echo $e->getMessage(); } } // // // // // // print_r($data->HotelList); // // // $i = $i + 1; ?>
  21. ok, im writing a simple CRUD application for my work and i am having trouble with the UPDATE statement in the following code, the insert statement works fine. frm_bpd_sv.php: <?php error_reporting(-1); $page['title'] = "BPD Save"; require_once('config.inc.php'); if(isset($_SESSION['jobDetailID'])){ $jobdetailid = $_SESSION['jobDetailID']; } else { header("location:index.php"); } try { $dbh = new PDO("mysql:host=$db_host;dbname=$db_name", $db_username, $db_password); } catch(PDOException $e){ echo $e->getMessage(); } if(isset($_GET['editID'])){$data['bpdID'] = $_GET['editID'];} $data['jobDetailID'] = $jobdetailid; if(isset($_POST['backflowID'])){$data['backflowID'] = $_POST['backflowID'];} else {$data['backflowID'] = null;} if(isset($_POST['bpdOnsite'])){$data['bpdOnsite'] = $_POST['bpdOnsite'];} else {$data['bpdOnsite'] = 0;} if(isset($_POST['bpdLocation'])){$data['bpdLocation'] = $_POST['bpdLocation'];} else {$data['bpdLocation'] = null;} if(isset($_POST['bpdMake'])){$data['bpdMake'] = $_POST['bpdMake'];} else {$data['bpdMake'] = null;} if(isset($_POST['bpdModel'])){$data['bpdModel'] = $_POST['bpdModel'];} else {$data['bpdModel'] = null;} if(isset($_POST['bpdSerial'])){$data['bpdSerial'] = $_POST['bpdSerial'];} else {$data['bpdSerial'] = null;} if(isset($_POST['bpdSize'])){$data['bpdSize'] = $_POST['bpdSize'];} else {$data['bpdSize'] = null;} if(isset($_POST['protectionType'])){$data['protectionType'] = $_POST['protectionType'];} else {$data['protectionType'] = null;} if(isset($_POST['bpdType'])){$data['bpdType'] = $_POST['bpdType'];} else {$data['bpdType'] = null;} if(isset($_POST['protectionLvl'])){$data['protectionLvl'] = $_POST['protectionLvl'];} else {$data['protectionLvl'] = null;} if(isset($_POST['wmNo'])){$data['wmNo'] = $_POST['wmNo'];} else {$data['wmNo'] = null;} if(isset($_POST['wmSize'])){$data['wmSize'] = $_POST['wmSize'];} else {$data['wmSize'] = null;} if(isset($_POST['wmLocation'])){$data['wmLocation'] = $_POST['wmLocation'];} else {$data['wmLocation'] = null;} if(isset($_POST['sprinklers'])){$data['sprinklers'] = $_POST['sprinklers'];} else {$data['sprinklers'] = null;} if(isset($_POST['drinkingTaps'])){$data['drinkingTaps'] = $_POST['drinkingTaps'];} else {$data['drinkingTaps'] = null;} if(isset($_POST['longitude'])){$data['longitude'] = $_POST['longitude'];} else {$data['longitude'] = null;} if(isset($_POST['latitude'])){$data['latitude'] = $_POST['latitude'];} else {$data['latitude'] = null;} if(isset($_POST['accuracy'])){$data['accuracy'] = $_POST['accuracy'];} else {$data['accuracy'] = null;} if(isset($_POST['activity'])){$data['activity'] = $_POST['activity'];} else {$data['activity'] = null;} if(isset($_POST['permisionTTOW'])){$data['permisionTTOW'] = $_POST['permisionTTOW'];} else {$data['permisionTTOW'] = null;} if(isset($_POST['comments'])){$data['comments'] = $_POST['comments'];} else {$data['comments'] = null;} if(isset($_POST['pass'])){$data['pass'] = $_POST['pass'];} else {$data['pass'] = null;} print_r($data); echo '<hr>'.$_GET['editID']; if(isset($_GET['editID'])){ $editID = $_GET['editID']; $temp = "UPDATE frm_bpd SET `backflowID` = :backflowID, `jobDetailID` = :jobDetailID, `bpdOnsite` = :bpdOnsite, `bpdLocation` = :bpdLocation, `bpdMake` = :bpdMake, `bpdModel` = :bpdModel, `bpdSerial` = :bpdSerial, `bpdSize` = :bpdSize, `protectionType` = :protectionType, `bpdType` = :bpdType, `protectionLvl` = :protectionLvl, `wmNo` = :wmNo, `wmSize` = :wmSize, `wmLocation` = :wmLocation, `sprinklers` = :sprinklers, `drinkingTaps` = :drinkingTaps, `longitude` = :longitude, `latitude` = :latitude, `accuracy` = :accuracy, `activity` = :activity, `permisionTTOW` = :permisionTTOW, `comments` = :comments, `pass` = :pass` WHERE `bpdID` = :bpdID"; } else { $editID = false; $temp = "INSERT INTO frm_bpd (`backflowID`, `jobDetailID`, `bpdOnsite`, `bpdLocation`, `bpdMake`, `bpdModel`, `bpdSerial`, `bpdSize`, `protectionType`, `bpdType`, `protectionLvl`, `wmNo`, `wmSize`, `wmLocation`, `sprinklers`, `drinkingTaps`, `longitude`, `latitude`, `accuracy`, `activity`, `permisionTTOW`, `comments`, `pass`) VALUES (:backflowID, :jobDetailID, :bpdOnsite, :bpdLocation, :bpdMake, :bpdModel, :bpdSerial, :bpdSize, :protectionType, :bpdType, :protectionLvl, :wmNo, :wmSize, :wmLocation, :sprinklers, :drinkingTaps, :longitude, :latitude, :accuracy, :activity, :permisionTTOW, :comments, :pass);"; } try { $sql = $dbh->prepare($temp); $sql->execute($data); $succsess = 1; } catch(PDOException $e) { header("location:frm_bpd.php?id=".$editID."&message=".$e->getMessage()); $succsess = 0; } if($editID == false){ $editID = $dbh->lastInsertId(); } /*if($succsess == 1){ header("location:frm_bpd.php?id=".$editID."&message=BPD%20Saved"); } else { header("location:frm_bpd.php?id=".$editID."&message=An%20Error%20Occured"); }*/ ?> frm_bpd Table: -- phpMyAdmin SQL Dump -- version 4.1.4 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Feb 10, 2014 at 01:36 AM -- Server version: 5.6.15-log -- PHP Version: 5.4.24 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- -- Database: `omni` -- -- -------------------------------------------------------- -- -- Table structure for table `frm_bpd` -- CREATE TABLE IF NOT EXISTS `frm_bpd` ( `bpdID` int(11) NOT NULL AUTO_INCREMENT, `backflowID` varchar(255) DEFAULT NULL, `jobDetailID` int(11) DEFAULT NULL, `bpdOnsite` tinyint(11) DEFAULT '0', `bpdLocation` varchar(255) DEFAULT NULL, `bpdMake` varchar(255) DEFAULT NULL, `bpdModel` varchar(255) DEFAULT NULL, `bpdSerial` varchar(255) DEFAULT NULL, `bpdSize` int(11) DEFAULT NULL, `protectionType` tinyint(11) DEFAULT NULL, `bpdType` tinyint(4) DEFAULT NULL, `protectionLvl` tinyint(4) DEFAULT NULL, `wmNo` varchar(255) DEFAULT NULL, `wmSize` int(11) DEFAULT NULL, `wmLocation` varchar(255) DEFAULT NULL, `sprinklers` tinyint(11) DEFAULT NULL, `drinkingTaps` tinyint(11) DEFAULT NULL, `longitude` varchar(255) DEFAULT NULL, `latitude` varchar(255) DEFAULT NULL, `accuracy` int(11) DEFAULT NULL, `activity` tinyint(11) DEFAULT NULL, `permisionTTOW` tinyint(11) DEFAULT NULL, `comments` varchar(255) DEFAULT NULL, `pass` tinyint(11) DEFAULT NULL, UNIQUE KEY `bpdID` (`bpdID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `frm_bpd` -- INSERT INTO `frm_bpd` (`bpdID`, `backflowID`, `jobDetailID`, `bpdOnsite`, `bpdLocation`, `bpdMake`, `bpdModel`, `bpdSerial`, `bpdSize`, `protectionType`, `bpdType`, `protectionLvl`, `wmNo`, `wmSize`, `wmLocation`, `sprinklers`, `drinkingTaps`, `longitude`, `latitude`, `accuracy`, `activity`, `permisionTTOW`, `comments`, `pass`) VALUES (1, NULL, 1328449, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), (2, NULL, 1328449, -1, '2', '3', '4', '5', 6, 1, 2, NULL, '7', 8, '9', -1, -1, NULL, '', 0, 2, -1, 'bla', -1); output of $data with print_r(); Array ( [bpdID] => 1 [jobDetailID] => 1328449 [backflowID] => [bpdOnsite] => -1 [bpdLocation] => some [bpdMake] => [bpdModel] => [bpdSerial] => [bpdSize] => [protectionType] => 0 [bpdType] => 0 [protectionLvl] => [wmNo] => [wmSize] => [wmLocation] => [sprinklers] => [drinkingTaps] => [longitude] => [latitude] => [accuracy] => [activity] => 0 [permisionTTOW] => [comments] => [pass] => ) i know it must be a typo somewhere but i just cant spot it, as i said the insert statement works fine, and no errors are being thrown. am i just not using the UPDATE statement correctly? any help would be greatly appreciated.
  22. Hi, Although I have been programming for a long time now I have been asked to help a friend out with some PHP and MySql (never touched either of them before this week) I find some tasks which should be obvious to me are a little alien. My problem is that I want to read a record from a user file using the 'id' and then using data from that record to read 1 or 2 records from a contact/address file. I do not know whether it will be 1 or 2 records as this data is entered by the user. The sample code here shows the user file "valid_user" and the contact/address file called "carer", not having used this form of syntax before I am not 100% sure that the SELECT statement is correct except that it does produce the correct data when run (well the first contact details). $myid = $_SESSION['id']; try { $query="SELECT * FROM carer INNER JOIN valid_users ON valid_users.id = carer.valid_users_id WHERE valid_users.id='$myid'"; $stmt = $dbh->prepare($query); $stmt->execute(); $count = $stmt->rowCount(); $row = $stmt->fetch(PDO::FETCH_ASSOC); $myfirstname = $row['firstname']; $mysurname = $row['surname']; $myaddress1 = $row['address1']; $myaddress2 = $row['address2']; $mytown = $row['town']; $mycounty = $row['county']; $mypostcode = $row['postcode']; $myhome = $row['landline']; $mymobile = $row['mobile']; $myemail = $row['email']; $myecontact = $row['econtact']; $myephone = $row['ephone']; This gets me details for the first contact, which is displayed quite happily but I do not understand how I go about fetching the 2nd contact record (if there is one). I understand I could use fetchAll but I cant then work out how i populate the variables for both the first contact and the second contact when the variables are not the same i.e. the firstname field in "contact" record 1 will populate $myfirstname whereas the firstname field in "contact" record 2 will populate $myfirstname2. It is done this way because I am displaying both sets of contact details on the screen. In my past experience I would just do a Read Next to get the second contact record but obviously no such syntax is available. I also use the record count later on in the program. I know this probably has an easy answer but all the documentation I have read want to talk about apples and pears and whether they are red or yellow and then shows you how to print the array without explaining how you get the separate elements of the array in to variables. Any help would be appreciated
  23. Someone gave me a script that works - but it doesn't work for me. I've been trying to debug it, but I'm striking out. First, let's start with a simple query: $sql= "SELECT COUNT(URL) AS num FROM people WHERE URL = :MyURL"; It works, where a URL is MySite/Carl_Sagan and $MyURL = 'Carl_Sagan' I have several similar queries for various websites and sections. I want to try to merge everything into a new website that will function kind of like a mini encyclopedia. So I use UNION ALL to link several queries together, like this... $sql = "SELECT SUM(num) FROM ( SELECT COUNT(URL) AS num FROM pox_topics WHERE URL = :MyURL UNION ALL SELECT COUNT(URL) AS num FROM people WHERE URL = :MyURL UNION ALL SELECT COUNT(Taxon) AS num FROM gz_life WHERE Taxon = :MyURL ) AS X"; $stmt = $pdo->prepare($sql); $stmt->bindParam(':MyUrl',$MyURL,PDO::PARAM_STR); $stmt->execute(); $Total = $stmt->fetch(); switch($Total['num']) { case 1: // ETC.
  24. Hi guys. I have following code to delete particular row from a table based on the title. But how can I delete all data from the table? <?php require 'connpdo.php'; $naslov = $_POST['naslov']; #DELETE DATA //delete some data $sqlInsert = 'DELETE FROM bloging WHERE title=:title'; $preparedStatement = $conn->prepare($sqlInsert); $preparedStatement->execute(array(':title' => $naslov)); //REDIRECT TO HOME PAGE header('Location: http://localhost/ITAPHP/index.php'); ?> So I would need something which would say DELETE * FROM bloging...Basically I have this table bloging with 3 fields id, title and text, and above code will identify specific post based on the title and delete that particular post. But I need button to delete all posts, to empty table. Thank you in advance!
  25. Hi guys! I have a slight problem. When I pass values as variables to a sql statement it doesnt work. This is the example: THIS WORKS: <?php require 'DB/dbinc.php'; try { // Connect and create the PDO object $conn = new PDO("mysql:host=$dbhost; dbname=$dbname", $usernm, $dbpass); $conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8 // changes data in "text" and "text" where title = some title $sql = "UPDATE bloging SET title='Novi Title', tekst='Novi tekst' WHERE title='Update post'"; $count = $conn->exec($sql); $conn = null; // Disconnect } catch(PDOException $e) { echo $e->getMessage(); } // If data added ($count not false) displays the number of rows added if($count !== false) echo 'Number of rows added: '. $count; ?> THIS DOES NOT WORK <?php require 'DB/dbinc.php'; $oldTitle = 'Stari naslov'; $nTitle = 'novinaslov'; $nText = 'novitekst'; try { // Connect and create the PDO object $conn = new PDO("mysql:host=$dbhost; dbname=$dbname", $usernm, $dbpass); $conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8 // changes data in "text" and "text" where title = some title $sql = "UPDATE bloging SET title=$nTitle, tekst=$nText WHERE title=$oldTitle"; $count = $conn->exec($sql); $conn = null; // Disconnect } catch(PDOException $e) { echo $e->getMessage(); } // If data added ($count not false) displays the number of rows added if($count !== false) echo 'Number of rows added: '. $count; ?> I don't get it why it wont accept variable instead of string text as a value? Thanx in advance!
×
×
  • 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.