disable php function with other function - php

I was wondering if there's a way to disable an existing php-function (or a part) when calling another function.
My situation is the following:
I have a php search function with a text input. This works fine. (See code below)
if(isset($_POST['search'])){
if(isset($_GET['go'])){
if(preg_match("/[A-Z | a-z]+/", $_POST['search'])){
$input=$_POST['search'];
//connects to database
//selects database table
//searches database
//assigns $results variable
//outputs results:
while($row=mysql_fetch_array($result)){
echo 'results...';
}}}} else {
//connects to database
//selects database table
//searches database:
$sql="SELECT * FROM table";
//outputs results (same as above)
}
so that's a very short form of my working search function. Below this very search function I have a button that - when clicked - should output the search results for one specific string. This works as well. The problem is that when this very button is clicked, it also shows the "else-part" of the function above, when I only want it to show the results for that specific string, and no other "table items"...
Now follows the code for the search-for-one-specific-string part:
function results_for_one_specific_string () {
//connects to database
//searches database:
$sql="SELECT * FROM table WHERE Name='string'";
//outputs results (same as above)
}
if (isset($_GET['button123'])) {
results_for_one_specific_string ()
}
Just to let you know, in order to call function results_for_one_specific_string () I use something like this:
title
Now my question is: Does anybody know how I can somehow 'disable' the "else-part" of my search function (1st block of code) only when the function results_for_one_specific_string () is called? (so that only the results of this function are printed and not the 'else' party of the first function as well)
thank you guys!

Would something like this work for you?
$hasBeenCalled = false; // Set a global var
function results_for_one_specific_string () {
//connects to database
//searches database
//outputs results
}
if (isset($_GET['button123'])) {
$hasBeenCalled = true; // Update global var here
results_for_one_specific_string ()
}
...
if(isset($_POST['search'])){
//connects to database
//searches database
//outputs results
} else if($hasBeenCalled==false){ // Check for global var here
//outputs all table items (not only the search results, everything!)
}

To me it seems you're having identical code for searching the custom string as well as for the specific string. If this is true, it would be easier and more transparent to make one function for both cases:
function results_for_any_string ($search='') {
if(strlen($search>0)){
//connects to database
//searches database
//outputs results
}
else {
//outputs all table items (not only the search results, everything!)
}
}
In the main script choose what you want to use as parameter.
if(isset($_POST['search'])) $parameter = $_POST['search'];
else if (isset($_GET['button123'])) $parameter = $_GET['button123'];
else $parameter='';
results_for_any_string ($parameter);
}
Also if noth buttons are in one form you can submit the specific value also through the same form and as POST. Not mixing post and get. See for example this post.

Related

Print a Conditioned COUNT query with PHP

I need some help with PHP, i wanna print a value from a COUNT(*) query but it's conditioned, my code:
<?php
require ('../login/conexion.php');
session_start();
if(!isset($_SESSION["id_usuario"])){
header("location: ../login/");
}
//I wanna do this
$consulta_OD = '';
function query_()
{
global $conexion, $consulta_OD;
$sql = 'SELECT COUNT(*) as total from gok_registro WHERE estado=3';
return $conexion->query($sql);
}
$consulta_OD = query_OD();
$costo_OD = $consulta_OD->fetch_assoc();
echo $costo_OD['total'];
?>
By the way, the connection to a BD is good since my code works, without the lines after the "//i wanna do this" comment. The query also works in the console.
The last line is to print the query in another part of the document, any help?
Your SQL request looks good.
But:
the function query_ is never call
the function query_OD not exist
global $consulta_OD; is not used in the function query_ so useless
If you rename query_ by query_OD your code should work

issue with getting result object of mysql query into a function

