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. Hello. I am new. I have simple two step process I want to be done. When it does work the webpage keeps going (im guessing it's an endless loop)... I can't seem to get it to work: I know there's something I'm missing about this PDO array stuff. <?php include("database.php"); $time_ago = strtotime("-1 minute"); /*find subscribers over a month old with the thirtydaysubs table*/ $checker = "SELECT emailaddress FROM aa_thirtydaysubs WHERE subscribedate < $time_ago"; $sthandler = $database->prepare($checker); $sthandler->execute(); /*then move it to main list and remove from 30 day list*/ $data = array(); $data = $sthandler->fetch(); if ($sthandler->columnCount()){ while($sthandler->fetchAll(PDO::FETCH_ASSOC) !== 0){ $email2 = $data->fetchColumn(0); $newlist= "2"; $updatelistid = "UPDATE zzemail_list_subscribers set listid = :newlist WHERE emailaddress = :email"; $sthandler3 = $database->prepare($updatelistid); $sthandler3->execute(array(':email' => $email2, ':newlist' => $newlist )); $clearars = "DELETE FROM aa_thirtydaysubs WHERE emailaddress= :email"; $sthandler6 = $database->prepare($clearars); $sthandler6->execute(array(':email' => $email2)); } } ?>
  2. 0down votefavorite I just converted a query that displays "bread crumbs" style navigation links to PDO: function get_path($dbh,$node,$TopnavTable, $TopnavName) { $stmt = $dbh->prepare("SELECT name FROM $TopnavTable WHERE $TopnavName = ?"); $stmt->bindValue(1,$node); $stmt->execute(); $stmt->setFetchMode(PDO::FETCH_ASSOC); $row = $stmt->fetch(); $path = array_merge(get_path($pdo,$row['Parent'], $TopnavTable, $TopnavName), $path); return $path ; } I also figured out a way to display the results: $Path2 = explode("/", $path); $Path2[1] = '<a href="/Topics">'.$Path2[1].'</a>'; $Path2[2] = '<a href="/Topics/'.$Path2[2].'">'.$Path2[2].'</a>'; $Path2[3] = '<span class="navHere"><b>'.$Path2[3].'</b></span>'; echo join( $Path2, ' > ' ); However, it only works only if I'm working with an array consisting of three segments. For example, I'm viewing the URL MySite/Topics/Washington/Governor, which displays the following bread crumbs trail: Topics > Washington > Governor If I view MySite/Washington, it should display... Topics > Washington But I get an error message: Undefined offset: 3, plus there's a trailing arrow (>) after Washington. So I'm trying to figure out how to make this work with any number of segments - 2, 3, 6, etc. Regardless of the number of segments, I'd like the last segment to be unlinked. (I'm going to further put it inside a span.) Does anyone have any tips? (If there's a completely different way of doing it that's better, I'd love to hear about it.)
  3. Wow I have to say its been a long time since I posted here but I do need alittle help so here we go: I got this script or created most of it (I dont remember) for me to connect mysql using PDO. The script works fine exept when i try to update a column in my db. now i get no errors but it does not update. $superglobals = array($_POST); foreach ($superglobals as $value){ foreach ($value as $k => $v){ $post[$k]=$v; } } $sql = "UPDATE ".DB_PREFIX."_dbase SET value = :value WHERE key = :key"; foreach ($post as $key => $value) { $bind = array("value"=> $value, "key"=>$key); $db->execute($sql, $bind) or die($db->error()); } I have upload the db class and gave you what im trying to do please help Here is the database CREATE TABLE db_dbase ( key text, value text ) database.php
  4. I am trying to get all the "posts" from a users friends list on their news feed. I'm trying to do so by getting all those posts where the user is the initiator_user_id and get all the posts from the friend_user_id then I want to get all the posts from initiator_user_id where the user's id is the friend_user_id. This is what I have that's messing up: $wallsql= $conn->prepare('SELECT * FROM activity f INNER JOIN wp_bp_friends n1 ON (n1.initiator_user_id=f.user_id) INNER JOIN wp_bp_friends n2 ON (n2.friend_user_id=f.user_id) WHERE (n1.friend_user_id=:userid) OR (n2.initiator_user_id=:userid) ORDER BY datetime DESC LIMIT 8'); $wallsql->bindParam(':userid', $_SESSION['uid']); $wallsql->execute(); Previously this works but it only gets the posts where the user is the initiator_user_id: $wallsql= $conn->prepare('SELECT * FROM activity f INNER JOIN wp_bp_friends n2 ON n2.friend_user_id=f.user_id WHERE n2.initiator_user_id=:userid ORDER BY datetime DESC LIMIT 8'); Any help would be much appreciated!
  5. How can i add total of user's following me? The code I currently have displays ALL the user's following me, instead of saying *numbers of user's following me* <?php $friends = Friends::getFriendsForUser($data->id); if (count($friends) > 0) { $db = DB::getInstance(); foreach($friends as $friend_id) { $friend = $db->query('SELECT name, username FROM users WHERE id = ?', array($friend_id)); if ($friend->count() == 1) { echo '<table> <tr> <td><img src="images/avatar.png"></td> <td><a href="profile.php?user='.escape($friend->first()->username).'">'.$friend->first()->name.'</a></td> </tr> </table>'; } } } else { echo 'Not following anyone.'; } ?>
  6. I've been looking at this for a bit and can't seem to figure what's going on? I have used this code before and never had this issue.... I'm tryig to populate a dropdown menu from a MySql DB. The dropdown menu seems to skip the first array... I attached a screenshot that hopefully show's what I'm talking about.. any thoughts?
  7. I'm having a problem with PHP and a stored procedure in SQL Server 2005. I haven't really touched stored procedures before and haven't used them with php. I can't retrieve a value from a table that I know is definitely there. I have a simple login table, what I want the stored procedure to do is to take a username as an input and then output that user's password salt. I want the stored procedure to use parameterised values to avoid SQL injection. What happens at the moment is when the php page is run, nothing is returned and the SQL Profiler displays the following error: User Error Message: Incorrect Syntax near '@Username' While this error message should tell me something is wrong, I can't for the life of me see where the incorrect syntax is. Copy of the Php: $user = "usercm"; $password ="cmuserpassword"; try{$conn = new PDO("odbc:DRIVER={SQL Server Native Client 10.0};SERVER=TestingServer;DATABASE=TestingDatebase;",$user,$password);} catch(PDOException $e){echo "oh no";} $username = "sdct"; $prepusp = $conn->prepare("EXEC uspReturnSalt(?,?)"); $prepusp->bindParam(1, $username, PDO::PARAM_STR); $prepusp->bindParam(2, $usersalt, PDO::PARAM_STR, 450); $prepusp->execute(); Copy of the Stored Procedure: ALTER PROCEDURE [dbo].[uspReturnSalt] @Username NVARCHAR(100), @Usersalt NVARCHAR(450) OUTPUT AS BEGIN DECLARE @sqlcmd NVARCHAR(MAX); DECLARE @params NVARCHAR(MAX); SET @sqlcmd = N'SELECT @Usersaltone = salt FROM CMUsers WHERE username = @Usernameone'; SET @params = N'@Usernameone NVARCHAR(100), @Usersaltone NVARCHAR(450) OUTPUT'; EXECUTE sp_executesql @sqlcmd, @params, @Usernameone = @Username, @Usersaltone = @Usersalt OUTPUT; END To clarify, the server this is on runs Windows 2003 so I cannot use the sqlsrv drivers as they require SQL Server Native Client 2012 which is incompatible. It is impossible to upgrade the operating system (server isn't mine) so I can't use any php drivers that require SQL Server Native Client 2012. If anyone could help I would be eternally grateful. Here is the sql profiler messages before and after that error: RPC:Completed | exec [sys].sp_sproc_columns_90 N'uspReturnSalt' ,@ODBCVer=3 RPC:Starting | declare @p1 int set @p1 =NULL exec sp_prepare @p1 output,N'@Username nvarchar(100),@P2 text OUTPUT' ,N'EXEC uspReturnSalt(@Username,@P2 OUTPUT)' ,1 select @p1 Exception | Error: 102, Severity: 15, State: 1 User Error Message | Incorrect syntax near '@Username'. SP:CacheMiss | (@Username nvarchar(100),@P2 text OUTPUT)EXEC uspReturnSalt(@Username,@P2 OUTPUT) Exception | Error: 8180, Severity: 16, State: 1 User Error Message | Statement(s) could not be prepared RPC:Completed | declare @p1 int set @p1=NULL exec sp_prepare @p1 output, N'@Username nvarchar(100),@P2 text OUTPUT' ,N'EXEC uspReturnSalt(@Username,@P2 OUTPUT)',1 select @p1
  8. Hello, I have a little problem. This is what I want to achive: I have 2 mysql tables (categories, channels), the channel table has a cat_id in it. I want to update/edit a product and place it in another category but the code that I've made shows just one catedory (id=1) even if the product has a parent id of 5. try { //prepare query $query = "select channel_id, name, category_id from channels where channel_id = ? limit 0,1"; $stmt = $pdo->prepare( $query ); //this is the first question mark $stmt->bindParam(1, $_REQUEST['id']); //execute our query $stmt->execute(); //store retrieved row to a variable $row = $stmt->fetch(PDO::FETCH_ASSOC); //values to fill up our form $channel_id = $row['channel_id']; $name = $row['name']; $category_id = $row['category_id']; }catch(PDOException $exception){ //to handle error echo "Error: " . $exception->getMessage(); } $query2 = "SELECT * FROM categories"; $stmt2 = $pdo->prepare( $query2 ); $stmt2->execute(); $results = $stmt2->fetchAll(PDO::FETCH_ASSOC); ?> <!--we have our html form here where new user information will be entered--> <form action='#' method='post' border='0'> <table> <tr> <td>Channel Name</td> <td><input type='text' name='name' value='<?php echo $name; ?>' /></td> </tr> <tr> <td>Category</td> <td> <?php foreach($results as $rows) {?> <select name="fileselect"> <option name='cat_id' value=" <?php echo $rows['category_id']; ?>"> <?php echo $rows['name']; ?></option> <!-- <input type='text' name='category_id' value='<?php //echo $category_id; ?>' /> --> <?php } ?> </select> </td> </tr> <tr> <td></td> <td> <!-- so that we could identify what record is to be updated --> <input type='hidden' name='channel_id' value='<?php echo $channel_id ?>' /> <!-- we will set the action to edit --> <input type='hidden' name='action' value='update' /> <input type='submit' value='Edit' /> </td> </tr> </table> </form> The update parte is ommited as it works if there is no dropdown, just a plain text input.
  9. I have a database class that uses PDO and it all works until i need to do an update where I increment the value What I have is a table and one of the columns is called 'counter' and I need to update this table every time a page is visited This is the function that handles all the PDO and creates the query /** * update * @param string $table A name of table to insert into * @param string $data An associative array * @param string $where the WHERE query part */ public function update($table, $data, $where) { ksort($data); $fieldDetails = NULL; foreach($data as $key=> $value) { $fieldDetails .= "`$key`=:$key,"; } $fieldDetails = rtrim($fieldDetails, ','); $sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where"); foreach ($data as $key => $value) { $sth->bindValue(":$key", $value); } $sth->execute(); } and this is how I call the function by passing parametres to the function $board = ucwords(str_replace('-',' ',$board)); $sql = "SELECT boardid from boards WHERE boardname = :board"; $rows = $this->db->select($sql, array(':board' => $board)); $postData = array( 'counter' => 'counter+1', ); $this->db->update('topics', $postData, "`topicid` = {$topic} AND `boardid` = {$rows[0]['boardid']}"); It fails the update with this error message The counter column is of type INT
  10. I have a MySQL database on justhost with a field called "category" that I want to use in a WHERE query. The database opens fine without any WHERE clause. It's only when I begin to use a WHERE clause that I begin to get into trouble. All the "Gurus" out there tell me I need to be shifting over to PDO, so here is my attempt to get up to speed. The previous page (select_category.php) had a form with a selection drop-down box for category. I addressed it in the next file (quiz.php) like this: $cat = $_POST['category']; Now I want to query the data: $db = new PDO('mysql:host=localhost;dbname=' . $dbname , $dbusername, $pass); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql->prepare("SELECT * FROM QuestionsAnswers WHERE category = " . $cat); //This is line 23 foreach ($db->query($sql) as $row) { print '<p>' . $row['question'] .' <br /> '. $row['displaystring'] . '</p>'; } but I'm getting errors: I have been around and around on this for two days. Does anybody see what I am obviously missing? Thanks.
  11. Is this the correct format to doing a MySQL full text search using PDO? I want to search about 4 tables for the same keyword and not sure of the syntax $count = "SELECT COUNT(*) FROM (SELECT t.boardid, t.topicid, 'messages' as mytable, topicname as title, message as content, MATCH(topicname, message) AGAINST(':keywords*' IN BOOLEAN MODE) as score FROM topics t INNER JOIN messages m ON t.topicid=m.topicid WHERE MATCH(topicname, message) AGAINST(':keywords*' IN BOOLEAN MODE) UNION ALL SELECT id,'', 'news' as mytable,title, content, MATCH(title, content) AGAINST(':keywords*' IN BOOLEAN MODE) as score FROM news WHERE MATCH(title, content) AGAINST(':keywords*' IN BOOLEAN MODE) UNION ALL SELECT id,'', 'events' as mytable,title, content, MATCH(title, content) AGAINST(':keywords*' IN BOOLEAN MODE) as score FROM events WHERE MATCH(title, content) AGAINST(':keywords*' IN BOOLEAN MODE) UNION ALL SELECT id,'', 'blogs' as mytable,title, content, MATCH(title, content) AGAINST(':keywords*' IN BOOLEAN MODE) as score FROM blogs WHERE MATCH(title, content) AGAINST(':keywords*' IN BOOLEAN MODE)) a GROUP BY title"; $keywords = strtolower($_SESSION['keywords']); $sth = $dbh->prepare($count); $sth->bindValue(':keywords', $keywords, PDO::PARAM_STR); $sth->execute();
  12. I have a function that updates a database and it works fine for one record but i have a form which shows loads of rows with checkboxes and i want to do a batch update (I suppose the principle is the same for a batch delete). When I click a load of checkboxed and call the funtion to update, i get an error about an array to string conversion and also this error message "Unknown column 'Array' in 'where clause" I know a way around it but it's not great using a foreach loop to update the database but that involves loads of queries This is my function I call to update the database /** * update * @param string $table A name of table to insert into * @param string $data An associative array * @param string $where the WHERE query part */ public function update($table, $data, $where) { ksort($data); $fieldDetails = NULL; foreach($data as $key=> $value) { $fieldDetails .= "`$key`=:$key,"; } $fieldDetails = rtrim($fieldDetails, ','); $sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where"); foreach ($data as $key => $value) { $sth->bindValue(":$key", $value); } $sth->execute(); } This works public function newsEdit($data) { $postData = array( 'title' => $data['news_title'], 'content' => $data['news_content'], 'photo' => $data['imgname'], 'keywords' => $data['news_keywords'], 'alternate' => $data['alternate'] ); $this->db->update('news', $postData, "`id` = {$data['newsid']}"); } $data = array(); $data['news_title'] = $_POST['news_title']; $data['news_content'] = $_POST['news_content']; $data['imgname'] = $_POST['imgname']; $data['news_keywords'] = $_POST['news_keywords']; $data['alternate'] = substr($_POST['imgname'],0,strrpos($_POST['imgname'], ".")); newsEdit($data); This doesn't public function newsArchive($ids) { $postData = array( 'archived' => 'Y' ); $this->db->update('news', $postData, "`id` IN ({$ids})"); } newsArchive($_POST['id']); What have i got to change to get the update working?
  13. Hello everyone.. i am stuck with following code and i want to use it in PDO plz help me if($number>0) { $id=mysql_result($result,0,"id"); $_SESSION['id']=$id; somepage.php }
  14. Hello, can someone please let me know if my code here is wrong? Im trying to upgrade old mysql to PDO. Just a simple update command and on a few values if the $variable = "" then make the value null in DB. thank you try{ $sql1="UPDATE newone SET corating=:corating, cotarg=:cotarg, coclose=:coclose, ROI=:ROI, est1=:est1, est2=:est2, basicos=:basicos, mktcap=:mktcap, coNav=:nav, WHERE coID=:coID"; $q1 = $dbh->prepare($sql1); $q1->execute(array( ':corating'=>$corating, ':cotarg'=>$cotarg, ':coclose'=>$coclose, ':ROI'=>$ROI, ':est1'=>isset($est1) ? $est1 : null, ':est2'=> isset($est2) ? $est2 : null, ':basicos'=>$basicos, ':mktcap'=>$mktcap, ':coNav'=>isset($nav) ? $nav : null, ':coID'=>$coID, )); } catch(PDOException $e) { echo 'ERROR: ' . $e->getMessage(); }
  15. LAMP environment, PHP 5.4.13, MySQL 5.5.30. Code snippet: $db = new PDO('mysql:host=localhost;dbname=test',$username,$password); $sql="INSERT INTO `atable`( `user`, `expires`, `approved_by`,... ) VALUES ( :auser, :aexpires, :aapproved_by,... )"; $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $stmt = $db->prepare($sql); $stmt->bindValue(':auser', $buser, PDO::PARAM_STR); $stmt->bindValue(':aexpires', $bexpires, PDO::PARAM_STR); $stmt->bindValue(':aapproved_by', $bmyNull, PDO::NULL_EMPTY_STRING); ... $stmt->exec($sql) or die(print_r($db->errorInfo(), true)); Error: Fatal error: Call to undefined method PDOStatement::exec() in ... Any insights greatly appreciated!
  16. Hello all, I am trying to make a determination about the best way to move forward with my database code for both personal projects and for the company I work for. For my own projects, I used to use mysql functions but have started to switch over to PDO. The company I work for is still using mysql functions and they are a bit wary about switching over to either mysqli or pdo, as they have a lot of code to go through and they don't want to make a bad decision. So I started working on a database class that would replicate all of the mysql functions they were used to (fetch_assoc, fetch_array, num_rows, etc) and decided to make it so that, via a config, you could use mysqli OR pdo and then, in each function, it would do it's best to get the expected result. This way, the code for the company would only ever have to do something like: $db->query($sql); if($db->num_rows() > 0) etc... But the more I read up on PDO (which I have been using in a more proceedural way), it seems like this is already a wrapper, so in effect I'm wrapping a wrapper. So, bottom line, what are others doing to future proff their database code? I like the idea of a class with generic function names, because if there is ever another style to use (mysqlii?) we can just write up the proper functions inside of the existing class and they'll work without a hitch. But is this something that pdo already delivers? I know it's good for dealing with multiple types of databases (mysql, mssql, oracle) but this company will only ever be working with mysql, so I don't have to go overboard with considerations for that. Thanks for any help/advice! JD
  17. Hi, I am trying to get the rank of a user in a database, based on his score, so when the user logs in he can see his rank. I am using this to build a list of all users ordered by their score for a different section. $stmt = $dbh->query("SELECT * FROM $table ORDER BY score DESC"); $rank = 0; while($uid = $stmt->fetchObject()) { $rank++; echo $uid->uname ."is ranked". $rank; }; How can I get ONLY a users rank in the db based on his ID number, if I have a table like, . | user | ID | score | Jim | 2568 | 80 Pete | 5693 | 115 Sam | 3258 | 569 George | 7412 | 30 the ID numbers are a unique key If Jim logs in today he will see: Your Current Rank is 3 I am using PHP with PDO on a MySQL table. Thanks!
  18. I am not a jquery guru in any sense, so I am seeking some help with the below code. What I am trying to do, is populate two input fields, based on what is selected from a dropdown field via a database call. When I select a term from the dropdown, I want the term start date and term end date to populate in the appropriate fields. First here is my form: <form class="form-horizontal margin-none" action="<?=BASE_URL;?>form/runSection/" id="validateSubmitForm" method="post" autocomplete="off"> <div class="control-group"> <label class="control-label"><font color="red">*</font> <?php _e( _t( 'Term' ) ); ?></label> <div class="controls"> <select style="width:100%;" name="termCode" id="select2_10" required> <option value=""> </option> <?php table_dropdown('term', 'termCode', 'termName'); ?> </select> </div> </div> <div class="control-group"> <label class="control-label"><?php _e( _t( 'Term Start/End' ) ); ?></label> <div class="controls"> <input type="text" name="termStartDate" id="termStartDate" disabled class="span6" required /> <input type="text" name="termEndDate" id="termEndDate" disabled class="span6" required /> </div> </div> Second here is the javascript section: <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#select2_10').live('change', function(event) { $.ajax({ type : 'POST', url : '<?=BASE_URL;?>section/runTermLookup/', dataType: 'json', data : $('#validateSubmitForm').serialize(), cache: false, success: function( data ) { for(var id in data) { $(id).val( data[id] ); } } }); }); }); </script> Third, here is the method from my controller which passes the $_POST['termCode'] to the method of the same name found in the model: public function runTermLookup() { if(!$this->_auth->isUserLoggedIn()) { redirect( BASE_URL ); } $data = array(); $data['termCode'] = isPostSet('termCode'); $this->model->runTermLookup($data); } Lastly, here is the method from my model: public function runTermLookup($data) { $bind = array(":term" => $data['termCode']); $q = DB::inst()->select( "term","termCode = :term","termID","termStartDate,termEndDate", $bind ); $r = $q->fetch(\PDO::FETCH_ASSOC); $json = array( 'input#termStartDate' => $r['termStartDate'], 'input#termEndDate' => $r['termEndDate'] ); echo json_encode($json); } I've been looking at this for hours, so a fresh pair of eyes is greatly appreciated. Thank you.
  19. I have a form which has multi-value select fields (Bootstrap) in which I can use to submit an array of data to the database. Now, the issue is I am having trouble retrieving that array with json_decode(). The issue is my array format for returning values: <?php echo json_decode( $this->prog[0]['schoolKey']) ); ?> When echoing out the above, I get the follow error message: "stripslashes() expects parameter 1 to be string, array given in ..." I know there is a easy solution, but I've been working 12 hours long and I can barely see straight. Any help with this is greatly appreciated.
  20. I am changing my test code from mysqli to PDO. It worked for one of my forms but the other I racking my brain as to why it isn't. I have stripped it down, found a few typos but array 0000 error is occurring and I am unsure how to resolve it. Can you help? James connection $dbtype = "mysql"; $dbhost = "localhost"; $dbname = "mydb1"; $dbuser = "myusr1"; $dbpass = "mp1"; try { // database connection $conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); $conn -> exec('SET CHARACTER SET utf8'); } catch(PDOException $e) { echo 'There was a problem'; } php $sql = "UPDATE catalogue SET title=:title, manufacturer=:manufacturer WHERE id=:id"; $q = $conn->prepare($sql); $q->bindParam(':id',$_POST['id'], PDO::PARAM_INT); $q->bindParam(':title',$_POST['title'], PDO::PARAM_STR); $q->bindParam(':manufacturer',$_POST['manufacturer'], PDO::PARAM_INT); if ($q->execute()){ echo "Saved successfully"; } else { echo "<br/> Crap, something went wrong <br/>"; //just for testing echo $sql." <br/>"; print_r($_POST); print_r($conn->errorCode()); echo "<br/>"; print_r($conn->errorInfo()); echo "<br/>"; } output Crap, something went wrong UPDATE catalogue SET title=:title, manufacturer=:manufacturer WHERE id=:id Array ( [title] => Madinoz Pty Ltd [manufacturer] => 71 [media_id] => 1 [category_id] => 17 [subcategory_id] => Please Select [notes] => This is some text. [keywords] => Hardware, Handles, Hooks, Rails, Fittings, [save] => Save [id] => 2 ) 00000 Array ( [0] => 00000 [1] => [2] => )
  21. I am trying to call a stored procedure that accepts parameter inserts. The original query was being run from asp and looked like this: EXEC [SearchForXML6b] @sessionID = 973543, @LineID = 892245, @SortOrder = 'YearPublished DESC, SortTitle ASC', @PageNumber = 1, @RecordsPerPage = 20 I am redesigning the website in PHP, and am using the PDO method for querying the database. I am using a windows server, but have configured php to work on it, and can return simple selects from the db using pdo no problem. From looking around for help for many hours, the accepted way to do what I need seems to be to do something like this: $sql = "{:retval = CALL SearchForXML6b (@sessionID = 973543, @LineID = 892245, @SortOrder = 'YearPublished DESC, SortTitle ASC', @PageNumber = 1, @RecordsPerPage = 20)}"; $stmt = $this->c->prepare( $sql ); $stmt->bindParam('retval', $retval, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, 4); However this isn't working. I have tried using EXEC instead of CALL but apparently PDO doesn't accept this. I have heard talk of installing OBDC but it seems to be more of a LINUX focused driver. Does anyone know if it is possible to run stored procedures with my configuration? Note: In SQL Server Management Studio, the SQL executes perfectly when using 'EXEC', but gives an error when trying to use 'CALL' as I don't think it's valid TSQL. Thanks in advance
  22. Well I am having the worst weekend ever. I have been working on this code all day and google is not my friend today. So here is the problem, I am trying to write a form that is basically keeping records of people who have stayed as guest and what meals they ate (breakfast, lunch, dinner, midnight snack). So the html form is pretty simple, and I have a few checkboxes and a little javascript to add more rows if there are more guest. Everything is working fine, but the checkboxes values are killing me. Basically if the box isnt checked than do what? Anyway my insert isnt working at all Anyway here is some basic coding Html form for checkboxes: <td><input type="checkbox" name="breakfast[]" /></td> <td><input type="checkbox" name="lunch[]" /></td> <td><input type="checkbox" name="dinner[]" /></td> <td><input type="checkbox" name="midnight[]" /></td> <td><input type="checkbox" name="lodging[]"/></td> <td><input type="text" name="guestName[]"/></td> So as you can see checkboxes for the meals and a text input for the guest name. Now here is my function (please go easy I am new to pdo) public function createMeal($id,$table){ try{ //write query if(isset($_POST['guestName'])){ $guestName = $_POST['guestName']; $repName = $_POST['repName']; $repTitle = $_POST['repTitle']; if(isset($_POST['breakfast'])){ $breakfast = $_POST['breakfast']; } if(isset($_POST['lunch'])){ $lunch = $_POST['lunch']; } if(isset($_POST['dinner'])){ $dinner = $_POST['dinner']; } if(isset($_POST['midnight'])){ $midnight = $_POST['midnight']; } if(isset($_POST['lodging'])){ $lodging = $_POST['lodging']; } } foreach($guestName as $a => $b) { $query = "INSERT INTO meals(repName, repTitle, breakfast, lunch, dinner, midnight, lodging, guestName, masterLogID) VALUES (:repName, :repTitle, :breakfast, :lunch, :dinner, :midnight, :lodging, :guestName, :masterLogID)"; $stmt = $this->conn->prepare($query); $stmt->bindParam(':repName',$repName[$a]); $stmt->bindParam(':repTitle',$repTitle[$a]); $stmt->bindParam(':breakfast',$breakfast[$a]); $stmt->bindParam(':lunch',$lunch[$a]); $stmt->bindParam(':dinner',$dinner[$a]); $stmt->bindParam(':midnight',$midnight[$a]); $stmt->bindParam(':lodging',$lodging[$a]); $stmt->bindParam(':guestName',$guestName[$a]); $stmt->bindParam(':masterLogID',$masterLogID); // Execute the query $stmt->execute(); } echo "Record was saved."; }catch(PDOException $exception){ //to handle error echo "Error: " . $exception->getMessage(); } } I am getting the message "Record was saved", but nothing is in the table. Any help is greatly appreciated
  23. I have a simple function public function showtrips($id,$table){ $sql="SELECT * FROM $table WHERE id = :id ORDER BY id DESC"; if(!$stmt = $this->conn->prepare($sql)){ // prepare failed echo "<pre>Prepare failed:\n"; print_r($pdo->errorInfo()); echo "</pre>"; } else { if(!$stmt->execute(array(':id'=>$id))){ // execute failed echo "<pre>Execute failed:\n"; print_r($stmt->errorInfo()); echo "</pre>"; } else { while($r = $stmt->fetch(PDO::FETCH_ASSOC)){ $data[]=$r; } return $data; } } } and a for loop that calls this function foreach($obj->showtrips($id,"trips") as $value){ extract($value); echo <<<show <tr class="success"> <td>$departTime</td> <td>$departPlace</td> <td>$arriveTime</td> <td>$arrivePlace</td> <td>$numberOfPass</td> <td>$purpose</td> <td>$cargo</td> <td>$remarks</td> </tr> show; } In my foreach loop how can I first test if the return variable $data has any data in it?
  24. Hi Guys, (sorry for childish question - I am not a PHP developer - more likely hobbits, but trying hard and did research already - unfortunately without luck as I cannot see online example) I am having problems with PDO while creating web stats page (to be honest it is very difficult for me to explain what I am trying to achieve but here we go..). I have created a class which contains function below: // Function: getWebStats [Getting All ] public static function getWebStats( $numRows=1000000, $order="visitedOn DESC" ) { $conn = new PDO( DB_DSN, DB_UNAME DB_PASS ); $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM web_stats ORDER BY " . mysql_real_escape_string($order) . " LIMIT :numRows"; $st = $conn->prepare( $sql ); $st->bindValue( ":numRows", $numRows, PDO::PARAM_INT ); $st->execute(); $list = array(); while ( $row = $st->fetch() ) { $record = new cmsStats( $row ); $list[] = $record; } // Now get the total number of stats that matched the criteria $sql = "SELECT FOUND_ROWS() AS totalRows"; $totalRows = $conn->query( $sql )->fetch(); // Now get the total number of clicks that matched the criteria $sql = "SELECT visitedPageTitle, SUM(clickCount) AS totalClicks FROM web_stats GROUP BY visitedPageTitle"; $totalClicks = $conn->query( $sql )->fetch(); // Close connection $conn = null; // Return data array return ( array ( "results" => $list, "totalRows" => $totalRows[0], "totalClicks" => $totalClicks[0] ) ); I am calling this class: function viewStats() { $results = array(); // getList $data = cmsStats::getWebStats(); $results['ListWebStats'] = $data['results']; $results['totalRows'] = $data['totalRows']; $results['totalClicks'] = $data['totalClicks']; And trying to insert data below: <?php foreach ( $results['ListWebStats'] as $ListWebStats ) { ?> <ul class="chartlist"> <li> <a href="<?php echo $ListWebStats->visitedURL?>"><?php echo $ListWebStats->visitedPageTitle?></a> <span class="count">echo $results['totalClicks']</span> // This is there I am struggling, as it doesn’t returns data correctly <span class="index" style="width: 42%">(42%)</span> </li> </ul> Problem: I know that my code isn't correct (my function needs to be reviewed). I would be thankful if you could point me to right direction or tell me what I am doing wrong. Many thanks!
  25. Hi, I'm trying to make it so the user can enter some text into a text box and from there it will add a link and NOT override it. Here's my problem, I can't seem to get this statement to work correctly as I don't know how to put some kind of variable. Overall: I want it so it adds what ever has been entered into the INPUT tag and add into the correct user_id Please exuse my messy code, I'm just trying to get it to work before I tidy it up. Declared variables at the top of the document: class Users { public $user_id = null; public $username = null; public $email = null; public $password = null; public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w"; public $links = null; public function __construct( $data = array() ) { if( isset( $data['user_id'] ) ) $this->user_id = stripslashes( strip_tags( $data['user_id'] ) ); if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) ); if( isset( $data['email'] ) ) $this->email = stripslashes( strip_tags( $data['email'] ) ); if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) ); if( isset( $data['links'] ) ) $this->links = stripslashes( strip_tags( $data['links'] ) ); } Here's what I've made: public function addLink() { $correct = false; try{ $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $sql = "UPDATE `a8906507_members`.`list_members` SET `links` = <SOME KIND OF VARIABLE HERE> WHERE `list_members`.`user_id` = <SOME KIND OF VARIABLE HERE> LIMIT 1"; $stmt = $con->prepare( $sql ); $stmt->bindValue( "links", $this->links, PDO::PARAM_STR ); $stmt->execute(); }catch( PDOException $e ) { return $e->getMessage(); } } Here's my HTML that connects to the public function and executes it. <form action="" method="post" name="add_link" id="add_link"> <table border="0" id="table-add"> <th colspan="2"> <h1>Add a livestream</h1> <?php if( !(isset( $_POST['add_link'] ) ) ) { ?> <?php } else { $usr = new Users; $usr->storeFormValues( $_POST ); $errorMessage = ""; $error = false; if( $usr->addLink() ) { echo 'Channel added!'; $error = false; } else { $errorMessage .= "<li class='error'>Link can't be added</li>"; $error = true; } if($error) { echo($errorMessage); } } ?> </th> <tr> <td> <p>Channel Name:</p> </td> <td> <input type="text" name="channel-name" class="frm-style" /> </td> </tr> <th colspan="2"> <input class="frm-submit-add" name="add_link" type="submit" value="Add" /> <th> </tr> </table> </form> Help will be appreciated, thanks.
×
×
  • 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.