PHP - Perpared Statements And Printing A Column On Screen?
The Connection:
<?php $dsn = "mysql:dbname=phpblog;host=localhost"; $user = "root"; $password = ""; try{ $pdo = new PDO($dsn, $user, $password); }catch(PDOException $e){ echo "Connection failed: " . $e->getMessage(); } ?>The Script: <?php $query = $pdo->prepare("SELECT * FROM posts WHERE id = ?"); $query->bindValue("1", $_GET['post_id']); $query->execute(); ?>I want to print the column "headline" on screen. I know how to do it with a foreach loop: Example: foreach($query as $data){ echo $data['headline']; }What can I do there? Similar TutorialsThis script ...
<?php echo "Your IP Address: <br/>"; print_r($_SERVER['REMOTE_ADDR']); ?>... prints: ::1I am looking to have the IP address from which the site is viewed printed on screen. What is the issue, here, with the script I have? I have been trying this on localhost and I am using XAMPP. I have 64 rows of players and want each User to be able to choose to bookmark an player, as well as unbookmark it too. I have a bookmark table set up, and each time a User decides to bookmark(+) or unbookmark(-) an player a row is created in the data table. (Matching the player ID and User ID) That's working fine. A query reads the most recent row for each player to determine if there is a + or - button next to each player. Testing the query and adding some dummy data, that part of it works too. However, the issue is the initial state, which I want to be a +. Once I go live, the table will be empty, nothing for the query to return/produce. How do I create an initial state of a + with no rows and have it not used or swapped out when Users start clicking + or -?
$query = "SELECT b.id, bookmark,playerID,userID,p.id FROM a_player_bookmark b LEFT JOIN a_players p ON '". $id ."' = playerID WHERE userID = '". $userID ."'&&'". $id ."' = playerID ORDER BY b.id desc LIMIT 1 "; $results = mysqli_query($con,$query); echo mysqli_error($con); while($row = mysqli_fetch_assoc($results)) { echo $row['bookmark']; if($row['bookmark'] == 0) { echo '-'; // this is where a form goes to remove a bookmark } else { echo '+'; // this is where a form goes to add a bookmark } } I tried to get it with CASE, but I don't think that's the right path. I also looked at UNION. I was able to get it to produce an initial state of +, but it still printed the already made up sample data too (so I have three instances of ++ or +-). (Players 2, 4 and 4)
Here is the what the UNION query looked like: $query = "(SELECT b.id, bookmark,playerID,userID,p.id FROM a_player_bookmark b LEFT JOIN a_players p ON '". $id ."' = playerID WHERE userID = '". $userID ."'&&'". $id ."' = playerID ORDER BY b.id desc LIMIT 1) UNION (SELECT b.id, bookmark,playerID,userID,p.id FROM a_player_bookmark b LEFT JOIN a_players p ON '". $id ."' = playerID WHERE userID = '". $userID ."' ORDER BY p.id desc LIMIT 1) ";
My Php Buddies, I have mysql tbl columns these:
id: Now, I want to display their row data by excluded a few columns. Want to exclude these columns: date_&_time account_activation_code account_activation_status id_verification_video_file_url password
So, the User's (eg. your's) homepage inside his account should display labels like these where labels match the column names but the underscores are removed and each words' first chars CAPITALISED:
Id: 1
For your convenience only PART 1 works. Need help on Part 2 My attempted code:
PART 1 <?php // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Query to get columns from table $query = $conn->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'members' AND TABLE_NAME = 'users'"); while($row = $query->fetch_assoc()){ $result[] = $row; } // Array of all column names $columnArr = array_column($result, 'COLUMN_NAME'); foreach ($columnArr as $value) { echo "<b>$value</b>: ";?><br><?php } ?> PART 2 <?php //Display User Account Details echo "<h3>User: <a href=\"user.php?user=$user\">$user</a> Details</h3>";?><br> <?php $excluded_columns = array("date_&_time","account_activation_code","account_activation_status","id_verification_video_file_url","password"); foreach ($excluded_columns as $value2) { echo "Excluded Column: <b>$value2</b><br>"; } foreach ($columnArr as $value) { if($value != "$value2") { $label = str_replace("_"," ","$value"); $label = ucwords("$label"); //echo "<b>$label</b>: "; echo "$_SESSION[$value]";?><br><?php echo "<b>$label</b>: "; echo "${$value}";?><br><?php } } ?> PROBLEM: Columns from the excluded list still get displayed. Edited November 19, 2018 by phpsaneHey guys, is there any way to have a LIKE condition on an IF statement? Something like: Code: [Select] if $GET_['WTV'] LIKE %LOVE% { $category=romance Any clues? Thanks in advance. I am trying to write an if statement that checks to make sure the information put in the text box is an imbedded file. Does anyone know how to do that? Hello, I am learning PDO SQL statements, I have mananged to connect using PDO: Code: [Select] try { $this->link = $dbh = new PDO('mysql:host='.$this->dbhost.';dbname='.$this->dbname.'', $this->dbuser, $this->dbpass); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } I am not getting any error, so I guess that is a good start. I then tried the PDO SQL statement out. My old mySQL query is commented out in the Code: [Select] if (isset($_SESSION['id']) && isset($_SESSION['password'])) { $_SESSION['id'] = ( isset( $_SESSION['id'] ) ) ? $_SESSION['id'] : FALSE; $_SESSION['password'] = ( isset( $_SESSION['password'] ) ) ? $_SESSION['password'] : FALSE; //$logged = mysql_query("SELECT * FROM `db_members` WHERE `id`='".$_SESSION['id']."' AND `password` = '".$_SESSION['password']."'"); //$logged = mysql_fetch_array( $logged ); // the new pdo statement $ff = $dbh->prepare('SELECT * FROM db_members WHERE id = '.$_SESSION['id'].' AND password = '.$_SESSION['password'].''); $ff->execute(); $logged = $ff->fetchAll(); echo $logged['username']; } I am trying to assign the session to logged variable. So all I am asking is go into db_members and check the id and password that is the same as session id and password and collect the rows data such as username. My login script and everything works perfectly, even session id and password is valid when echo'd but I cannot assign it to the logged variable like my old sql statements. Code: [Select] $logged = mysql_query("SELECT * FROM `db_members` WHERE `id`='".$_SESSION['id']."' AND `password` = '".$_SESSION['password']."'"); $logged = mysql_fetch_array( $logged ); I used other PDO statements and it works perfectly but I just don't understand why this is not working.... can I please get some help if you have any solution to this? Hi Guys, Newbie trying to understand PHP conditionals. In the below Code: [Select] [[*id]] is a global variable which equates to my current page id so it could have the value of 1 for example. I tested it using echo and the correct values pass to it in the cms I'm using. What I cant achieve is for the conditionals below to work correctly so perhaps you can see a syntax error or show me away of doing the same using an array or something perhaps? THANKS Code: [Select] <?php $id='[[*id]]' if ($id=="1" || $id=="2") echo "we are in 1 or 2"; elseif ($id=="3" || $id=="4") echo "we are in 3 or 4"; else echo "not in 1 to 4"; ?> Anything wrong with this because I got a parse error ONLY after adding to create this. <?php $visible = array('Yes', 'No'); foreach($visible as $visible): $visible2 = array('yes', 'no'); foreach($visible2 as $visible2): ?> The below is constantly loading the password page no matter what is enter in the password input on the form (on another page). I have checked the $login variable by echoing it and it is carrying the value from the field. <?php $off="yes"; $login=$_POST['login']; if($off=="yes" && (!isset($_SESSION['login']) || $_SESSION['login']!="pass")){ if($login=="" || $_SESSION['login']!="pass"){ header('Location: ./index2.html'); exit(); } elseif(!isset($_SESSION['login'])){ session_start(); $_SESSION['login']=$login; header('Location: ./index.php'); exit(); } } elseif($off=="no" || $_SESSION['login']=="pass"){ content goes here. } ?> Hey Guys, I am creating an array and I have a need to put a if statement inside it. Is this even possible? Here is where I am at so far, its just not working. function load_permissions($gid) { $data = array(); $this->db->select('`groups`.`name` AS `permission_name`, `permissions`.``'); $query = $this->db->get('`groups`,`permissions`'); if ($query->num_rows() > 0){ foreach ($query->result_array() as $row){ $data[] = array( "name" => $row['permission_name'], "read" => if($row['level'] >= 1) { img("img/true.gif") } else { img("img/false.gif") }, ); } } $query->free_result(); return $data; Thanks, Peter How to write 2 "if" statements together? if($userResult==$myResult) and ($userResult<0) { If my SQL statement returns a result I want to change the background color of a cell. If the user is logged in I want to then show one of two buttons. either book, or cancel, depending on whether the cell is available or not. So far I have this: $sql = "SELECT * FROM diary WHERE day = '$mon' AND studio_id ='mon11'"; $query = mysql_query($sql) or die (mysql_error()); if (mysql_num_rows($query) < 1) { $bgcolour= '#5DFC0A'; if(isSet($_SESSION['logged'])) { $book = '<form action="../book.php" method="POST"><input type="hidden" name="day" value='.$mon.' type="text"/><input type="hidden" name="month" value='.$month.' type="text"/><input type="hidden" name="year" value='.$year.' type="text"/><input type="hidden" name="book_id" value="mon11" type="text"/><input type="submit" name="submit" value="Book!"></form>'; }} else { $bgcolour= '#FF0000'; } if(isSet($_SESSION['logged'])) { $book = '<form action="../cancel.php" method="POST"><input type="hidden" name="day" value='.$mon.' type="text"/><input type="hidden" name="month" value='.$month.' type="text"/><input type="hidden" name="year" value='.$year.' type="text"/><input type="hidden" name="book_id" value="mon11" type="text"/><input type="submit" name="submit" value="Cancel!"></form>'; } echo "<td rowspan='3' bgcolor=".$bgcolour.">"; if (isset($book)) { echo $book; } I want to use the $session(logged) variable to show the appropriate button, but I can't get it to work in the other if statement, Any ideas? I have a general dbInsert class method that accepts three arguments: table, fields, and values - the last two each as an array. I am using a PDO connection and prepared statements to sanitize everything. I am having a problem with the bindParam() function accepting the parameter ID's though... here's my code and the result I am getting, any advice? My arguments: $this->_table = "testdata"; $this->_fields = array('product_id', 'store_id', 'description', 'price', 'colors', 'sizes'); $this->_values = array("20002157", "2005", "Kids polo shirt", "12.59", "White", "Large"); My object: $_crud = new Crud(); $_makeCrud = $_crud->dbInsert($this->_table, $this->_fields, $this->_values); My class: public function dbInsert($table, $fields, $values) { $_table = $table; $_fields = implode(", ", $fields); // Create and format the list of insert values $_values = ""; // replaces values with "?" placeholders foreach ($values as $value) { $_values .= "?" . ", "; } // trims off last comma and space $_values = substr($_values, 0, -2); // checks database connection if (isset($this->_dbh)) { // Create the SQL Query $this->_sql = 'INSERT INTO ' . $_table . ' (' . $_fields . ') VALUES (' . $_values . ')'; // Build the query transaction $this->_dbh->beginTransaction(); // Build the prepared statement $this->_stmt = $this->_dbh->prepare($this->_sql); // Bind the parameters to their properties foreach ($values as $key => $val) { // starts $key at 1 $key = (int) $key + 1; $this->_stmt->bindParam($key, $val); } // Execute the query $this->_stmt->execute(); $this->_affectedRows = $this->_stmt->rowCount(); } } What my new table row should look like: Code: [Select] product_id store_id description price colors sizes ---------------------------------------------------------------------------------------------- 20002157 2005 kids polo shirt 12.59 white large But this is what my new row DOES look like: Code: [Select] product_id store_id description price colors sizes ---------------------------------------------------------------------------------------------- Large 0 Large 0.00 Large Large So it's taking the value of that last $value and inserting it in all the fields, the store_id and price are 0 and 0.00 because of their numeric type... I assume it is a syntax error, missing quotes somewhere, but where? Hello, I'm currently working on just a quick little frontend for VirtualBox and I'm just running into a little bit of a problem that I can't find my way around. Now this is my first project in php. I'm familiar with programming concepts (well except this one apparently ) and by familiar were talking I like to tinker with small languages.. no formal training. Anyway, here we go. So heres the main page. Pretty simple, you type the argument that goes with the following command and check the box next to the command you'd like to execute. Code: [Select] <HTML> <HEAD> <TITLE>LCCP ver1</TITLE> </HEAD> <BODY> <?php include "header.php"; ?> <form method="post" action="lccp_ver1.php"> <p>cmd="createvm"<br> Enter the name of the Virtual Guest you'd like to create: <input type="text" name="id"> <input type="checkbox" name="createvm"> </p> <p>cmd="showvrtinfo"<br> Enter the name of the Virtual Machine you'd like to view: <input type="text" name="id2"> <input type="checkbox" name="showvminfo"> </p> <p>cmd="unregistervm"<br> Enter the name of the Virtual Guest you'd like to delete: <input type="text" name="id3"> <input type="checkbox" name="unregistervm"> </p> <p>cmd="startvm"<br> Enter the name of the Virtual Machine you'd like to start: <input type="text" name="id4"> <input type="checkbox" name="startvm"> </p> <p>cmd="controlvm"<br> Enter the name of the Virtual Machine you'd like to control: <input type="text" name="id5"> <input type="checkbox" name="controlvm"> </p> <p>Then.. would you like to...</p> <p>arg="pause" <input type="checkbox" name="controlvm_pause"></p> <p>arg="resume" <input type="checkbox" name="controlvm_resume"></p> <p>arg="reset" <input type="checkbox" name="controlvm_reset"></p> <p>arg="poweroff" <input type="checkbox" name="controlvm_poweroff"></p> <p>arg="savestate" <input type="checkbox" name="controlvm_savestate"></p> <input type="submit" name="Submit" value="Submit"> </form> </BODY> </HTML> And then here is the execution page Code: [Select] <HTML> <HEAD> <TITLE>LCCP command <?php function ServerLoad() { $stats = exec('uptime'); preg_match('/averages?: ([0-9\.]+),[\s]+([0-9\.]+),[\s]+([0-9\.]+)/', $stats, $regs); return ($regs[1].', '.$regs[2].', '.$regs[3]); } echo ServerLoad(); ?> </TITLE> </HEAD> <BODY> <?php include "header.php"; ?> <?php function createvm($id) { $output = shell_exec("VBoxManage createvm --name " . $id . " --register"); return $output; } function showvminfo($id) { $output = shell_exec("VBoxManage showvminfo " . $id); return $output; } function unregistervm($id) { $output = shell_exec("VBoxManage unregistervm ". $id ." --delete"); return $output; } function startvm($id) { $output = shell_exec("VBoxManage startvm ". $id ." --type headless"); return $output; } function controlvm($id,$arg) { $output = shell_exec("VBoxManage controlvm ". $id ." ". $arg); return $output; } function print_output($output) { echo' <pre>'. $output . ' </pre>'; } //******************exec main********************** if (isset($_POST['createvm'])) { // createvm($_POST['id2']); print_output(createvm($_POST['id'])); } if (isset($_POST['showvminfo'])) { // showvminfo($_POST['id']); print_output(showvminfo($_POST['id2'])); } if (isset($_POST['unregistervm'])) { // unregistervm($_POST['id3'); print_output(unregistervm($_POST['id3'])); } if (isset($_POST['startvm'])) { // startvm($_POST['id4']); print_output(startvm($_POST['id4'])); } if ((isset($_POST['controlvm'])) AND (isset($_POST['controlvm_pause'))) { //controlvm($_POST['id5']," pause"); print_output(controlvm($_POST['id5']," pause")); } if ((isset($_POST['controlvm'])) AND (isset($_POST['controlvm_resume'))) { //controlvm($_POST['id5']," resume"); print_output(controlvm($_POST['id5']," resume")); } if ((isset($_POST['controlvm'])) AND (isset($_POST['controlvm_reset'))) { //controlvm($_POST['id5']," reset"); print_output(controlvm($_POST['id5']," reset")); } if ((isset($_POST['controlvm'])) AND (isset($_POST['controlvm_poweroff'))) { //controlvm($_POST['id5']," poweroff"); print_output(controlvm($_POST['id5']," poweroff")); } if ((isset($_POST['controlvm'])) AND (isset($_POST['controlvm_savestate'))) { //controlvm($_POST['id5']," savestate"); print_output(controlvm($_POST['id5']," savestate")); } //**********working on*************** //teleport? ?> </BODY> </HTML> Now my question is with the if statements. Well, number one I guess is there a more efficient way of doing this that I'm overlooking? I looked into switches but I don't know how I'd pull that off with checkboxes without some complicated loop and somehow converting the checkboxes "yes" or "nos" into numbers or something. If statements just seemed like less of a headache but I may be finding otherwise haha. Number two here is how do I get the "controlvm" command to work? When I comment out that last indented lines of if statements the program runs perfect (and thats with the controlvm function as well. so.. the problem isn't there). Basically whats the appropriate way to do this. I'm stuck and my limited program knowledge and Google searching is starting to run thin. Thanks in advance for the help! Hi, What is a shorter way instead of having all these if statements? Here it is: Code: [Select] if($matchno==1) return 66; elseif($matchno==2) return 67; elseif($matchno==3) return 68; elseif($matchno==4) return 69; elseif($matchno==5) return 70; elseif($matchno==6) return 71; elseif($matchno==7) return 72; elseif($matchno==8) return 73; elseif($matchno==9) return 74; elseif($matchno==10) return 75; elseif($matchno==11) return 76; elseif($matchno==12) return 77; elseif($matchno==13) return 78; elseif($matchno==14) return 79; elseif($matchno==15) return 80; elseif($matchno==16) return 81; elseif($matchno==17) return 82; elseif($matchno==18) return 83; elseif($matchno==19) return 84; elseif($matchno==20) return 85; elseif($matchno==21) return 86; elseif($matchno==22) return 87; elseif($matchno==23) return 88; elseif($matchno==24) return 89; elseif($matchno==25) return 90; elseif($matchno==26) return 91; elseif($matchno==27) return 92; elseif($matchno==28) return 93; elseif($matchno==29) return 94; elseif($matchno==30) return 95; elseif($matchno==31) return 96; elseif($matchno==32) return 97; someone please code shorter? I will learn this way. Thanks. How could I make it so that if the $date variable is past than $memberdate then something shows else something else does. <?php $date = date('Y-m-d H:i:s', time()-3600); $memberdate = '2011-01-29 01:03:28'; ?> Thanks in advance, I realised I could convert it into a unix timestamp but there must be a better way. Ty. I always have trouble reading shorthand statements, as i am used to always using brackets. So when i view someones code and they use shorthand, i get confused. Can i get a clear explanation on the example below:
if ( have_posts() ) : while ( have_posts() ) : the_post(); the_content(); endwhile; else: echo "<p>Sorry, no posts matched your criteria.</p>"; endif;I've always been accustomed to using brackets, so i have trouble understanding the above quickly. I can't get these two if, elseif and else statements too work, here is the code: if(empty($this->password)){ $this->errors[] = 'You must enter a password!'; } elseif(!strlen($this->password) >= 6){ $this->errors[] = 'Your password must be longer than 6 characters!'; } if(empty($this->email)){ $this->errors[] = 'You must enter an email address!'; } elseif(!preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}$/',$this->email)){ $this->errors[] = 'Your password can only contain these characters: a-z, A-Z and 0-9!'; } if(empty($this->confemail)){ $this->errors[] = 'Please confirm your email address!'; } elseif(!$this->confemail == $this->email){ $this->errors[] = 'The email addresses you entered did not match!'; } The if and elseif statements for "email" work just fine but the other 2 doesn't. With the "password" i first want to check if the field is empty, and when it is, it works as it should. But when i for example type "test" too check if the password is longer than 6 characters i don't get any message at all? With the "confemail" i want to first check if the field is empty, and when it is, it works as it should. But when i type in "test@test.com" in both fields to try to compare "confemail" to "email" i still get the "Please confirm your email address!" message? Hey everyone, i am currently working on a "contact us" script. I want the form to first allow the user which department they want to email. E.g. "Sales" and "Support" By changing this drop down box it will change which email the form is sent to. Im having trouble setting the PHP side of this script up to change the emails. Any help regarding this matter is much appreciated. HTML FORM: Code: [Select] <form name="contactForm" method="post" action="forms/contactUs.php"> <table width="350" border="0"> <tr> <td width="150" class="bold">Department:</td> <td width="200" align="left"> <select name="department" class="dropDown"> <option value="sales">Sales</option> <option value="support">Support</option> </select> </td> </tr> <tr> <td class="bold">Full Name:</td> <td> <input name="name" type="text" class="contactTextBox" /> </td> </tr> <tr> <td class="bold">Company:</td> <td> <input name="company" type="text" class="contactTextBox" /> </td> </tr> <tr> <td class="bold">Email:</td> <td> <input name="email" type="text" class="contactTextBox" /> </td> </tr> <tr> <td class="bold">Comments:</td> <td> <textarea name="com" id="com" cols="5" rows="5" class="contactTextArea" /></textarea> </td> </tr> <tr> <td> </td> <td align="right"> <input type="submit" class="button" value="Submit" /> <input type="reset" class="button" value="Reset" /> </td> </tr> </table> </form>PHP <?php $department = $_POST['department']; $confirm = "sales"; if(isset($_POST['email'])) { if($department == $confirm) { $email_to = "sales@pixemadesigns.com"; $email_subject = "Sales Question"; } else { $email_to = "support@pixemadesigns.com"; $email_subject = "Support Question"; } $fullName = $_POST['name']; $company = $_POST['company']; $email_from = $_POST['email']; $comments = $_POST['com']; $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "Full Name: ".clean_string($fullName)."\n"; $email_message .= "Company: ".clean_string($company)."\n"; $email_message .= "Email: ".clean_string($email_from)."\n"; $email_message .= "Comments: ".clean_string($comments)."\n"; // create email headers $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); header("location: ../contactSubmit.html"); ?> <? } ?> Hi There, Im trying to figure out how to do this if/else statement. I need it to say, "if this is true, do this. if this is true, do this. If neither is true, do this. So there are three different possible outcomes. I tried to put each new if inside of the previous else. but that doesn't seem to work. $firstname = $_REQUEST['firstname']; $lastname = $_REQUEST['lastname']; if ($firstname == 'Joey' and $lastname == 'Hodara') { $output = 'Welcome to our site, ' . htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ', Oh Glorious Leader!'; } else { if ($firstname == 'Matt' and $lastname == 'Fig') { $output = 'Welcome to our site, ' . htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ', Portagee!'; } else{ if ($firstname == 'Jon' and $lastname == 'Spense') { $output = 'Welcome to our site, ' . htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ', bro!'; } } $output = 'Welcome to our site, ' . htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ' ' . htmlspecialchars($lastname, ENT_QUOTES, 'UTF-8') . '!'; ?> |