I have a function to process info from a database. This is called multiple times in a page. And I don't want to query the database every time. So I put the query outside. If I do that, the function doesn't work. I know this can be done because, there was a similar question somewhere in SO. But that addressed a different situation. I don't know what is wrong here. Any help will be greatly appreciated.
If I put all this code into a separate test file including the conn file and query, it works. But in my main page, where I have the functions.php included first, then conn.php and then the query and then the display code called by js fadein event, the $result refuses to work inside the function
EDIT : This code has been cleaned up as per comments received (globals replaced with variables passed to the function and variable names rationalised)
function total($item,$result,$val){
global $totRate;
while($getRates=$result->fetch_assoc()){
$gotItem= strtolower(preg_replace('/[^(\x20-\x7F)]*/',"",$getRates['item']));
$gotItem=str_replace(array("_"," ","/"),"",$gotItem);
if($item==$gotItem){
$rate= $getRates['rate'];
$totRate=$val*$rate;
return $totRate;
}
}
}
The Result Call PHP file
$query = "SELECT * FROM rates ORDER BY item";
$result = $orderdb->query($query)
if (isset($_POST[$itemname]) && !empty($_POST[$itemname])) {
$val=$_POST[$itemname];
total($itemname);
echo $totprate;
} else {
echo "0";
}
I am writing this with the assumption that your SQL is working but are having problems displaying what you want - this may help. The code below saves your $result variable from your query and then passes it into the total function as a second parameter. Previously you were returning $totprate from total but you were not saving it anywhere - it is now saved to the $totprate variable.
Note: I cannot see $orderdb anywhere in your code, I'm assuming you have that in your file and that it is working.
function total($item, $result){
global $val;
global $pid;
global $pitem;
global $prate;
global $totprate;
global $gotitem;
global $getratess;
// global variable for $result removed so it doesn't overwrite variable passed to function
while($getratess=$result->fetch_assoc()){
$gotitem= strtolower(preg_replace('/[^(\x20-\x7F)]*/',"",$getratess['item']));
$gotitem=str_replace(array("_"," ","/"),"",$gotitem);
if ($item==$gotitem) {
$pid=$getratess['id'];
$pitem= $getratess['item'];
$prate= $getratess['rate'];
$totprate=$val*$prate;
return $totprate;
}
}
}
$query = "SELECT * FROM rates ORDER BY item";
$result = $orderdb->query($query);
if (isset($_POST[$itemname]) && !empty($_POST[$itemname])) {
$val=$_POST[$itemname];
$totprate = total($val, $result); // pass itemname as first parameter and result array as second parameter and save it to the $totprate variable
echo $totprate;
} else {
echo "0";
}
Let me know if this helps.

PHP Variable inURL

