Search the Community
Showing results for tags 'pdo'.
-
hi, guys im trying to echo out results of a particular variable in my search_results.php file where i want to actually display the status of a friend which isn't showing up but is showing up in home.php page which handles the session user data. though i tried some variations it isn't of any help. The satusui variable which has the same logic works well but not the status_list variable for the friend in search_results page. please, help me to build the conversation system. code in status_list page:- $status2view=$project->statusView($f_uname); foreach($status2view as $row){ //print_r($row); $id=$row['update_id']; //gives output on var_dump $status_replies_=$project->reply2StatusView($id); foreach ($status_replies_ as $row) { $status_reply_id=$row['update_id']; $reply_author=$row['author']; $reply_d=htmlentities($row['update_body']); $reply_data= stripslashes($reply_d); $reply_t= htmlentities($row['title']); $reply_title= stripslashes($reply_t); $account_name=$row['account_name']; $reply_date=$row['time']; $reply_delete_button=""; if ($reply_author==$session_uname || $account_name==$session_uname) { $reply_delete_button="<li><span id='$status_reply_id' class='delete_reply_btn glyphicon glyphicon-remove'><a href='#' title='Delete this comment'>Remove X</a></span></li>"; } $status_replies="<div id='".$status_reply_id."' class='replyboxes'><b>Reply by<a href='search_results.php?u=".$reply_author."'>".$reply_author."</a>".$reply_date ."<legend>" . "<b class='caret'><button type='button' class='btn btn-danger dropdown-toggle pull-right' data-toggle='dropdown' aria-expanded='true' ><span class='glyphicon glyphicon-edit'></span> <ul class='dropdown-menu'>".$reply_delete_button." " . "<li><a href='#' class='hidden_text_area glyphicon glyphicon-pencil' title='Edit this comment' >Edit</a></li>" . "<li><a href='report.php?u='".$reply_author."'>Report</a><li></ul>" . "</button></b></legend><br>". html_entity_decode($reply_data).""; } } foreach ($status2view as $row1) { //got values here. $updateid=$row1['update_id']; $account_name=$row1['account_name']; $os_id=$row1['os_id']; $author=$row1['author']; $post_date=$row1['time']; $title= stripslashes($row1['title']); $data= stripslashes($row1['update_body']); $statusdeletebutton=''; //insert_status_ui script to get message. if($isowner=="yes"){ $statusui_edit="<div type='".$updateid."' class='hidden_edit_4_session session_editor".$updateid." jumbotron'>" . "<a href='#' type='".$updateid."' class='pull-right close_edit' title='Close without editing'>Close X</a>" . "<input type='text' class='form-control title_s_edit title_s_".$updateid."' name='status_title' value='".html_entity_decode($title)."' placeholder='Title' >" . "<div> </div>" . "<textarea id='wall_edit_1' type='".$updateid."' rows='5' cols='50' class='session_edit text_value_".$updateid."' wrap='hard' placeholder='whats up ".$session_uname."'> ".html_entity_decode($data)."</textarea><br>" . "<button style='float:right;' value='".$updateid."' type='a' class='btn btn-warning btn btn-large btn-lg post-s-edit'>Update</button></div>"; } elseif ($is_friend==TRUE&&$session_uname!=$f_uname) { $statusui_edit="<div type='".$updateid."' class='hidden_edit_4_friend friend_editor".$updateid." jumbotron'>" . "<a title='Close without editing' type='".$updateid."' href='#' class='pull-right close_edit_f'>Close X</a>" . "<input type='text' class='form-control title_f_edit title_f_".$updateid."'' name='status_title' value='".html_entity_decode($title)."' placeholder='Title'><br>" . "<div> </div>" . "<textarea id='wall_edit_2' value='' type='".$updateid."' rows='5' cols='50' class='friend_edit update_friend_".$updateid."' placeholder='hi ".$session_uname." want to say something to ".$f_uname.". '>" .html_entity_decode($data)."</textarea><br>" . "<button style='float:right;' value='".$updateid."' type='c' class='btn btn-warning btn-large btn-lg post-f-edit'>Update</button></form>"; } if ($author==$session_uname || $account_name==$session_uname) { $statusdeletebutton='<li>' . '<a href="#" type="'.$updateid.'" class="delete_4_session hidden_text_delete_'.$updateid.' glyphicon glyphicon-trash delete_reply_btn" title="Delete this status and its replies">Remove</a></li>'; } if($isowner=="yes"){ $status_list= $statusui_edit.'<div attr="'.$updateid.'" type="'.$updateid.'" class="statusboxes status_'.$updateid.' jumbotron">' . '<h3 style="color:black; margin-bottom:5px; margin-top:5px;" class="pull-left">' . '<div id="'.$updateid.'" class="title_s_2copy" value="'.html_entity_decode($title).'">'.html_entity_decode($title).'</div></h3>' . '<span class="pull-right">' . '<div class="dropdown">' . '<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" >' . '<span class="glyphicon glyphicon-edit"></span></button>' . '<ul class="dropdown-menu">' . '<li><a href="#" attr="'.$updateid.'" type="'.$updateid.'" class="edit_4_session hidden_text_edit glyphicon glyphicon-pencil" title="Edit this status" >Edit</a></li>'.$statusdeletebutton.'</ul></div></span><br><hr>' . '<legend><span class=" data_s_2copy" type="'.$updateid.'" value="'.html_entity_decode($data).'" style="font-size:9px; margin-bottom:0px; margin-top:0px; text-align:left; color:black;">' . html_entity_decode($data).'</span><br><br></legend><b style="text-align:right; color:black;"><small>Posted by:- <a href="search_results.php?u='.$author.'">'.$author. '</a> '.$post_date.'</small></b>' . '<br>'.$status_replies.'<br>'; if ($is_friend==TRUE||$session_uname==$f_uname) { $status_list.= '<textarea id="'.$updateid.'" class="status_update input-custom2" placeholder="comment\'s"></textarea>' . '<button id="'.$updateid.'" type="b" class="btn btn-warning pull-right btn-sm">Reply</button></div>'; } echo $status_list; }elseif ($is_friend==TRUE&&$session_uname!=$f_uname) { $status_list= $statusui_edit.'<div attr="'.$updateid.'" type="'.$updateid.'" class="statusboxes status_'.$updateid.' jumbotron">' . '<h3 style="color:black; margin-bottom:5px; margin-top:5px;" class="pull-left">' . '<div id="'.$updateid.'" class="title_s_2copy" value="'.html_entity_decode($title).'">'.html_entity_decode($title).'</div></h3>' . '<legend><span class=" data_s_2copy" type="'.$updateid.'" value="'.html_entity_decode($data).'" style="font-size:9px; margin-bottom:0px; margin-top:0px; text-align:left; color:black;">' . html_entity_decode($data).'</span><br><br></legend><b style="text-align:right; color:black;"><small>Posted by:- <a href="search_results.php?u='.$author.'">'.$author. '</a> '.$post_date.'</small></b>' . '<br>'.$status_replies.'<br>'; $status_list.= '<textarea id="'.$updateid.'" class="status_update input-custom2" placeholder="comment\'s"></textarea>' . '<button id="'.$updateid.'" type="b" class="btn btn-warning pull-right btn-sm">Reply</button></div></div>'; echo $status_list; } } code for search_results page where the statuslist is included:- if($isowner=="yes"){ $statusui="<div class='jumbotron'><input type='text' class='form-control title_s' name='status_title' placeholder='Title ' ><br>" . "<textarea id='wall_id_1' class='update_session' placeholder='whats up ".$session_uname."'>" . "</textarea>" . "<button style='float:right;' type='a' class='btn btn-warning btn btn-large btn-lg post-s'>Post</button></div>"; $statusui_edit="<div attr='".$updateid."' class='hidden_edit_4_session session_edit".$updateid." jumbotron'>" . "<a href='#' class='pull-right close_edit' title='Close without editing'>Close X</a>" . "<input type='text' class='form-control title_s_edit' name='status_title' value='".html_entity_decode($title)."' placeholder='Title' >" . "<div> </div>" . "<textarea id='wall_edit_1' class='session_edit' placeholder='whats up ".$session_uname."'> ".html_entity_decode($data)."</textarea><br>" . "<button style='float:right;' type='a' class='btn btn-warning btn btn-large btn-lg post-s-edit'>Update</button></div>"; } elseif ($is_friend==TRUE&&$session_uname!=$f_uname) { $statusui="<div class='jumbotron'><input type='text' class='form-control title_f' name='status_title' placeholder='Title'><br>" . "<textarea id='wall_id_2' type='c' class='status_4_friend' style='' placeholder='hi ".$session_uname." want to say something to ".$f_uname.". '>" . "</textarea><br>" . "<button style='float:right;' type='c' class='btn btn-warning btn-large btn-lg post-f'>Post</button></div>"; $statusui_edit="<div attr='".$updateid."' class='hidden_edit_4_friend friend_edit".$updateid." jumbotron'>" . "<a title='Close without editing' href='#' class='pull-right close_edit_f'>Close X</a>" . "<input type='text' class='form-control title_f_edit' name='status_title' value='".html_entity_decode($title)."' placeholder='Title'><br>" . "<textarea id='wall_edit_2' value='' class='update_4_expresspad'placeholder='hi ".$session_uname." want to say something to ".$f_uname.". '>" .html_entity_decode($data)."</textarea><br>" . "<button style='float:right;' type='c' class='btn btn-warning btn-large btn-lg post-f-edit'>Update</button>"; } ?> <div class="container-fluid"> <br><div class="row"> </div><br> <div class="row"> <div class="col-sm-2"> <p>Friends list:</p> <?php include_once 'notification/friend_list.php'; echo $friends_html; ?> </div> <div class="col-lg-8"> <div class="tab-content"> <ul class="nav nav-tabs"> <li class="active"><a href="#tabs-1" data-toggle="tab" class="profile">Profile</a></li> <li><a href="#tabs-2" data-toggle="tab"class="articles">Status</a></li> <li><a href="#tabs-4"data-toggle="tab" class="gallery_photos">Gallery</a></li> <li><a href="#tabs-5" data-toggle="tab" class="videos">Videos</a></li> </ul> <div id="tabs-1" class="tab-pane fade profile1 active in"> <?php echo '<table border="0"><tr width="20%"><td>Profile Photo</td><td>' . $friend_button . '</td></tr> <tr><td></td><td>' . $block_button . '</td></tr> <tr width="100%"><td width="20%"></td><td width="55%"><p>Full Name:' . $fname_s . ' ' . $lname_s . '<br> </td><td width="20%"></td></tr> </table>'; ?> </div> <div id="tabs-2" class="tab-pane fade articles">
-
hi, guys i have a problem in outputting the id in php. what i'm trying to do is create a article and when the user clicks the edit button the text area shows up for editing while the original article hides. i'm using both jquery and php to do it. the problem is that when the user clicks the edit button the hidden text area doesn't showup when i looked in to the browser source i found that the id is not outputting in the hidden textarea. so, please guide me on how to print the id in the hidden area. here is the code for jquery : $(".hidden_text_edit").click(function(){ var id=$(this).attr("id"); $(".hidden_edit_4_session").find("id").show(); var hide_status=$(".statusboxes").attr('type'); var title=$(".title_s_2copy").attr('type'); var data=$(".data_s_2copy").attr('type'); $(hide_status).hide(); //tinyMCE.get('.hidden_edit_4_session').setContent(data); $(".title_s_edit").val(title); }); $(".close_edit").click(function(){ $(".hidden_edit_4_session").hide(); var hide_status=$(".statusboxes").attr('div', 'type'); $(hide_status).show(); }); code for article and hidden text area logic: <?php if(isset($_SESSION['app'])){ $statusui="<div class='jumbotron'><input type='text' class='form-control title_s' name='status_title' placeholder='Title ' ><br>" . "<textarea id='wall_id_1' class='update_session' placeholder='whats up ".$session_uname."'>" . "</textarea>" . "<button style='float:right;' type='a' class='btn btn-warning btn btn-large btn-lg post-s'>Post</button></div>"; $statusui_edit="<div id=".$updateid." class='hidden_edit_4_session".$updateid." jumbotron'><a href='#' class='pull-right close_edit' title='Close without editing'>Close X</a><input type='text' class='form-control title_s_edit' name='status_title' value='".html_entity_decode($title)."' placeholder='Title' ><div> </div>" . "<textarea id='wall_edit_1' value='".html_entity_decode($data)."' class='session_edit' placeholder='whats up ".$session_uname."'>" . "" .html_entity_decode($data)."</textarea><br>" . "<button style='float:right;' type='a' class='btn btn-warning btn btn-large btn-lg post-s-edit'>Update</button></div>"; } elseif ($is_friend==TRUE&&$session_uname!=$f_uname) { $statusui="<input type='text' class='form-control title_f' name='status_title' placeholder='Title'><br>" . "<textarea id='wall_id_1' type='c' value='".html_entity_decode($data)." class='status_4_expresspad_friend' style='' placeholder='hi ".$session_uname." want to say something to ".$f_uname.". '>" . "</textarea><br>" . "<button style='float:right;' class='btn btn-warning btn-large btn-lg post-f'>Post</button><br><br><br><div> </div>"; $statusui_edit="<div class='hidden_edit_4_friend jumbotron'><a title='Close without editing' href='#' class='pull-right close_edit_f'>Close X</a><input type='text' class='form-control title_f_edit' name='status_title' value='".html_entity_decode($title)."' placeholder='Title'><br>" . "<textarea id='wall_edit_2' value='".html_entity_decode($data)."' class='update_4_expresspad'placeholder='hi ".$session_uname." want to say something to ".$f_uname.". '>" . "</textarea><br>" . "<button style='float:right;' type='c' class='btn btn-warning btn-large btn-lg post-f-edit'>Update</button>"; } ?> here is the code where the status list is outputting in a loop with the hidden text area's logic: <?php $status2view=$project->statusView($session_uname, $f_uname); //gives output on var dump #row vars to extract user's update data. foreach($status2view as $row){ $id=$row['update_id']; $status_replies_=$project->reply2StatusView($id); foreach ($status_replies_ as $row) { $status_reply_id=$row['update_id']; $reply_author=$row['author']; $reply_d=htmlentities($row['update_body']); $reply_data= stripslashes($reply_d); $reply_t= htmlentities($row['title']); $reply_title= stripslashes($reply_t); $account_name=$row['account_name']; $reply_date=$row['time']; $reply_delete_button=""; if ($reply_author==$session_uname || $account_name==$session_uname) { $reply_delete_button="<li><span id='$status_reply_id' class='delete_reply_btn glyphicon glyphicon-remove'><a href='#' title='Delete this comment'>Remove X</a></span></li>"; } $status_replies="<div id='".$status_reply_id."' class='replyboxes'><b>Reply by<a href='search_results.php?u=".$reply_author."'>".$reply_author."</a>".$reply_date ."<legend>" . "<b class='caret'><button type='button' class='btn btn-danger dropdown-toggle pull-right' data-toggle='dropdown' aria-expanded='true' ><span class='glyphicon glyphicon-edit'></span> <ul class='dropdown-menu'>".$reply_delete_button." " . "<li><a href='#' class='hidden_text_area glyphicon glyphicon-pencil' title='Edit this comment' >Edit</a></li>" . "<li><a href='report.php?u='".$reply_author."'>Report</a><li></ul>" . "</button></b></legend><br>". html_entity_decode($reply_data).""; } } foreach ($status2view as $row1) { //got values here. $updateid=$row1['update_id']; $account_name=$row1['account_name']; $os_id=$row1['os_id']; $author=$row1['author']; $post_date=$row1['time']; $title= $row1['title']; $data= $row1['update_body']; $statusdeletebutton=''; if ($author==$session_uname || $account_name==$session_uname) { $statusdeletebutton='<li>' . '<a href="#" id="'.$updateid.'" class="delete_4_session hidden_text_delete_'.$updateid.' glyphicon glyphicon-trash delete_reply_btn" title="Delete this status and its replies">Remove</a></li>'; } $status_list= '<div id="'.$updateid.'" type="'.$updateid.'" class="statusboxes jumbotron">' . '<h3 style="color:black; margin-bottom:5px; margin-top:5px;" class="pull-left"><div id="'.$updateid.'" class="title_s_2copy" value="'.html_entity_decode($title).'">'.html_entity_decode($title).'</div></h3>' . '<span class="pull-right">' . '<div class="dropdown">' . '<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" >' . '<span class="glyphicon glyphicon-edit"></span></button>' . '<ul class="dropdown-menu">' . '<li><a href="#" id="'.$updateid.'" type="'.$updateid.'" class="edit_4_session hidden_text_edit glyphicon glyphicon-pencil" title="Edit this status" >Edit</a></li>'.$statusdeletebutton.'</ul></div></span><br><hr><span class="pull-left data_s_2copy" id="'.$updateid.'" value="'.html_entity_decode($data).'" style="font-size:9px; margin-bottom:0px; margin-top:0px; text-align:left; color:black;">' . html_entity_decode($data).'</span><br><br><hr><b style="text-align:right; color:black;"><small>Posted by:- <a href="search_results.php?u='.$author.'">'.$author. '</a> '.$post_date.'</small></b>' . '<br>'.$status_replies.'<br>'.$statusui_edit; if ($is_friend==TRUE||$session_uname==$f_uname) { $status_list.= '<textarea id="'.$updateid.'" class="status_update input-custom2" placeholder="comment\'s"></textarea>' . '<button id="'.$updateid.'" type="b" class="btn btn-warning pull-right btn-sm">Reply</button></div>'; } echo $status_list; }
-
hi, guys im actually following a tutorial here and i'm perplexed with this error, where there is no output for one object inside a loop. since the tutorial is procedural code and im doing it in oop i dont know where im going wrong.please help me. the code for the complete article.php is here: <?php include_once '../includes/dbconfig.inc.php'; $status2view=$project->statusView($session_uname, $f_uname); //gives output on var dump #row vars to extract user's update data. for ($i= 0; $i >=0 ; $i++) { $id=array_column($status2view ,'update_id'); //gives output on var_dump if ($id==NULL) { break; }else { continue; } $status_replies_=$project->reply2StatusView($id[$i]); var_dump($status_replies_); //no output on var_dump while ($row = $status_replies_) { echo "<pre>"; var_dump($row); echo "</pre>"; $status_reply_id=$row['update_id']; $reply_author=$row['author']; $reply_d=htmlentities($row['update_body']); $reply_data= stripslashes($reply_d); $reply_t= htmlentities($row['title']); $reply_title= stripslashes($reply_t); $account_name=$row['account_name']; $reply_date=$row['time']; $reply_delete_button=""; if ($reply_author==$session_uname || $account_name==$session_uname) { $reply_delete_button="<li><span id='$status_reply_id' class='delete_reply_btn glyphicon glyphicon-remove'><a href='#' title='Delete this comment'>Remove X</a></span></li>"; } $status_replies="<div id='".$status_reply_id."' class='replyboxes'><div><b>Reply by<a href='search_results.php?u=".$reply_author."'>".$reply_author."</a>".$reply_date ."<legend>" . "<b class='caret'><button type='button' class='btn btn-danger dropdown-toggle pull-right' data-toggle='dropdown' aria-expanded='true' ><span class='glyphicon glyphicon-edit'></span> <ul class='dropdown-menu'>".$reply_delete_button." " . "<li><a href='#' class='hidden_text_area glyphicon glyphicon-pencil' title='Edit this comment' >Edit</a></li>" . "<li><a href='report.php?u='".$reply_author."'>Report</a><li></ul>" . "</button></b></legend><br>".$reply_data."</div></div>"; } } while ($row1 = $status2view) { for ($j = 0; $j >= 0; $j++) { $updateid=$row1[$j]['update_id']; $account_name=$row1[$j]['account_name']; $os_id=$row1['os_id']; $author=$row1['author']; $post_date=$row1['time']; $title= htmlentities($row1['title']); $data= htmlentities($row1['update_body']); if ($row1==NULL) { break; } $status_list='<fieldset><div id="'.$updateid.'" class="statusboxes"><div>' . '<legend><h3 class="pull-left">'.$title.'</h3><span class="pull-right">'.$statusdeletebutton.'</span></legend><br>' . $data.'<br><b>Posted by<small><a href="search_results.php?u='.$author.'">'.$author.'</a>'.$post_date.'</small></b>' . '<br><hr style="2px dashed #080808">'.$status_replies . '</div></div>'.$statusui_edit.'</fieldset>'; here is the code for the method: public function statusView($session_uname,$f_uname) { $sql="select * from updates where account_name=:either and type='a' or account_name=:either and type='c' order by time desc limit 20"; $stmth=$this->_db->prepare($sql); $stmth->bindValue(":either",($session_uname|$f_uname)); $stmth->execute(); return $stmth->fetchAll(PDO::FETCH_ASSOC); } public function reply2StatusView($updateid){ $stmth= $this->_db->prepare("select * from updates where update_id=:statusid and type='b' order by time asc"); $stmth->bindparam(":statusid", $updateid); $stmth->execute(); return $stmth->fetchAll(PDO::FETCH_ASSOC); }
-
Hi all. I don't know why this is happening. I have a scrip that backs up database. It works fine on database1 but when i use it on database2, it throws an error? Fatal error: Call to a member function fetch_row() on a non-object in $tableshema = $shema->fetch_row() ; both databases are on same domain. ps: even with another backup script still throws an error in database2 thanks ##################### //CONFIGURATIONS ##################### // Define the name of the backup directory define('BACKUP_DIR', 'cashBackup' ) ; // Define Database Credentials define('HOST', 'localhost' ) ; define('USER', 'username' ) ; define('PASSWORD', 'password' ) ; define('DB_NAME', 'database2' ) ; /* Define the filename for the Archive If you plan to upload the file to Amazon's S3 service , use only lower-case letters . Watever follows the "&" character should be kept as is , it designates a timestamp , which will be used by the script . */ $archiveName = 'mysqlbackup--' . date('d-m-Y') . '@'.date('h.i.s').'&'.microtime(true) . '.sql' ; // Set execution time limit if(function_exists('max_execution_time')) { if( ini_get('max_execution_time') > 0 ) set_time_limit(0) ; } //END OF CONFIGURATIONS /* Create backupDir (if it's not yet created ) , with proper permissions . Create a ".htaccess" file to restrict web-access */ if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ; if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ; // Create an ".htaccess" file , it will restrict direct access to the backup-directory . $content = 'deny from all' ; $file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ; $written = $file->fwrite($content) ; // Verify that ".htaccess" is written , if not , die the script if($written <13) die("Could not create a \".htaccess\" file , Backup task canceled") ; // Check timestamp of the latest Archive . If older than 24Hour , Create a new Archive $lastArchive = getNameOfLastArchieve(BACKUP_DIR) ; $timestampOfLatestArchive = substr(ltrim((stristr($lastArchive , '&')) , '&') , 0 , - ; if (allowCreateNewArchive($timestampOfLatestArchive)) { // Create a new Archive createNewArchive($archiveName) ; } else { echo '<p>'.'Sorry the latest Backup is not older than 24Hours , try a few hours later' .'</p>' ; } ########################### // DEFINING THE FOUR FUNCTIONS // 1) createNewArchive : Creates an archive of a Mysql database // 2) getFileSizeUnit : gets an integer value and returns a proper Unit (Bytes , KB , MB) // 3) getNameOfLastArchieve : Scans the "BackupDir" and returns the name of last created Archive // 4) allowCreateNewArchive : Compares two timestamps (Yesterday , lastArchive) . Returns "TRUE" , If the latest Archive is onlder than 24Hours . ########################### // Function createNewArchive function createNewArchive($archiveName){ $mysqli = new mysqli(HOST , USER , PASSWORD , DB_NAME) ; if (mysqli_connect_errno()) { printf("Connect failed: %s", mysqli_connect_error()); exit(); } // Introduction information $return = "--\n"; $return .= "-- A Mysql Backup System \n"; $return .= "--\n"; $return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n"; $return .= "--\n"; $return .= "-- Database : " . DB_NAME . "\n"; $return .= "--\n"; $return .= "-- --------------------------------------------------\n"; $return .= "-- ---------------------------------------------------\n"; $return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ; $return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ; $tables = array() ; // Exploring what tables this database has $result = $mysqli->query('SHOW TABLES' ) ; // Cycle through "$result" and put content into an array while ($row = $result->fetch_row()) { $tables[] = $row[0] ; } // Cycle through each table foreach($tables as $table) { // Get content of each table $result = $mysqli->query('SELECT * FROM '. $table) ; // Get number of fields (columns) of each table $num_fields = $mysqli->field_count ; // Add table information $return .= "--\n" ; $return .= '-- Tabel structure for table `' . $table . '`' . "\n" ; $return .= "--\n" ; $return.= 'DROP TABLE IF EXISTS `'.$table.'`;' . "\n" ; // Get the table-shema $shema = $mysqli->query('SHOW CREATE TABLE '.$table) ; // Extract table shema $tableshema = $shema->fetch_row() ; // Append table-shema into code $return.= $tableshema[1].";" . "\n\n" ; // Cycle through each table-row while($rowdata = $result->fetch_row()) { // Prepare code that will insert data into table $return .= 'INSERT INTO `'.$table .'` VALUES ( ' ; // Extract data of each row for($i=0; $i<$num_fields; $i++) { $return .= '"'.$rowdata[$i] . "\"," ; } // Let's remove the last comma $return = substr("$return", 0, -1) ; $return .= ");" ."\n" ; } $return .= "\n\n" ; } // Close the connection $mysqli->close() ; $return .= 'SET FOREIGN_KEY_CHECKS = 1 ; ' . "\n" ; $return .= 'COMMIT ; ' . "\n" ; $return .= 'SET AUTOCOMMIT = 1 ; ' . "\n" ; //$file = file_put_contents($archiveName , $return) ; $zip = new ZipArchive() ; $resOpen = $zip->open(BACKUP_DIR . '/' .$archiveName.".zip" , ZIPARCHIVE::CREATE) ; if( $resOpen ){ $zip->addFromString( $archiveName , "$return" ) ; } $zip->close() ; $fileSize = getFileSizeUnit(filesize(BACKUP_DIR . "/". $archiveName . '.zip')) ; $message = <<<msg <h4>BACKUP completed ,</h4> <p> The backup file has the name of : <strong> $archiveName </strong> and it's file-size is : $fileSize. </p> <p> This zip archive can't be accessed via a web browser , as it's stored into a protected directory.<br> It's highly recomended to transfer this backup to another filesystem , use your favorite FTP client to download the file . </p> msg; echo $message ; } // End of function creatNewArchive // Function to append proper Unit after a file-size . function getFileSizeUnit($file_size){ switch (true) { case ($file_size/1024 < 1) : return intval($file_size ) ." Bytes" ; break; case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1) : return round(($file_size/1024) , 2) ." KB" ; break; default: return round($file_size/(1024*1024) , 2) ." MB" ; } } // End of Function getFileSizeUnit // Funciton getNameOfLastArchieve function getNameOfLastArchieve($backupDir) { $allArchieves = array() ; $iterator = new DirectoryIterator($backupDir) ; foreach ($iterator as $fileInfo) { if (!$fileInfo->isDir() && $fileInfo->getExtension() === 'zip') { $allArchieves[] = $fileInfo->getFilename() ; } } return end($allArchieves) ; } // End of Function getNameOfLastArchieve // Function allowCreateNewArchive function allowCreateNewArchive($timestampOfLatestArchive , $timestamp = 24) { $yesterday = time() - $timestamp*3600 ; return ($yesterday >= $timestampOfLatestArchive) ? true : false ; } // End of Function allowCreateNewArchive
-
I have been using the below method to access my database for some time now and just wanted to make sure im doing the correct thing. My application runs perfectly but im just trying to improve my programming skills. The classes are all loaded in with an autoloader so in theory using the classes below I could just call: echo User::getUsername(1); Like I say it works fine I would just love some feedback about what other people do and suggestions on something that might run better or looks cleaner. class Db { private static $db_read; private static $db_write; public static method read(){ if( self::$db_read == null ){ //create new database connection is it doesnt exist self::$db_read = new PDO(); } return self::$db_read; } public static method write() { if( self::$db_write == null ){ //create new database connection is it doesnt exist self::$db_write = new PDO(); } return self::$db_write; } class User { public static function getUsername($user_id){ $d = Db::read()->prepare('select * from user where id = ? '); $d->execute( array($user_id) ); $user = $d->fetch(); return $user['username']; } }
-
hi, guys can any one say where im going wrong in this code as im not able to get to display friend lists in both search_results.php and home.php. the code in friend_list.php which is included in both home and search results page to display friends list: <?php $friends_html=""; $orlogic=""; $uname_s= \htmlentities($_GET['u']); $sql="select count(friend_id) from friends where friend_one=:uname_s and accepted='1' or friend_two=:uname_s and accepted='1'"; $stmt=$conn->prepare($sql); $stmt->bindparam(":uname_s", $uname_s); $stmt->execute(); $query_count=$stmt->fetchAll(PDO::FETCH_ASSOC); $friend_count=$query_count[0]; if ($friend_count<1) { $friends_html="$uname_s has no friends yet"; } else { $all_friends=array(); $sql="select friend_one, friend_two from friends where friend_two=:uname_s and accepted='1' order by rand()"; $stmt=$conn->prepare($sql); $stmt->bindparam(":uname_s",$uname_s); $stmt->execute(); while ($row =$stmt->fetchAll(PDO::FETCH_ASSOC)) { array_push($all_friends, $row[0]['friend_one']); } $sql1="select * from friends where friend_one=:uname_s and accepted='1' order by rand()"; $stmt1=$conn->prepare($sql1); $stmt1->bindparam(":uname_s",$uname_s); $stmt1->execute(); while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)) { array_push($all_friends, $row1['friend_two']); } $friendArrayCount= count($all_friends); foreach ($all_friends as $key => $user) { $orlogic .="uname='$user' OR"; } $orlogic1= chop($orlogic, "OR"); $sql2="select uname,avatar from user where :orlogic1"; $stmt2=$conn->prepare($sql2); $stmt2->bindparam(":orlogic1",$orlogic1); $stmt2->execute(); while ($row11 = $stmt2->fetchAll(PDO::FETCH_ASSOC)) { $friend_username=$row11[0]["uname"]; $friend_avatar=$row11[0]["avatar"]; if ($friend_avatar!=""){ $friend_pic='user/'.$friend_username.'/'.$friend_avatar; } else { $friend_pic='img/avatardefault.png'; } echo '<a href="search_results.php?u='.$friend_username.'"><img class="friendpics" src="'.$friend_pic.'" height="80" width="80" alt="'.$friend_username.'" title="'.$friend_username.'">'.$friend_username.'</a>'; } } if you guys need any further info please let me know
-
Hi all. How can i send mail to multiple users at the same time with each user getting their own related data. I'm using php mailer as an engine to send the mail. Based on this, i'd have loved to setup a cron for it but i do not know how, so i figure i'd just do it manually before i get to know how to setup a cron job. It's just to send a reminder to users and each user has a different subscription expiry time. I want each user to get their respective expiration date, expiry day etc. Thanks if(isset($_POST['send_reminder'])){ $sql = "SELECT * FROM users WHERE status = '$status'"; $stmt = $pdo->query($sql); $stmt->execute(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $name = $row['name']; $acct_no = $row['acct_no']; $email_addresses = $row['email']; $expiry_date = $row['expiry_date']; $expiry_day = $row['expiry_day']; } $message="Hello $name,<br> <p> This is to remind you that your subscription will expire in $expiry_day. </p> <p> Details as follows: Name: $name<br> Account Number: $acct_no<br> Email: $email_addresses<br> Expire in days: $expiry_day<br> Expiry Date: $expiry_date </p> <p> Thank you </p> $mail = new PHPMailer; //$mail->SMTPDebug = 3; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'mail.server.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'mails@services.cap'; // SMTP username $mail->Password = 'password'; // SMTP password $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 465; // TCP port to connect to $mail->From = mails@services.cap'; $mail->FromName = 'Club 404'; $mail->addAddress($email_addresses); // Add a recipient $mail->WordWrap = 587; // Set word wrap to 50 characters $mail->AddEmbeddedImage("../img/logo.png", "my_logo"); $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'REMINDER ON CLUB EXPIRY DATE'; $mail->Body = $mess; $mail->send(); }
-
I'm looking for an application or a social wall plugin to be added to a project. After looking at Wordpress and finally sifting through all the plugins (maybe all), I have come to a conclusion the plugins are not giving me enough customization options. For example, customizing the registration form. I need to add javascript for a combo box in order to display different options depending on what was selected. What I need - Your Opinion on a good social wall that's easy to make changes. I need a secure login and password --- PDO based A control panel would be nice to activate users or deactivate. A customized registration form Ability to add more pages, add php to customize it to work like I need it to. Responsive. If anyone has an opinion with experience on this matter it would be great to hear from you.
-
I am trying to control the items shown by selecting them by active = 0. I can get it to work. Any help would be appreciated. <?php try { $sql = "SELECT company.co_name, company.active, co_info.customer_no, co_info.password, co_address, co_city, co_state, co_zip, host, ftp_name, ftp_password FROM company LEFT JOIN co_info ON company.id = co_info.id WHERE company.active = '0' "; $result = $dbh->query($sql);
-
Hi all. I generated a random number and assigned it a variable to be used through out the session but on getting to the next page, the value changes. It is regenerating another number which isnt the intention. I have tried severally but no way! i really cannot figure out why the value changes in my second page. $loan = mt_rand(1000, 9999); $name = "John"; if(isset($_POST['continue'])){ $_SESSION['num'] = $number; $sql = ("INSERT INTO table (name, token_number) VALUES(:name, :token_number) $stmt=$pdo->prepare($sql); $stmt->execute(array( ':name'=>$name; ':token_number'=>$_SESSION['num'] )); if($stmt->rowCount()==1){ header("location: nextpage.php"); }else{ echo "Something went wrong"; } }
-
I am trying to coonect my jquery price slider to my database in order to search for recipes depending on the price. I have written the code below but I am not sure were i am going wrong. Could anyone help? <!--Javascript code for jquery price range slider--> <script type="text/javascript"> $(function() { $( "#slider-range" ).slider({ range: true, min: 0, max: 10, values: [ <?php echo $min?>,<?php echo $max?> ], // This line could be the issue? slide: function( event, ui ) { $( "#amount" ).val( "£" + ui.values[ 0 ] + " - £" + ui.values[ 1 ] ); } }); $( "#amount" ).val( "£" + $( "#slider-range" ).slider( "values", 0 ) + " - £" + $( "#slider-range" ).slider( "values", 1 ) ); }); </script> <!--php code to connect to jquery price slider--> <?php require_once './config.php'; include './header.php'; include('database.php'); if($_POST && isset($_POST['amount'])){ $values = $_POST['amount']; $values = str_replace(array(' ', '£'), '', $_POST['amount']); list($min, $max) = explode('-', $values); $sql = "SELECT `recipe_name`, `recipe_price`, `Image` FROM `recipe` WHERE `recipe_price` BETWEEN :min AND :max"; $stmt = $DB->prepare($sql); $stmt->execute(array(':min' => $min, ':max' => $max)); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); if (count($rows) > 0) { foreach ($rows as $row) { // do loop stuff } } else { $min = 0; $max = 10; $HTML = ''; } } ?> <!--HTML code for price slider --> <form action="" method="post" id="recipe"> <div style="margin-left:20px"> <label for="amount">Price range:</label> <input type="text" id="amount" name="amount" style="border:0; color:#f6931f; font-weight:bold;" readonly> <br><br> <div id="slider-range" style="width:50%;"></div> <br><br> <input type="submit" value="Find" /> <br><br> <?php echo $HTML?> </div> </form> <!-- connnect to Database - PDO connection--> <?php error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE); ob_start(); define('DB_DRIVER', 'mysql'); define('DB_SERVER', 'localhost'); define('DB_SERVER_USERNAME', 'xxxxx'); define('DB_SERVER_PASSWORD', 'xxxx'); define('DB_DATABASE', 'xxxxx'); define('PROJECT_NAME', 'BudGet Recipes'); $dboptions = array( PDO::ATTR_PERSISTENT => FALSE, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', ); try { $DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions); } catch (Exception $ex) { echo $ex->getMessage(); die; } ?>
-
I cannot view data based upon my "wid" in the following code. Basically I have a page that you click on a link, and it passes a number to the "wid" as an integer. I want to call on that corresponding table that has a "like" wid. Here is what I have so far... <?php require 'database.php'; if(!empty($_GET['wid'])) { $wid = $_GET['wid']; } else { $wid = null; } if ( null==$wid ) { header("Location: workorders.php"); } else { $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = 'SELECT * FROM items where wid = ?'; $rows = $pdo->query($sql); foreach ($pdo->query($sql) as $row) { echo '<tr>'; echo '<td>'. $row['id'] . '</td>'; echo '<td>'. $row['wid'] . '</td>'; echo '<td>'. $row['model'] . '</td>'; echo '<td>'. $row['description'] . '</td>'; echo '<td>'. $row['cost'] . '</td>'; echo '<td>'. $row['retail'] . '</td>'; echo '<td>'. $row['tax'] . '</td>'; echo '<td width=250>'; } Database::disconnect(); } ?>
-
Here's my example of using transactions in PDO: I am getting the two errors below when I run my scripts in the browser. PDOException: There is no active transaction in...... Fatal error: Uncaught exception 'PDOException' with message 'There is no active transaction' in ...... here is ny pdo database connection class: <?php class conn { public $host = ''; public $dbname = ''; public $username = ''; public $password = ''; /** * @var object $db_connection The database connection */ private $db_connection = null; public function __construct($host, $dbname, $username, $password) { $this->host = $host; $this->dbname = $dbname; $this->username = $username; $this->password = $password; } public function connected() { try { $this->db_connection = @new PDO('mysql:host='.$this->hos.';dbname='.$this->dbname.';charset=utf8mb4', $this->username, $this->password); return $this->db_connection; } catch (PDOException $e) { echo "Unable to connect to the PDO database: " . $e->getMessage(); } } } And below is the database queries: <?php require('config/conn.php'); $host = 'localhost'; $dbname = 'dbname'; $username = 'username'; $password = 'password'; $db = new conn($host, $dbname, $username, $password); try { //note that calling beginTransaction() turns off auto commit automatically $db->connected()->beginTransaction(); $stmt = $db->connected()->prepare("INSERT INTO category_types (name, cat_id) VALUES (:name, :value)"); $stmt->bindParam(':name', $name); $stmt->bindParam(':value', $value); // insert one row $name = 'one'; $value = 1; $stmt->execute(); // insert another row with different values $name = 'two'; $value = 2; $stmt->execute(); $stmt = $db->connected()->prepare("INSERT INTO category_types2 (name, cat_id) VALUES (:name, :value)"); $stmt->bindParam(':name', $name); $stmt->bindParam(':value', $value); // insert one row $name = 'one'; $value = 1; if($stmt->execute()) //all went well commit! $db->connected()->commit(); } catch (Exception $e) { //Something went wrong rollback! $db->connected()->rollBack(); echo "Failed: " . $e->getMessage(); } What might I be doing wrong? Thanks
-
Hi I’m looking for a standalone PHP OOP framework or code that follows best practices using - PDO prepared statements - Singleton Design Pattern Not looking for a massive library, something short and sweat straight to the point Any comments, feedback would be appreciated
-
Hi all. I have two tables where the username is what they have in common. i want to perform a join for both tables but i'm having problems with mysql joins. //to get the desire result individually i did //table one $stmt = $pdo->query("SELECT * FROM tableone WHERE username = '$_GET[id]'"); $row = $stmt->fetch(PDO::FETCH_ASSOC); $credit_score = $row['credit_score']; $acct_num = $row['acct_num']; $acct_name = ucwords($row['surname']) ." ". ucwords($row['firstname']); $username = $row['username']; if($credit_score ==3){ $bill_limits = 2000; }elseif($credit_score ==2){ $bill_limits = 1000; }elseif($credit_score ==1){ $bill_limits = 500; } //table two $stmt=$pdo->query("SELECT SUM(amt) as bill FROM tabletwo WHERE username = '$_GET[id]' AND relationship = 'PARENT'"); $row = $stmt->fetch(PDO::FETCH_ASSOC); $bill = $row['bill']; $service_charge_for_limits = '0.05' * $bill; $tax_rate_for_limits = '0.13' * $service_charge_for_limits; $bill_sum = $tax_rate_for_limits + $service_charge_for_limits + $bill; Approved Bill Limits = $<?php echo number_format($bill_limits,2); ?> <br> Bill Limits Used = $<?php echo number_format($bill_sum,2); ?> <br> <?php $available_limits = $bill_limits - $bill_sum; ?> Bill Limits Available = $<?php echo number_format($available_limits,2); ?> The above gives me the correct result, but now i have another page where i want to all the clients and their corresponding available limits, used limits and approve limits form table two and other information from table one On the page i have $stmt = $pdo->prepare("SELECT * FROM tableone WHERE status = 'COMPLETED' ORDER BY id DESC LIMIT $start, $limit"); $stmt->execute(); $num_rows = $stmt->rowCount(); echo "<table width='100%' class='table-responsive table-hover table-condensed table-striped'>"; echo "<tr> <th bgcolor='#444444' align='center'><font color='#fff'>Account Number</th> <th bgcolor='#444444' align='center'><font color='#fff'>Subscriber's Name</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>Username</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>Limits ($)</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>View Profile</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>Delete Account</font></th> </tr>"; // keeps getting the next row until there are no more to get while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { // Print out the contents of each row into a table echo "<tr><td>"; echo $row['acct_num']; echo "</td><td>"; echo ucwords($row['surname']." ". $row['firstname']); echo "</td><td>"; echo $row['username']; echo "</td><td>"; $credit_score = $row['credit_score']; if($credit_score ==3){ $bill_limits = 2000; }elseif($credit_score ==2){ $bill_limits = 1000; }elseif($credit_score ==1){ $bill_limits = 500; } echo number_format($bill_limits, 2); echo "</td><td>"; echo "<a href='view-client-profile.php?id={$row['username']}'>view more</a>"; echo "</td><td>"; echo "<a href='delete-account.php?id={$row['username']}'>Delete Account</a>"; echo "</td></tr>"; //echo "</td><td>"; //echo "<a href='settle.php?id={$row['acct_num']}'>Points</a>"; } echo "</table>"; How ca i join tableone and tabletwo (plus sum)
-
Hello all. I am trying to get values from two tables but i am getting the wrong output regardless of the type of join i use. The two query have some similar columns/rows. I want to fetch only the specified columns/rows with their unique data but my query is giving me on a column the value of just another column. For instance if a description column in table A has a value of INVOICE and on table B the description is RECEIPT all my query show is either INVOICE or RECEIPT in all the columns regardless of whether the description is receipt or not and also i want all the fields that is not on the other table to be blank and not replicate columns eg. description. image refuse to show when attached and wouldn't allow me to use the image link on the editor, said i am not allowed. SELECT table1.trans_ref, table1.description, table1.date_paid, table1.recurring, table1.amt, table1.bill_code, table2.trans_ref, table2.description, table2.amt_deposited, table2.deposit_date FROM table1 RIGHT JOIN table2 ON table1.username = table2.username ps: would want amount and deposit amount to be on same column and also use a where username = username. or maybe i am not doing the right thing? is it possible to a select on two tables without using a JOIN? so that you can echo only the needed values in a loop. thanks
-
So I have this code: <?php $user = "clicrckc_osherdo"; $pass = "3563077"; $CurrentUser= $_SESSION['user_id']; try { $dbh = new PDO('mysql:host=localhost;dbname=clicrckc_andfit', $user, $pass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "connected successfully"; print_r($_SESSION); $UserName = $dbh->prepare("SELECT first_name,last_name FROM users WHERE user_id = ?"); $UserName->bindParam(1, $CurrentUser); $UserName->execute(); $UserName->fetch(PDO::FETCH_ASSOC); $dbh = null; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } ?> <div id="PersonalDetails">Hello dear <?= $UserName ?>!</div> I am trying to insert the current username in the session to the html code where $Username is. I cannot find out why it wont work. I am getting the following message, instead of the current username in the session: Catchable fatal error: Object of class PDOStatement could not be converted to string in/home/clicrckc/public_html/dashboard.phpon line136 I have tried to google the issue but I could not address the issue. please- help anyone? Thank you.
-
hi I want to use url attachments for other post instead upload files again. Duplicate row(s) of attachments table with "attid field" posted from form and change a "postid field" in same table. I have a form with some input checkbox. The values of input are numbers which point to values of the field in database (attachments table > attid field ). <input type="checkbox" name="attid[]" value="10" /> <input type="checkbox" name="attid[]" value="250" /> This "attid" field is a Primary Key and AUTO_INCREMENT. I want when form submit, duplicate a row(s) with "attid" posted. Used this > INSERT INRO - SELECT query with loop by for each but not succesful $sql = ('INSERT INTO attachments (field1, field2) (SELECT * FROM attachments WHERE attid= :attid)'); thanks
-
Hi all, I am working on a search script which searches article titles from the table. i have worked out the function, but have not been able to add an error message if the results are zero. my class file has this following function public function search($table){ $search=$_GET['search']; if ($this->databaseConnection()) { $sql="SELECT * FROM $table WHERE title LIKE '%$search%'"; $q = $this->db_connection->query($sql) or die("failed!"); while($r = $q->fetch(PDO::FETCH_ASSOC)){ $data[]=$r; } return $data; } } my results page has the following code <?php foreach($crud->search("articles") as $value){ extract($value); echo <<<show <p>" <a href="view.php?article_id=$article_id">$title</a> "</p> <br> show; } ?> would be highly obliged if anyone can help me out. apologies if this is a stupid question, but i am pretty much an amateur still. regards, Nayan
-
Hello All, Have a GoDaddy MySQL PHP:PDO hosting questions. Using a database class to make script queries. Unfortunately, I'm required to use GoDaddy Windows hosting. However, I'm a Linux kind of guy. Here's the issue. The viewer script includes database credentials defined as constants, in a file outside the root directory. Typically, these constants are available to all sub processes including class objects. Everything works as expected on development server. The error message I get with version using constants: L226: projectGallery_class datapull Caught Exception --- invalid data source name with host string userDBName.db.6482519.hostedresource.com;dbname=userDBName However when I deploy to GoDaddy's production server, the constants are defined - but empty. Here is the example code. /* works on Linux */ class datapull { var $host; // not assigned here var $userName; // not assigned here var $userPass; // not assigned here protected function conn() { try { $DB = new PDO(DB_HOST,DB_UNAME,DB_PASS); $DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $DB; } catch( Exception $e ) { $mes = "L226: datapull::conn() Caught Exception --- "; $mes .= $e->getMessage(); error_log($mes); } } public function dbquery($qqueue) { $DB = (!isset($DB)) ? $this->conn() : $DB; /* some query stuff here */ return $result } The modified class for GoDaddy Windows class datapull { var $host = “mysql:host=userDBName.db.1234567.hostedresource.com;dbname=userDBName”; var $userName = “userDBName”; //godaddy user and database naming convention var $userPass = “userPWDString”; //user password protected function conn() { try { $DB = new PDO($this->host,$this->userName,$this->userPass); $DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $DB; } catch( Exception $e ) { $mes = "L226: datapull::conn() Caught Exception --- "; $mes .= $e->getMessage(); error_log($mes); } } public function dbquery($qqueue) { $DB = (!isset($DB)) ? $this->conn() : $DB; /* some query stuff here */ return $result }
-
I am having a bit of issue. I have a simple query that loops to find each record, like this. // select query here if(count($result) > 0) { foreach($result as $row) { $userid = $row['user_id']; $_SESSION['userid'] = $userid; } } else { // error here } I want to use the "$userid" on a different page; so I created a session for it. When ever I use that session on another page, it gives me only the last record's user id and not the first one. How can I fix this?
-
This should all be working but I think I might be overlooking something. Problem 1. I am using ajax to process a form. I don't think the problem is with ajax(works with other queries), but rather with php. Here is my simple query. $stmt = $db->prepare("SELECT * FROM records WHERE request_by = :request_by, request_to = :request_to AND session = :session"); $stmt->bindParam(':request_by', $byUserid); $stmt->bindParam(':request_to', $toUserid); $stmt->bindValue(':session', 1); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); if(count($result) > 0) { $success = 'This was successful.'; } else { $error = 'There was a problem.'; } This above query gives me this error. Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' request_to = '7' AND session = '1'' at line 1 Problem 2. Say the main page is "index.php" with submit form and I am using ajax via url: process.php. Well on "index.php" page, I have foreach loop that gets me a "$toUserid" for each record. I would like to use that "$toUserid" in "process.php" page. I tried setting it as a session but still it won't give me that exact userid. It'll give me the same userid as the user I am currently logged in. What exactly I am doing wrong and how I can i fix it?
-
Hi, I'm quite new to OOP PHP and i'm trying to make a dynamic insert function , i've followed an example on Stackoverflow to do so since its my first try at making something dynamic.http://stackoverflow.com/a/13333344/3559635 It works but im still quite confused about the two foreach loops , and if possible could someone explain that part to me please and or is there an easier more clean way to do this for a new guy like me? Im sending my POST values from the index.php <?php include("Database.php"); $db = new Database(); var_dump($db); $table = "users"; $whitelist = array('username', 'password'); $data = array_intersect_key($_POST, array_flip($whitelist)); if(isset($_POST['username']) AND ($_POST['password'])) { $db->postTesting($data, $table); } else { echo "Please fill in everything!"; } Database.php <?php class Database { private $connection; private $typedb = "mysql"; private $host = "127.0.0.1"; private $dbname = "oopphp"; private $username = "root"; private $password = ""; public function __construct() { try{ $this->connection = new PDO($this->typedb. ":host=".$this->host. ";dbname=".$this->dbname, $this->username, $this->password); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this->connection; } catch(PDOException $e) { throw new Exception("Connection failed: ".$e->getMessage()); } } public function postTesting($data, $table) { try{ //var_dump($table, $data); $columns = ""; $holders = ""; foreach ($data as $column => $value) { //var_dump($column); //var_dump($value); $columns .= ($columns == "") ? "" : ", "; $columns .= $column; $holders .= ($holders == "") ? "" : ", "; $holders .= ":$column"; //var_dump($columns); //var_dump($holders); } $sql = "INSERT INTO $table ($columns) VALUES ($holders)"; //return $sql; $stmt = $this->connection->prepare($sql); //var_dump($stmt); foreach ($data as $placeholder => $value) { $stmt->bindValue(":$placeholder", $value); //var_dump($stmt); //var_dump($placeholder); //var_dump($value); } //var_dump($sql); //var_dump($stmt); $stmt->execute(); } catch(PDOException $rError) { throw new Exception("Registering Failed: ".$rError->getMessage()); } } } Im seriously confused about this part. foreach ($data as $column => $value) { //var_dump($column); //var_dump($value); $columns .= ($columns == "") ? "" : ", "; $columns .= $column; $holders .= ($holders == "") ? "" : ", "; $holders .= ":$column"; //var_dump($columns); //var_dump($holders); } Thanks in advance for the help
-
I'm not sure where to exactly begin with this query, but here's the objectives: Column A values: 3, 5, 7, 9, 21 Column B value: 2 Column User: $id Perform an if on each separate column A while ran in a batch process to speed up the query
-
$news='news'; $sql_news = "INSERT INTO `rise`.`news` ( `user` , `message` ) VALUES ( :id, :news );"; $q_news = $conn->prepare($sql_news); $q_news -> execute(array(':id'=>$id, ':news'=>$news)); print_r($q_news); echo $q_news->rowCount(); Why does it echo 1 instead of 2 when everything else on the page is turned off for processing, and it's the last thing on the page? Why do 2 inserts happen?