Strange problem in php with % inside sql command - php

I have a php file that gets some arguments to pass them to sql command. The first one is this:
if (isset ($_GET['pedio'])){
$pedio = " ` pedio ` LIKE '%" . $_GET['pedio'] . "%'";
}
With this form, the code is not running. The problem is "%'". If I remove % from "%'" then the code is running but it not what I want to take as expression. I tried:
$pedio = " `pedio` LIKE '%" . $_GET['pedio'] . chr(37) . "'";
but it didn't help. If i change chr(37) to chr(38) then the code is running but I have & in the end of the expression, not %. What is wrong with it? Any solutions?
EDIT:
my code:
<?php
if (isset($_GET['pedio'])) {
$pedio = " pedio LIKE '%$pedio%'";
}
if (isset($_GET['instit_type'])) {
if ($pedio != "") {
$instit_type = " AND";
}
$instit_type.= " instit_type = '" . $_GET['instit_type'] . "'";
}
if (isset($_GET['city'])) {
if ($pedio != "" || $instit_type != "") {
$city = " AND";
}
$city.= " city = '" . $_GET['city'] . "'";
}
echo "<p>" . $pedio . " , " . $instit_type . " , " . $city . "</p>";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM schools WHERE"; . $pedio;
// . $instit_type . $city . $category;
// echo $sql; $result = $conn->query($sql);
This modification is not working either:
if (isset ($_GET['pedio']))
{
switch ($_GET['pedio']){
case 1:
$pedio = " `pedio` LIKE '%1%'";
case 2:
$pedio = " `pedio` LIKE '%2%'";
case 3:
$pedio = " `pedio` LIKE '%3%'";
case 4:
$pedio = " `pedio` LIKE '%4%'";
}
}
Now, I noticed that
$pedio = " `pedio` = '%1%'";
code is running with no problem but the sql command is wrong and no results are returned. Replacing LIKE with = eliminates my problem? How is this possible? What is going on anyway?

Its worth an answer.
If your base Query starts with $sql = "SELECT * FROM schools WHERE";, you need to manipulate the current variable by adding a . before = src.
Full code example
ATTENTION This example isnt secure! Use prepared statements instead.
<?php
$baseSql = "SELECT * FROM school";
if(isset($_GET['pedio'])) {
$baseSql .= "WHERE pedio LIKE '%" . $_GET['pedio'] . "%'";
}
?>

You can try the following :
$variable = $_GET['pedio'];
$pedio = "pedio LIKE '%$variable%'";

Related

Multiple if else in mysql query