I have a display page pulling from a database. With that I have a display function. I have everything working correctly, but I want to change the variable that is visible at the end of the URL, now it is from the 'id' column in my database and I would like it to be from the 'name' column.
This is my display function (included in another file)
public function __construct($rid, $table) {
/* Connect to Database */
require('dbinfo.php');
//$table=$this->table; // Choose Table Optional
$link = mysql_connect($databaseip,$username,$password);
mysql_select_db($database,$link);
$query = "SELECT * FROM $table WHERE rid=$rid";
$result=mysql_query($query);
$this->result = $result;
mysql_close($link);
And the Get PHP in the header of the display page is as follows:
<?php
$rid = $_GET['r'];
require('func/recipe.php');
// Recipe Display Function
if (isset($_GET['r'])) {$recipe = new recipeObject($rid,'my table name');} else {
header('location: SET URL');
}
?>
And my database structure looks like this - https://www.dropbox.com/s/rfga1vl8miqcd9s/database.png?dl=0
So I missed this big time the first time around. My apologies. Here is what I found to work for the query portion. And should help with SQL Injections.
$termSafe = mysql_real_escape_string($rid);
$query = "select * FROM $table WHERE (name LIKE '$termSafe')";

PHP jQuery: Passing a PHP variable FROM (not to) $.load()

I've seen questions asking about sending variables TO a document being loaded in $.load, but not retrieving variables from a $.load.
I've pasted the pertinent pieces of code below; essentially what I'm trying to do is run a PHP function every so often, and initially when the page first loads.
When the page first loads, it runs the getData function - and everything works as intended. But later down the page, when I try to load pullData.php, srcAverage doesn't update with the new value. The JS alert shows the srcAverage value.
Example: The first time the page is run, srcAverage is X. Every 5 seconds, we want to load pullData.php and update srcAverage on index.php with the new value (change X).
I feel like it's something really small I'm doing incorrectly - ideas?
conn.php
<?php
define("HOST", "stuff");
define("USER", "stuff");
define("PASSWORD", "stuff");
define("DATABASE", "stuff");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
// Connection info above all works as intended
?>
index.php
<?php
include 'inc/conn.php';
include 'inc/function.php';
$src = "none";
getData($src, $mysqli);
// This initial run of getData works as intended
// Skip to further down
// The JS alert below does NOT reflect the new srcAverage
?>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
// each interval, get first and second values
$("#targetDiv").load("pullData.php");
alert('New value is <?php echo $srcAverage; ?>');
}, 5000); // end setInterval
});
</script>
pullData.php
<?php
include 'incl/conn.php';
include 'incl/function.php';
$src = "none";
getData($src, $mysqli);
?>
The getData function (see code below) grabs 4 values from separate tables, averages them together (I have them all separated in different statements and variables for troubleshooting purposes), then sets the variable srcAverage to the average value. I've tested that the MySQLi statements are working fine, and srcAverage is assigned the correct value by the function. Echoing or JS alerting show the value as intended (on this page). But the variable does NOT get passed to index.php when loaded via load().
function.php
<?php
function getData($src, $mysqli) {
// Check SRC for specific source
// If no specific source, get average of all sources
// If YES specific source, get that value
global $srcAverage;
if ($src == 'alt') {
if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($altVal); // get variables from result.
$stmt->fetch();
if($stmt->num_rows == 1) { // The entry exists, good to go
// echo $altVal;
}
} else {
// Either no results pulled or more than one.
echo "Error pulling alternate data!";
return false;
}
}
else {
// Value 1
if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($firstVal); // get variables from result.
$stmt->fetch();
if($stmt->num_rows == 1) {
// echo $firstVal; // This works as intended
}
} else {
// Either no results pulled or more than one.
echo "Error pulling first value data!";
return false;
}
// Value 2
if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($secondVal); // get variables from result.
$stmt->fetch();
if($stmt->num_rows == 1) { // The entry exists, good to go
// echo $secondVal;
}
} else {
// Either no results pulled or more than one.
echo "Error pulling second value data!";
return false;
}
// Value 3
if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($thirdVal); // get variables from result.
$stmt->fetch();
if($stmt->num_rows == 1) { // The entry exists, good to go
// echo $thirdVal;
}
} else {
// Either no results pulled or more than one.
echo "Error pulling third value data!";
return false;
}
// Value 4
if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($fourthVal); // get variables from result.
$stmt->fetch();
if($stmt->num_rows == 1) { // The entry exists, good to go
// echo $fourthVal;
}
} else {
// Either no results pulled or more than one.
echo "Error pulling fourth value data!";
return false;
}
// So everything up to this point is working fine. Statements grab data as intended, and assign variables.
// We have data - move forward
$srcCount = 4;
$srcTotal = $firstVal + $secondVal + $thirdVal + $fourthVal;
$srcAverage = $srcTotal / $srcCount;
$srcAverage = number_format((float)$srcAverage, 2, '.', '');
// echo "Total: $srcTotal .... Average: $srcAverage";
// If we were to echo above, it would display correctly. Problem is passing the variable to index
return $srcAverage;
}
}
?>
You're misunderstanding the php page lifecycle. <?php echo $srcAverage; ?> is evaluated only once when the page is initially loaded/rendered.
If you want to get the new value, you should probably switch over to using $.ajax() instead of .load(), and have pullData.php echo the result as json so you can work with the response in javascript.
Your problem is you are echoing out $srcAverage through php. The browser doesn't get php from the server or know how to execute it, it only sees the result of the php script. So, if you view source you will see that all your alert is is:
alert('New value is ');
The php already ran, $srcAverage when it was echoed was undefined due to scope so it put a null which converts to an empty string.
What gets loaded by $.load is the result of pullData.php, already parsed by php and returned through the server. pullData.php has no output. You need to echo the result of getData so that the javascript can see it.
What you need to be doing in javascript is:
alert('New value is ' + $('#targetDiv').html());
Based on your example markup you also seem to be missing #targetDiv. You probably want to wrap your original getData in #targetDiv.
So, your fixed version looks like this:
index.php
<div id='targetDiv'>
<?php
include 'inc/conn.php';
include 'inc/function.php';
$src = "none";
echo getData($src, $mysqli);
// This initial run of getData works as intended
// Skip to further down
// The JS alert below does NOT reflect the new srcAverage
?>
</div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
// each interval, get first and second values
$("#targetDiv").load("pullData.php");
alert('New value is ' + $('#targetDiv').html();
}, 5000); // end setInterval
});
</script>
pullData.php
<?php
include 'incl/conn.php';
include 'incl/function.php';
$src = "none";
echo getData($src, $mysqli);
?>
Pass it as a new argument
$("#element").load("file.php", { 'myVar' : 'someValue'} );
Then on the server:
$_POST['myVar'];
will contain the value.
Edit
Maybe I mis understood, if you want to access data from the load function, you need to use the callback.
$('#element').load('file.php', function(data){
//response from the server
});

