Search the Community
Showing results for tags 'pdo'.
-
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.
-
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.
-
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();
-
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?
-
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 }
-
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(); }
-
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!
-
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
-
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!
-
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.
-
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.
-
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] => )
-
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
-
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?
-
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!
-
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.
-
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
-
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']}"; }
-
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?
-
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.
-
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!
-
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
-
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); }
-
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?
-
What is the best way to connect to my database with PDO
youngboy84 posted a topic in PHP Coding Help
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