I have re-written this question because of all the down votes and it would seem that either no one understood the question or was unwilling to help a newbie. So I'll as it this way: Can someone tell/show me why this code does not work? (500 error)
OR... at the very least point me in the right direction? I AM WILLING TO LEARN, I just don't know where to begin or who/where to learn from as I am not sure what to even ask other than how do you run multiple "else" statements... that however left me more confused than I already am though!
Any "HELP" would be greatly appreciated!
<?php
$servername = "localhost";
$username = "****";
$password = "***";
$dbname = "***";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$bname = $_POST['bname'];
$baddress = $_POST['baddress'];
$bcity = $_POST['bcity'];
$bstate = $_POST['bstate'];
$zipcode = $_POST['zipcode'];
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Login FROM `USERS` WHERE Business_Name = '" . $_POST["bname"] . "' AND Business_Address = '" . $_POST["baddress"] . "' AND Business_State = '" . $_POST["bstate"] . "' AND Business_Zip = '" . $_POST["zipcode"] . "' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while ($row = $result->fetch_assoc())
{
echo "https://www.***.com/realsite.php?Login=" . $row["Login"] . "";
}
}
else
{
$sql = "SELECT Login FROM `DATA` WHERE Business_Name = '" . $_POST["bname"] . "' AND Business_Address = '" . $_POST["baddress"] . "' AND Business_State = '" . $_POST["bstate"] . "' AND Business_Zip = '" . $_POST["zipcode"] . "' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while ($row = $result->fetch_assoc())
{
echo "https://www.***.com/demo.php?Login=" . $row["Login"] . "";
}
}
else
{
$sql = "INSERT INTO `DATA` (Business_Name, Business_Address, Business_City, Business_State, Business_Zip)
SELECT '$bname', '$baddress', '$bcity', '$bstate', '$zipcode' FROM (SELECT 1) t
WHERE NOT EXISTS (SELECT Login, Business_Name,Business_Address FROM `DATA` WHERE Business_Name='$bname' AND Business_Address='$baddress')";
if (mysqli_query($conn, $sql))
{
echo "<a href='https://www.servedwell.com/realsite.php?Login=" . $row["Login"] . "'>LINK</a>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
}
?>
Credit goes to #Ancaron for properly formatting code and correcting a syntax error. Final posted code works fine.

PHP, MySQL stored procedure not storing data as expected

There does not seem to be a repeat of this question and I feel this should be a simple fix.
I have tested the stored procedure and when adding the parameters it works fine,
I have also tested a simple SQL statement which also works as expected.
However, when I try to pass my variables into the statement, I get a "Zero results using SQL:" I have also tried to do this as just a prepared statement or as just pure SQL with my variables, but again it never stores anything in the database.
The debug output shows what I am trying to pass, but nothing goes into the database
Here is the full code
require_once (getcwd() . "/lib/dataLib.php");
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (isset($_POST['btnSubmit']))
{
$projectName = $_POST['projectName'];
$projectDescription = $_POST['projectDescription'];
$projectLink = $_POST['projectLink'];
addItemToDatabase($projectName, $projectDescription, $projectLink);
}
}
/********************************
* addItemToDatabase
*******************************/
function addItemToDatabase($name, $description, $link)
{
$projectLinkSanSpace = str_replace(' ', '', $link);
$projectLinkAsLink = "<a href='project/" . $projectLinkSanSpace . "'>" . $link . "</a>";
databaseConnection('programWork');
$conn = new mysqli(DBF_SERVER, DBF_USER, DBF_PASSWORD, DBF_NAME);
if ($conn -> connect_error)
{
die("Connection Failed!: " . $conn ->connect_error);
}
/*$sql = 'insert into projectList (
*projectName,
*projectDescription,
*projectPage,
*projectSource)
*Values ("Stuff", "Things", "Yeah", "Yeah")'; */
$sql = "call insertItemIntoWork($name, $description, $projectLinkAsLink, $projectLinkAsLink)";
$result = $conn->query($sql);
displayResult($result, $sql);
}
some notes on the code,
I am using a lib to call external functions which I did not copy/paste here, as I do not think they are relevant to the question. I also did not include the HTML bits which is just the form which should be fairly straight forward, and should work since the debug displayResults() shows values.
Bottom line question is, is there something procedural that I am screwing up here. I do not have to call a function I suppose but is this a situation where the variables are set after the query is ran?
UPDATE
I added an error handler per Jay below:
$echoSuccess = true;
$msg = "The query completed successfully";
if ($conn->query($sql) === TRUE)
{
if ($echoSuccess)
{
echo "<span class='errMsg'>" . $msg . " successful.</span><br />";
}
} else
{
echo "<strong>Error when: " . $msg . "</strong> using SQL: " . $sql . "<br />" . $conn->error;
//displayResult($result, $sql)
}
Saying there are errors in my SQL.
I think I can work those out and on account of that I do not think this question needs further answering, but rather illustrates the need of error handlers
So,
Thank you Jay Blanchard for pointing me in the right direction, turns out the spaces in my input were causing issues entering items into the database.
To fix this I had to add quotes around my parameters, though this seems like an odd requirement (perhaps I am missing something)
But it works now as expected.
Here are the alterations:
error_reporting(E_ALL); ini_set('display_errors', 1);
include "lib/style.php";
require_once (getcwd() . "/lib/coleSterlingLib.php");
//require_once (getcwd() . "/lib/jsFormInteraction.js");
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (isset($_POST['btnSubmit']))
{
$projectName = $_POST['projectName'];
$projectName = "'" . $projectName . "'";
$projectDescription = $_POST['projectDescription'];
$projectDescription = "'" . $projectDescription . "'";
$projectLink = $_POST['projectLink'];
$projectLink = "'" . $projectLink . "'";
addItemToDatabase($projectName, $projectDescription, $projectLink);
}
}
Note the $projectName = "'" . $projectName . "'";
Everything else stayed roughly the same
function addItemToDatabase($name, $description, $link)
{
$projectLinkSanSpace = str_replace(' ', '', $link);
$projectLinkAsLink = "<a href='project/" . $projectLinkSanSpace . "'>" . $link . "</a>";
databaseConnection('programWork');
$conn = new mysqli(DBF_SERVER, DBF_USER, DBF_PASSWORD, DBF_NAME);
if ($conn->connect_error)
{
die("Connection Failed!: " . $conn->connect_error);
}
//$sql = 'insert into projectList (projectName, projectDescription, projectPage, projectSource) Values ("Stuff", "Things", "Yeah", "Yeah")';
$sql = "call insertItemIntoWork($name, $description, $link, $link)";
//$result = $conn->query($sql);
$echoSuccess = true;
$msg = "The query completed successfully";
if ($conn->query($sql) === TRUE)
{
if ($echoSuccess)
{
echo "<span class='errMsg'>" . $msg . " successful.</span><br />";
}
} else
{
echo "<strong>Error when: " . $msg . "</strong> using SQL: " . $sql . "
<br />" . $conn->error;
//displayResult($result, $sql)
}
}