How to get jquery autocomplete to display only terms that begin with the typed query

Context
I am adding autocomplete function to the search engine at motherpipe.co.uk.
I want it to only suggest terms that begin with the letters typed in by the user. For example, if the user types "lon" the function should return ten suggestions that begin with "lon".
I have about 50,000 terms in a local database
I have managed to get the autocomplete up and running, working with a separate php script that calls the database (sql).
Problem
My problem is that to begin with the top ten listings in the database (based on id) are shown regardless of what the user is typing in. It is only after the user types a further letter that suggestions appear correctly.
Question
How can I modify either jquery or the php code to make sure that ONLY terms that begin with what is typed in are returned (and then only the top ten terms in that subset based on the id.)?
HTML
<script type="text/javascript" src="/scripts/autocomplete/autocomplete/jquery.js"></script>
<script type="text/javascript" src="/scripts/autocomplete/autocomplete/jquery.autocomplete.js"></script>
<script>
$(document).ready(function(){
$("#tag").autocomplete("/scripts/autocomplete/autocomplete/autocomplete.php", {
selectFirst: false,
minChars: 2
});
});
</script>
PHP
<?php
$q=$_GET['q'];
$mydata=mysql_real_escape_string($q);
$mysqli=mysqli_connect('localhost','username','password','languages') or die("Database Error");
$sql="SELECT searchterms FROM topterms WHERE searchterms LIKE '$mydata%' ORDER by id";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
if($result)
{
while($row=mysqli_fetch_array($result))
{
echo $row['searchterms']."\n";
}
}
?>
With the new version of jQuery autocomplete when you use a URL as a source (like you do):
You must return JSON data:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP).
The GET argument you receive is 'term', not 'q'
The Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results.
The proper way to use real escape with mySQL in PHP is to use it after the connection has been established, in your case:
$q = $_GET['term'];
$mysqli = mysqli_connect('localhost','username','password','languages');
if (!$mysqli or $mysqli->connect_error) die("Database Error");
$mydata = $mysqli->real_escape_string($q);
$sql = "SELECT searchterms FROM topterms WHERE searchterms LIKE '$mydata%' ORDER by id";
$result = mysqli_query($mysqli,$sql);
$json = array();
if ($result and $result->num_rows > 0) {
while($row=mysqli_fetch_array($result)) {
$json[] = $row['searchterms'];
}
}
header('Content-Type: application/json'); // You can skip that because IE doesn't really like it
echo json_encode($json);

Categories