PHP - If Statement Query In Procedural Code For Now
I am just wanting to know what the other forms of this type of conditonal would be, the type of if statement is as follows:
if ($_POST) {print_r($_POST);} Just seen it a few times now, I know this means if $_POST exists. use the print_r() function to display the entire post array suber global variable. But what are the other combinations other than just if true? Like how are they used like this, like if I wanted to see if a random variable is not identical to another etc. Any helps appreciated, Jez. Similar TutorialsHi all, I work on a php project. I wrote it in procedural way. As project grows, it stating be harder to maintain obviously and I want to convert project ( or at lease key features) to oo code. My intention is to replace part which for example connects to database and then use the rest of the script and then move to another part write it in oo and replace old part. I wrote a simple class called Connection, just to handle connection. When I make object it connects, I retrieve some info from database using query as class function. However, there is no way I can execute my procedural login script after I made a connection object. And question is why? Do I need to write whole Database class to handle it? Can I merge oo and procedural php code together in once script? Code sample: Code: [Select] class Connection{ // database access paramiters var $host = 'localhost'; var $data_base = 'database'; var $user = 'user'; var $pass = 'pass'; var $con_handle; // constructing object with automatic connetction to db function __construct(){ $this->connect(); } function connect(){ // open a connection to the database server $this->con_handle = new mysqli ($this->host, $this->user, $this->pass); if (mysqli_connect_errno()) { echo("Could not open connection to database server"); exit; } // selecting database $this->con_handle->select_db($this->data_base) or die(mysql_error()); } } Code: [Select] //{ few includes here} $connection= new Connection(); //{rest of my login script} So I have this snippet of code: Code: [Select] $row['ratings'] = ""; $ratingsSQL = $this->ipsclass->DB->query( "SELECT `pid` , `rating` , COUNT(`rating`) as ratings FROM `ibf_ratings` WHERE `pid` = '" . $row['pid'] . "' GROUP BY `rating` "); $i = 0; $ratingshtml = ""; if( $this->ipsclass->DB->get_num_rows( $ratingsSQL ) ) { while( $rrow = $this->ipsclass->DB->fetch_row( $ratingsSQL ) ) { $ratingshtml .= "<div class=\"rate_it_display\" style=\"background-image: url( 'style_images/rate/" . str_replace( ' ' , '' , strtolower( $this->ratings[$rrow['rating']] ) ) . ".png' ) \"> " . $rrow['ratings']. " x " . $this->ratings[$rrow['rating']] . "!</div>"; $i++; } $ratingshtml .= "<a href=\"#\" onclick=\"return RateItExpand( {$row['pid']} );\" style=\"color: #999;\">(list)</a>"; } $row['ratings'] = $this->ipsclass->compiled_templates['skin_topic']->ratings( $row['pid'] , $row['author_id'] , $ratingshtml ); I want to add an if statement to the code so that the ratings won't load unless a user clicks a button at the top of the screen. Can anyone help me with this? I'd be very appreciative. Thanks in advance. Hello all,
Based on the suggestion of you wonderful folks here, I went away for a few days (to learn about PDO and Prepared Statements) in order to replace the MySQLi commands in my code. That's gone pretty well thus far...with me having learnt and successfully replaced most of my "bad" code with elegant, SQL-Injection-proof code (or so I hope).
The one-and-only problem I'm having (for now at least) is that I'm having trouble understanding how to execute an UPDATE query within the resultset of a SELECT query (using PDO and prepared statements, of course).
Let me explain (my scenario), and since a picture speaks a thousand words I've also inlcuded a screenshot to show you guys my setup:
In my table I have two columns (which are essentially flags i.e. Y/N), one for "items alreay purchased" and the other for "items to be purchased later". The first flag, if/when set ON (Y) will highlight row(s) in red...and the second flag will highlight row(s) in blue (when set ON).
I initially had four buttons, two each for setting the flags/columns to "Y", and another two to reverse the columns/flags to "N". That was when I had my delete functionality as a separate operation on a separate tab/list item, and that was fine.
Now that I've realized I can include both operations (update and delete) on just the one tab, I've also figured it would be better to pare down those four buttons (into just two), and set them up as a toggle feature i.e. if the value is currently "Y" then the button will set it to "N", and vice versa.
So, looking at my attached picture, if a person selects (using the checkboxes) the first four rows and clicks the first button (labeled "Toggle selected items as Purchased/Not Purchased") then the following must happen:
1. The purchased_flag for rows # 2 and 4 must be switched OFF (set to N)...so they will no longer be highlighted in red.
2. The purchased_flag for row # 3 must be switched ON (set to Y)...so that row will now be highlighted in red.
3. Nothing must be done to rows # 1 and 5 since: a) row 5 was not selected/checked to begin with, and b) row # 1 has its purchase_later_flag set ON (to Y), so it must be skipped over.
Looking at my code below, I'm guessing (and here's where I need the help) that there's something wrong in the code within the section that says "/*** loop through the results/collection of checked items ***/". I've probably made it more complex than it should be, and that's due to the fact that I have no idea what I'm doing (or rather, how I should be doing it), and this has driven me insane for the last 2 days...which prompted me to "throw in the towel" and seek the help of you very helpful and intellegent folks. BTW, I am a newbie at this, so if I could be provided the exact code, that would be most wonderful, and much highly appreciated.
Thanks to you folks, I'm feeling real good (with a great sense of achievement) after having come here and got the great advice to learn PDO and prepared statements.
Just this one nasty little hurdle is stopping me from getting to "end-of-job" on my very first WebApp. BTW, sorry about the long post...this is the best/only way I could clearly explaing my situation.
Cheers guys!
case "update-delete": if(isset($_POST['highlight-purchased'])) { // ****** Setup customized query to obtain only items that are checked ****** $sql = "SELECT * FROM shoplist WHERE"; for($i=0; $i < count($_POST['checkboxes']); $i++) { $sql=$sql . " idnumber=" . $_POST['checkboxes'][$i] . " or"; } $sql= rtrim($sql, "or"); $statement = $conn->prepare($sql); $statement->execute(); // *** fetch results for all checked items (1st query) *** // $result = $statement->fetchAll(); $statement->closeCursor(); // Setup query that will change the purchased flag to "N", if it's currently set to "Y" $sqlSetToN = "UPDATE shoplist SET purchased = 'N' WHERE purchased = 'Y'"; // Setup query that will change the purchased flag to "Y", if it's currently set to "N", "", or NULL $sqlSetToY = "UPDATE shoplist SET purchased = 'Y' WHERE purchased = 'N' OR purchased = '' OR purchased IS NULL"; $statementSetToN = $conn->prepare($sqlSetToN); $statementSetToY = $conn->prepare($sqlSetToY); /*** loop through the results/collection of checked items ***/ foreach($result as $row) { if ($row["purchased"] != "Y") { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToY = $statementSetToY->fetch(); foreach($resultSetToY as $row) { $statementSetToY->execute(); } } else { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToN = $statementSetToN->fetch(); foreach($resultSetToN as $row) { $statementSetToN->execute(); } } } break; }CRUD Queston.png 20.68KB 0 downloads Hi and thank you for reading my topic.
I'm building a search engine from a tutorial and I'm getting the famous "Warning: mysql_num_rows() expects parameter 1" boolean etc..
I know mysql_num_rows() is depricated and I promise not to use it in the future but for now I'm using it in other projects on the same server and all's ok.
I'm quite sure it's a problem with the SQL syntax because when I paste SELECT * FROM searchengine WHERE keywords LIKE 'any_keyword_from_the_column' -into Phpmyadmin it won't return results, however a simple SELECT * FROM searchengine returns results.
So, without using mysql_error() I get: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\research2\search.php on line 42
But after I applyin mysql_error() to everything I narrowed it down to this: $query = mysql_query($query) or die (mysql_error());:
I get the error msg:
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 'OR keywords LIKE 'search' OR keywords LIKE 'term'' at line 1
I've checked multiple times to see if I've left out any columns in the db or mismatched them in while loop.
Below I have included the code which you can paste into a file called search.php along with the mysql dump file to pase into phpmyadmin query box. I'm using xampp.
In the code the WHERE clause is extended into the if statement and concatenated into the $query variable. This is done to break the words in the text box so they can be searched as an array.
As I said, I really think it is the SQL syntax and not the mysql_* functions but I could be wrong.
I'd really like to get this code working and mess with it. It looks like it could be very useful as a private website search engine.
Thanks for your time and mental energy.
<html> <head> <title></title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> </head> <body> <h2>Search Engine</h2> <form action = './search.php ' method = 'get'> <input type = 'text' name = 'k' size = '50' value = '<?php echo $_GET['k']; ?>' /> <input type = 'submit' value = 'Search'> </form> <hr /> results <br> <?php $k = $_GET['k']; $terms = explode(" ", $k); $query = "SELECT * FROM searchengine WHERE "; foreach ($terms as $each) { $i = 0; if ($i == 1) $query .= "keywords LIKE '$each' "; else $query .= "OR keywords LIKE '$each' "; } mysql_connect("localhost", "root", "") or die (mysql_error()); mysql_select_db("search2") or die (mysql_error()); $query = mysql_query($query) or die (mysql_error()); $numrows = mysql_num_rows($query) ; if ($numrows > 0) { while ($row = mysql_fetch_assoc($query)) { $id = $row['id']; $title = $row['title']; $description = $row['description']; $keywords = $row['keywords']; $link = $row['link']; echo "<h2><a href='$link'>$title</a></h2> $description<br /><br />"; } } else echo $k ; ?> </body> </html>and here is the SQL dump (I called my db search2 and my table searchengine -- phpMyAdmin SQL Dump -- version 4.2.7.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Nov 27, 2014 at 11:54 AM -- Server version: 5.6.20 -- PHP Version: 5.5.15 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `search2` -- CREATE DATABASE IF NOT EXISTS `search2` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `search2`; -- -------------------------------------------------------- -- -- Table structure for table `searchengine` -- CREATE TABLE IF NOT EXISTS `searchengine` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `description` varchar(250) NOT NULL, `keywords` text NOT NULL, `link` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `searchengine` -- INSERT INTO `searchengine` (`id`, `title`, `description`, `keywords`, `link`) VALUES (1, 'Nick Frosty''s Official Web Site', 'Welcome to Nick''s', 'Nickfrosty Website tutorials videos web design', 'http://www.nickfrosty.com'), (2, 'Google search engine', 'The best search engine', 'google web site search ', 'http://www.google.oom'), (3, 'The Yahoo Search Engine', 'Not as good as Google', 'Yahoo search engine website', 'http://www.google.com'), (4, 'This is a test', 'This is a test website', 'Google', 'http://www.google.com'); -- -- Indexes for dumped tables -- -- -- Indexes for table `searchengine` -- ALTER TABLE `searchengine` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `searchengine` -- ALTER TABLE `searchengine` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;If you have any questions about any details of this code please ask me. Thanks for your time Hi, My issue here is that I cant get my query string variables to ONLY feed into if/else statement on my secondary page. I include my secondary page (fine.php) from my index page. My query string variables keep being fed back into my original if/ese statement on index.php. here is the if/else on index.php (these links work fine): <?php if($_SERVER['QUERY_STRING']=='/index.php' || $_SERVER['QUERY_STRING']=='') { include 'port.php'; } elseif (isset($_GET['pos'])){ include 'pos.php'; } elseif (isset($_GET['web'])){ include 'web.php'; } elseif (isset($_GET['fine'])){ include 'fine.php'; } else {include '404.php';} here is the if/else on my secondary page (fine.php). These links are supposed to alert the if/else in the next table cell. However, they instead alert the if/else in index.php. <td><br/> <a href="?backset"><img src="fine/thumbs/x-backset.jpg" border="0"></a><br/><br/> <a href="?backside"><img src="fine/thumbs/x-backside.jpg" border="0"></a><br/><br/> <a href="?bannerprint"><img src="fine/thumbs/x-bannerprint.jpg" border="0"></a><br/><br/> <a href="?chopu"><img src="fine/thumbs/x-chopu.jpg" border="0"></a><br/><br/> </td> <td><br/> <div id="DivPiece" align="left"> <?PHP if (isset($_GET['backset'])){ include 'fine/backset.php'; } elseif (isset($_GET['backside'])){ include 'fine/backside.php'; } elseif (isset($_GET['bannerprint'])){ include 'fine/bannerprint.php'; } elseif (isset($_GET['chopu'])){ include 'fine/chopu.php'; } ?> </div> </td> How can I get the links on the secondary page to only alert the if/else statement on that page, and BLOCK the if/else statement on index.php from seeing them? I still want to use the query string though. Thanks! [/quote] This isn't the entire code just enough to see what I'm trying to do. Everything was working until I added the mysql update query in the if statement. Is this possible or am I doing something wrong? When I run the script it just echos "No results found" twice as $num_results = 2. Code: [Select] <?php include("../includes/connect.php"); $query = "SELECT ........ "; $result = $db->query($query); $num_results = $result->num_rows; if ($num_results == 0) { exit; } else { $i=0; while ($i < $num_results) { $row = $result->fetch_assoc(); $id = $row['id']; if ($expiration_date > $today) { ### EMAIL CODE HERE ### $update = "UPDATE model SET reminder_sent = '1' WHERE id = '$id' "; $result_2 = $db->query($update); $i++; } else { echo "No results found."; $i++; } } } ?> I need to convert the following select statement to a pdo->query but have no idea how to get it working: SELECT t.id FROM ( SELECT g.* FROM location AS g WHERE g.start <= 16785408 ORDER BY g.start DESC, g.end DESC LIMIT 1 ) AS t WHERE t.end >= 16785408; Here's the code I'm trying: <?php $php_scripts = '../../php/'; require $php_scripts . 'PDO_Connection_Select.php'; require $php_scripts . 'GetUserIpAddr.php'; function mydloader($l_filename=NULL) { $ip = GetUserIpAddr(); if (!$pdo = PDOConnect("foxclone_data")) { exit; } if( isset( $l_filename ) ) { $ext = pathinfo($l_filename, PATHINFO_EXTENSION); $stmt = $pdo->prepare("INSERT INTO download (address, filename,ip_address) VALUES (?, ?, inet_aton('$ip'))"); $stmt->execute([$ip, $ext]) ; $test = $pdo->prepare("SELECT t.id FROM ( SELECT g.id FROM lookup AS g WHERE g.start <= inet_aton($ip) ORDER BY g.start DESC, g.end DESC ) AS t WHERE t.end >=inet_aton($ip)"); $test ->execute() ; $ref = $test->fetchColumn(); $ref = intval($ref); $stmt = $pdo->prepare("UPDATE download SET ref = '$ref' WHERE address = '$ip'"); $stmt->execute() ; header('Content-Type: octet-stream'); header("Content-Disposition: attachment; filename={$l_filename}"); header('Pragma: no-cache'); header('Expires: 0'); readfile($l_filename); } else { echo "isset failed"; } } mydloader($_GET["f"]); exit; It gives the following error: QuoteFatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.144.181) ORDER BY g.start DESC, g.end DESC ) AS t WHERE t.end >=inet_aton(7' at line 1 in /home/foxclone/test.foxclone.com/download/mydloader.php:19 Stack trace: #0 /home/foxclone/test.foxclone.com/download/mydloader.php(19): PDO->prepare('SELECT t.id FRO...') #1 /home/foxclone/test.foxclone.com/download/mydloader.php(38): mydloader('foxclone40a_amd...') #2 {main} thrown in /home/foxclone/test.foxclone.com/download/mydloader.php on line 19 How do I fix this? I am making a space game. The game requires a map. The map needs to contain one or more galaxies. Each galaxy should have from 100 to 1000 star systems. Each star system needs to possess a random number of planets from 1-10. I suspect that I can use while loops to control the number of galaxies star systems and planets, but I need to know how to assign coordinates when making the universe. This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=321234.0 Hey, I was wondering if there is a way to pull multiple rows at once using a list of unique identifiers. For example, I want to pull the rows with the IDs of 4,13,91 and 252 I know the WHERE part of this query is incorrect, but I'm putting it to hopefully help you guys understand what I'm looking for. $result = mysql_query("SELECT * FROM $table WHERE id='4' OR '13' OR '91' OR '252'"); while($row = mysql_fetch_array($result)) { echo($row['name']); } Or is the best way simply to do it one query at a time without a while statement? There could be as many as a few dozen records being pulled per page. I'm trying to create a INSERT query statement that makes use of the content of 'include' files. When I call up the include it simply echos it to the screen but I can't seem to capture the text string and actually make it function as part of the query. I've tried setting the include as a variable but again it only outputs to the screen. Help please! Here's a portion of the code... if (($_POST['sched_templates']) == "sched_TestingOnly.htm") { $query = include 'sched_TestingOnlyQuery1.htm'; } if (@mysql_query ($query)) { mysql_close(); // End adding Registration to the database header ('Location: redirectfile.htm'); exit(); } else { print "<p><b>Sorry, your entry could not be entered. } Folks,
Look what I found he My procedural style code is this alongside their OOP:
<?php if (!$conn) { $error = mysqli_connect_error(); $errno = mysqli_connect_errno(); print "$errno: $error\n"; exit(); } // Get the total number of records from our table "students". $total_pages = $conn->query('SELECT * FROM browsing_histories')->num_rows; //I NEED HELP TO SUBSTITUTE THIS TO PROCEDURAL STYLE // Check if the page number is specified and check if it's a number, if not return the default page number which is 1. $page = isset($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1; // Number of results to show on each page. $num_results_on_page = 5; // if ($stmt = $conn->prepare('SELECT * FROM following_histories ORDER BY id LIMIT ?,?')) { if($query = "SELECT id,date_and_time,query_type,followed_word,query_string,browsed_page_original,browsed_page_converted,referral_page_original,referral_page_converted,username,gender,age_range,date_of_birth,skin_complexion,height,weight,sexual_orientation,religion,education,profession,marital_status,working_status,country_of_birth,home_town,home_neighbourhood,home_borough,home_council,home_city,home_county,home_district,home_region,home_state,home_country FROM browsing_histories WHERE username = ? ORDER BY id LIMIT ? OFFSET ?"){ //my substitution of above line $stmt = mysqli_prepare($conn,$query); //MY SUBSTITUTION OF ABOVE LINE // Calculate the page to get the results we need from our table. $calc_page = ($page - 1) * $num_results_on_page; //$stmt->bind_param('ii', $calc_page, $num_results_on_page); mysqli_stmt_bind_param($stmt,'sii',$followee_username,$calc_page,$num_results_on_page); //MY SUBSTITUTION OF ABOVE LINE //$stmt->execute(); mysqli_stmt_execute($stmt); //MY SUBSTITUTION OF ABOVE LINE // Get the results... //$result = $stmt->get_result(); $result = mysqli_stmt_get_result($stmt) //MY SUBSTITUTION OF ABOVE LINE ?> <!DOCTYPE html> <html> <head> <title>PHP & MySQL Pagination by CodeShack</title> <meta charset="utf-8"> <style> html { font-family: Tahoma, Geneva, sans-serif; padding: 20px; background-color: #F8F9F9; } table { border-collapse: collapse; width: 500px; } td, th { padding: 10px; } th { background-color: #54585d; color: #ffffff; font-weight: bold; font-size: 13px; border: 1px solid #54585d; } td { color: #636363; border: 1px solid #dddfe1; } tr { background-color: #f9fafb; } tr:nth-child(odd) { background-color: #ffffff; } .pagination { list-style-type: none; padding: 10px 0; display: inline-flex; justify-content: space-between; box-sizing: border-box; } .pagination li { box-sizing: border-box; padding-right: 10px; } .pagination li a { box-sizing: border-box; background-color: #e2e6e6; padding: 8px; text-decoration: none; font-size: 12px; font-weight: bold; color: #616872; border-radius: 4px; } .pagination li a:hover { background-color: #d4dada; } .pagination .next a, .pagination .prev a { text-transform: uppercase; font-size: 12px; } .pagination .currentpage a { background-color: #518acb; color: #fff; } .pagination .currentpage a:hover { background-color: #518acb; } </style> </head> <body> <table> <tr> <th>Name</th> <th>Age</th> <th>Join Date</th> </tr> <?php while ($row = $result->fetch_assoc()): ?> <tr> <td><?php echo $row['id']; ?></td> <td><?php echo $row['followee_username']; ?></td> <td><?php echo $row['follower_username']; ?></td> </tr> <?php endwhile; ?> </table> <?php if (ceil($total_pages / $num_results_on_page) > 0): ?> <ul class="pagination"> <?php if ($page > 1): ?> <li class="prev"><a href="pagination.php?page=<?php echo $page-1 ?>">Prev</a></li> <?php endif; ?> <?php if ($page > 3): ?> <li class="start"><a href="pagination.php?page=1">1</a></li> <li class="dots">...</li> <?php endif; ?> <?php if ($page-2 > 0): ?><li class="page"><a href="pagination.php?page=<?php echo $page-2 ?>"><?php echo $page-2 ?></a></li><?php endif; ?> <?php if ($page-1 > 0): ?><li class="page"><a href="pagination.php?page=<?php echo $page-1 ?>"><?php echo $page-1 ?></a></li><?php endif; ?> <li class="currentpage"><a href="pagination.php?page=<?php echo $page ?>"><?php echo $page ?></a></li> <?php if ($page+1 < ceil($total_pages / $num_results_on_page)+1): ?><li class="page"><a href="pagination.php?page=<?php echo $page+1 ?>"><?php echo $page+1 ?></a></li><?php endif; ?> <?php if ($page+2 < ceil($total_pages / $num_results_on_page)+1): ?><li class="page"><a href="pagination.php?page=<?php echo $page+2 ?>"><?php echo $page+2 ?></a></li><?php endif; ?> <?php if ($page < ceil($total_pages / $num_results_on_page)-2): ?> <li class="dots">...</li> <li class="end"><a href="pagination.php?page=<?php echo ceil($total_pages / $num_results_on_page) ?>"><?php echo ceil($total_pages / $num_results_on_page) ?></a></li> <?php endif; ?> <?php if ($page < ceil($total_pages / $num_results_on_page)): ?> <li class="next"><a href="pagination.php?page=<?php echo $page+1 ?>">Next</a></li> <?php endif; ?> </ul> <?php endif; ?> </body> </html> <?php //$stmt->close(); mysqli_stmt_close($stmt); //MY SUBSTITUTION OF ABOVE LINE } ?> Edited February 2, 2019 by phpsane Hi All, I have the following code which works fine: $mysqli = new mysqli("server", "user", "pass", "database"); if($mysqli->connect_error) { exit('Could not connect'); } $sql = "SELECT customer_contactname, customer_companyname, customer_phonenumber, customer_emailaddress, customer_address1, customer_address2, customer_city, customer_postcode FROM ssm_customer WHERE customer_id = ?"; $stmt = $mysqli->prepare($sql); $stmt->bind_param("s", $_GET['q']); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($ccontname, $ccompname, $cphoneno, $cemail, $cad1, $cad2, $ccity, $cpost); $stmt->fetch(); $stmt->close(); however, when i use my dbconn.php as an include rather than the top section of this code, i get the following error: function prepare() on null The error references the following $stmt = $mysqli->prepare($sql); In my database connection file, i am using the following: $conn = mysqli_connect($db_servername, $db_username, $db_password, $db_name); This seems to be the issue and i believe i am mixing procedural and object based but not sure why there should be a difference here? when i used my database connection file, i do change $mysqli->prepare to $conn->prepare Kind Regards Edited February 4, 2019 by AdamhumbugI need to check if in databaseA (shown below as applicant) it says "PendingGroupA" if yes echo "something" and if not to check databaseB (shown below as comp) for the username and password. Then upon successful username and password entry echo "message B". And if username and password fails to echo "message C". How can I write this correctly? $result=mysql_query("SELECT * FROM comp WHERE username = '$useid' AND pass ='$pass'"); if(mysql_num_rows ($result) == 0) { $login = "&err=Login Failed. Please retry."; echo($login); } elseif { $row = mysql_fetch_array($result); $user=$row['user']; $pass=$row['pass']; $login = "$user=" . $user . "$pass=" . $pass . "&err=Login Successful."; echo($login); } else { $resultA=mysql_query("SELECT * FROM applicant WHERE username = '$useid' AND statusA ='PendingGroupA'"); $peningGA = "&err=Please be patient!"; echo($peningGA); } I have 99% of the code written but I still need a line or two but can't figure it out. Due_Attny is a date field. This code looks at my MySQL database & if the due_attny field is between todays date & the trigger date it will send an email to the $email variable. There is also a field in my MySQL database named a_mail_sent that by default is set to 0 which means an email has not been sent. I need to edit this code so it will look at the a_email_sent field & if the value is 0, it sends the email & updates the a_email_sent field to 1 which means the email has been sent. If the a_mail_sent field has a value of 1, I don't need the email to be sent. Can somoeone help me out with this code? Thanks Code: [Select] <?php include('connection.php'); // DB connection // Constants $number_of_days_before = 6; $email = "emailaddress@mail.org"; $reminder_details = ""; $todays_date = date( "Ymd" ); echo $todays_date; $year = substr($todays_date, 0, 4); $month = substr($todays_date, 4, 2); $date = substr($todays_date, 6, 2); $trigger_date = date("Ymd", mktime(0,0,0,$month, $date+$number_of_days_before,$year)); $insertquery = "UPDATE psrinfo SET a_mail_sent=1 WHERE employee='Employee1'"; mysql_query($insertQuery) or die ('Error updating database'); echo $trigger_date; $result = mysql_query( "SELECT a_mail_sent, due_attny, employee, pacts, dock, fname, lname FROM psrinfo WHERE employee='Employee1' AND due_attny BETWEEN $todays_date AND $trigger_date" ); $nr = mysql_num_rows( $result ); while( $row = mysql_fetch_array( $result ) ) { $reminder_details .= "Name: ".$row["fname"]." ".$row["lname"]."\n"; $reminder_details .= "PACTS Number: ".$row["pacts"]."\n"; $reminder_details .= "Dock: ".$row["dock"]."\n"; $reminder_details .= "Due to Attny: ".$row["due_attny"]."\n\n\n"; } mysql_free_result( $result ); if( !empty( $nr ) ) { // Send reminder email $mailheader = "From: Reminder System <$email>\nX-Mailer: Reminder\nContent-Type:text/plain"; mail("$email", "PSR Due Within 6 Days", "$reminder_details", "$mailheader"); } ?> $name value is coming through from form submission.
<?php } If statement is not working properly. Whether $name is empty or not, it adds the where clause. ?>
<?php I have this simple form that registers schools. This year I have decide to upgrade and include a feature that checks if the school is already registered or not based on the imputed name. Here is the code (that is the only way I know how): mysql_connect("", "", "") or die(mysql_error( '' )); mysql_select_db("") or die(mysql_error( '' )); $query = "SELECT * FROM School_Registrations WHERE School_Name= '$_POST[SchoolName]' "; $result = mysql_query($query); if (mysql_numrows($result) > 0) { while($row = mysql_fetch_array($result)) echo" error code here";} else {mysql_query("INSERT INTO `database`.`School_Registrations` (all the variables here);") or die(mysql_error( '' )); echo "Success Code";} I am trying to incorporate this code somewhere into the 'else' statement but I have no luck. I am constantly getting some errors and when I fix one there is one more to take its place. I am lost. The last one I can not fix and I am not sure what it wants from me: Fatal error: Call to undefined function getPage() It works by itself without the if/else statement but not in the code listed above $url = 'http://www.otherpage.com/page.php?'; $url .= 'email='.urlencode($_POST['email']); $result2 = getPage('', $url, '', 15); function getPage($proxy, $url, $header, $timeout) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXY, $proxy); curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_REFERER, 'http://azsef.org'); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8'); $result2['EXE'] = curl_exec($ch); $result2['INF'] = curl_getinfo($ch); $result2['ERR'] = curl_error($ch); curl_close($ch); return $result2; } Can you tell me why doesn't it work? Thanks create table mimi (mimiId int(11) not null, mimiBody varchar(255) ); <?php //connecting to database include_once ('conn.php'); $sql ="SELECT mimiId, mimiBody FROM mimi"; $result = mysqli_query($conn, $sql ); $mimi = mysqli_fetch_assoc($result); $mimiId ='<span>No: '.$mimi['mimiId'].'</span>'; $mimiBody ='<p class="leading text-justify">'.$mimi['mimiBody'].'</p>'; ?> //what is next? i want to download pdf or text document after clicking button or link how to do that Hey everyone, im having problems querying the results from the database using this query.... $get_points = mysql_query("SELECT * FROM points WHERE ACOS( (SIN(PI() * '41.896301269531' / '180') * SIN(PI() * latitude / '180')) + (COS(PI() * '41.896301269531' /'180') * COS(PI() * latitude / '180') * COS(PI() * longitude / '180' - PI() * '-88.744201660156' / '180')) )* '180' / PI() * '60' * '1.1515' <= '80'") or die(mysql_error()); Basically what it does it checks the for location with in 80 miles of the lat and long coordinates. The problem is no result are showing up. I know there are locations because i tested this as an sql code in my database and it ran perfectly, but i can't get it to work using php.. I get no errors, nothing. can anyone help me out? |