Get all rows from MySQL Query

The PHP Code:
<?php
//Server Information
$servername = "localhost";
$dbusername = "USERNAME";
$password = "TOTALLYSECUREPASSWORD";
$dbname = "DEFINITELYADATABASE";
//Query Information
$guid = $_POST['GUID'];
$username = $_POST['USERNAME'];
$admin_username = $_POST['ADMIN_USERNAME'];
$ban_reason = $_POST['BAN_REASON'];
$ip = $_POST['IP'];
//Create Connection
$connection = mysqli_connect($servername, $dbusername, $password, $dbname);
//Check the Connection
if ($connection->connect_error){
die("Connection failed: " . $connection->connect_error);
}
//$sql = "SELECT DATE, DBUSERNAME, GUID, IP, USERNAME, BAN_REASON FROM bans";
//$result = $connection->query($sql);
$sql = "SELECT * FROM bans WHERE";
$types = json_decode($_POST['QUERY_TYPE'], true);
if (in_array("query_admin_username", $types)) {
$sql = $sql . " DBUSERNAME = " . "\"" . $admin_username . "\"" . " &&";
}
if (in_array("query_guid", $types)) {
$sql = $sql . " GUID = " . "\"". $guid . "\"" . " &&";
}
if (in_array("query_ip", $types)) {
$sql = $sql . " IP = " . "\"" . $ip . "\"" . " &&";
}
if (in_array("query_username", $types)) {
$sql = $sql . " USERNAME = " . "\"" . $username . "\"" . " &&";
}
if (in_array("query_ban_reason", $types)) {
$sql = $sql . " BAN_REASON = " . "\"" . $ban_reason . "\"" . " &&";
}
$sql_query = substr($sql, 0, -3);
echo ($sql_query);
$result = $connection->query($sql_query);
while ($connection->query($sql_query)) {
}
if (!$result) {
die("Invalid Query: " . mysqli_error());
}
$row = $result->fetch_array(MYSQLI_NUM);
while ($row = mysqli_fetch_assoc($result)) {
echo ($row);
}
mysqli_close($connection);
?>
As weird as all that looks, it works just how I want it to (I think).
My issue:
I want to be able to get the data from each row and export it as one large String, something along the lines of:
[DATE] DBUSERNAME banned USERNAME (GUID / IP) for BAN_REASON.
I just have absolutely no idea how to go about this. I've tested the Query and it's returning everything it should, however I was using "echo ($row[0])" etc to display them, which is pretty impractical if it's going to return a large amount of rows.
Sorry if something doesn't make sense, my brain is fried at the moment. Please let me know if I forgot anything.
You could concatenate the columns like this if the rest of your script works:
SELECT CONCAT('[',DATE,'] ',DBUSERNAME,' banned ',USERNAME,'(',COALESCE(GUID, IP),),') for ', BAN_REASON) AS your_columns_in_one_line FROM your_table WHERE .....;
See this link for reference to CONCAT

Mutliple querystring parameters to mysql query

I originally had this working:
url: http://server/blah.php?FacilityCode=FT
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
$result = mysql_query($sql);
But I want to change this so that people can submit multiple values in the query strying somehow, ie: http://server/blah.php?FacilityCode=FT,CC,DD,EE
I tried changing the query to an "IN" clause instead of an "equals" but I'm not sure how to get the ' marks around each element.
Use implode() function for IN (...).
$a = array('AB', 'CD', 'EF', 'ZE');
echo "field IN ('" . implode("', '", $a) . "')";
... will output:
field IN ('AB', 'CD', 'EF', 'ZE')
+escape every option you get.
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$array=explode(',',$facilitycode);
foreach ($array as $a){$output.="'$a',";}
$clause=substr($output,0,-1);
If your trying to create a string which looks like this: 'AB', 'CD', 'EF', 'ZE'
Try this before its placed inside the query:
$facilitycode = preg_replace('/([^,]+)/', '\'$1\'', $facilitycode);
I wrote this based on your query, but still I dont get this part of query "AND ('" . $facilitycode . "' = ''", anyway you need to check if $_GET data have "," and if does explode that variable by "," so that you can add an OR clausule for everything that was separated by "," in $_GET data.
After that just form your query by doing a foreach for every element in exploded array like I done below:
<?php
$facilitycode = $_GET["FacilityCode"];
$facility_number_chk = strpos($facilitycode, ",");
if ($facility_number_chk > -1) {
$facilitycode = explode(",", $facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = ''";
foreach($facilitycode as $facode) {
$facode = mysql_real_escape_string($facode);
$sql .= " OR Facility.FacilityCode = '". $facode . "'";
}
$sql .= "')";
}
else {
$facilitycode = mysql_real_escape_string($facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
}
$result = mysql_query($sql);
And if there is only one element in $_GET data just do an else like I done with your regular query.
I ended up using a combination of a few of the answers. Basically I exploded on the ",", then did a foreach to add the ' marks and call escape_string, and then imploded it back.
$facilitycodes = $_GET["FacilityCode"];
if ($facilitycodes == '') {
$additionalfilter = '';
}
else {
$facilitycodearray = explode(",", $facilitycodes);
foreach($facilitycodearray as &$facilitycode) {
$facilitycode = "'" . mysql_real_escape_string($facilitycode) . "'";
}
$facilitycodesformatted = implode(",", $facilitycodearray);
$additionalfilter = " AND Facility.FacilityCode IN (" . $facilitycodesformatted . ")";
}
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
$additionalfilter;

PHP session save_handler user (mysql) won't save

PHP sessions work by default with my configuration, if I just go session_start() and try the standard session increment test it works.
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
However I want to use a MySQL table for session storage. I've put together my sessions.php file with all the functions, copied them right out of a book like a n00b, and the functions work (affect the database) if I call them like regular functions, but using the standard test above does not work. It sets the session for just the page load, and no change in the database. I put a line in each function to log each call, and the log reflects that the functions are being called by session_start().
Here's what my code looks like:
session_module_name("user");
session_set_save_handler("session_open", "session_close",
"session_read", "session_write", "session_remove", "session_gc");
session_start();
session_open, etc, being the name of my functions. I've even tried another set of functions out of an o'rly example, and got the same results.
Any ideas why? session_register() also yields the same results.
EDIT: here are the actual functions, I apologize for the length, but I log everything in dev.
function session_db(){
return("my_db_name");
}
function session_table(){
return("sessions_table");
}
function session_log($message){
if($file = fopen($application["siteroot"] . 'log/session.txt', "a")){
fwrite($file, date("Y-m-d H:i:s ") . $message . "\n");
fclose($file);
}
}
function session_open($path, $name){
session_log("session_open");
return(true);
}
function session_close(){
session_log("session_close");
return(true);
}
function session_read($id){
session_log("session_read");
if(!mysql_select_db(session_db())){
session_log("session_read select database error: " . mysql_error());
return(false);
}
$sql = "select * from " . session_table() . " where id='" . $id . "'";
if(!$result = mysql_query($sql)){
session_log("MySQL error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
if(mysql_num_rows($result)){
session_log("MySQL query returned " . mysql_num_rows($result) . "rows.");
$row = mysql_fetch_assoc($result);
session_log("session_read returned " . $row["data"]);
return($row["data"]);
}
else{
session_log("session_read found zero rows with SQL: " . $sql);
return("");
}
}
function session_write($id, $data){
session_log("session_write");
if(!mysql_select_db(session_db())){
session_log("session_write select database error: " . mysql_error());
return(false);
}
$sql = "update " . session_table() . " set data = '" . addslashes($data) . "', time=null";
if(isset($PHP_AUTH_USER)){
$sql .= ", user='" . addslashes($PHP_AUTH_USER) . "'";
}
$sql .= " where id='" . $id . "'";
if(!$result = mysql_query($sql)){
session_log("session_write error " . mysql_error() . " with SQL: " . $sql);
return(false);
}
if(mysql_affected_rows()){
session_log("session_write update affected " . mysql_affected_rows() . " rows with SQL: " . $sql);
return(true);
}
session_log("session_write updated zero rows with SQL: " .$sql);
$sql = "insert into " . session_table() . "(data,id) values('" . addslashes($data) . "','" . $id . "')";
if(!$result = mysql_query($sql)){
session_log("session_write error " . mysql_error() . "with SQL: " . $sql);
return(false);
}
else{
session_log("mysql_write inserted with SQL: " . $sql);
return(true);
}
}
function session_remove($id){
session_log("session_remove");
if(!mysql_select_db(session_db())){
session_log("session_remove select database error: " . mysql_error());
return(false);
}
$sql = "delete " . session_table() . " where id='" . $id . "'";
if($result = mysql_query($sql)){
session_log("MySQL query delete worked");
return(true);
}
else{
session_log("MySQL update error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
}
function session_gc($life){
session_log("session_gc");
if(!mysql_select_db(session_db())){
session_log("session_gc select database error: " . mysql_error());
return(false);
}
$sql = "delete " . session_table() . " where time < '" . date("YmdHis", time() - $life) . "'";
print("session_gc sql: " . $sql);
if($result = mysql_query($sql)){
session_log("session_gc deleted " . mysql_affected_rows() . " rows.");
return(true);
}
else{
session_log("session_gc error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
}
I don't think you need the call to session_module_name, try commenting it out and see what happens.
There are a couple of things...
We might need to see, at the very least, the actual functions.
You probably want to register a shutdown function, your writes are probably being called too late to save to the database.
register_shutdown_function('session_write_close');
Just to clarify, the reason for the above is that the write and close functions are normally called after objects are destroyed. This call will ensure that these are made before object destruction.

Categories