How to use passed variable in a PDO prepared SELECT WHERE statement - php

I am trying to figure out how to use a php variable in a PDO prepared statement. The code below returns nothing. The part that I'm not sure about is
$stmt = $conn->prepare("SELECT * FROM laptop WHERE '$ckey' = :avalue");
I'm trying to use a variable for the key and the value, It doesn't seem to be returning results. The switch statement is meant to look for which field the user filled out. This is a basic search for a rudimentary inventory system. I know there are open source solutions available, but my company won't let us use open source software on the network. I also realize the output isn't formatted into a table, but I figured I'd get the query to work, then worry about prettying up the output. I also realize there are some similar questions, but I haven't seen anyone trying to use variables in the WHERE part of a statement. If it's because it won't work, and everyone knows this but me, I apologize.
Here is the entire code block.
function mkquery($ckey,$cdata)
{
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$stmt = $conn->prepare("SELECT * FROM laptop WHERE '$ckey' = :avalue");
//$stmt is the prepared query, you execute it to perform the query
$stmt->bindParam(':avalue',$ckey, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $val ) {
echo $val['Model'] . " ";
echo $val['Name'] . " ";
echo $val['DellTag'] . " ";
echo $val['HHSCTag'] . " ";
echo $val['OS'] . " ";
echo $val['KBOX'] . " ";
echo $val['SB'] . " ";
echo $val['Issued'] . " ";
echo $val['Tech'] . " ";
echo "<br>";
}
}
switch (isset($_POST)) {
case isset($_POST['name']):
$selector = 'name';
mkquery($selector,$_POST['name']);
break;
case isset($_POST['model']):
$selector = 'model';
mkquery($selector,$_POST['model']);
break;
case isset($_POST['delltag']):
$selector = 'delltag';
mkquery($selector,$_POST['delltag']);
break;
case isset($_POST['hhsctag']):
$selector = 'hhsctag';
mkquery($selector,$_POST['hhsctag']);
break;
case isset($_POST['city']):
$selector = 'city';
mkquery($selector,$_POST['city']);
break;
case isset($_POST['kbox']):
$selector = 'kbox';
mkquery($selector,$_POST['kbox']);
break;
case isset($_POST['sb']):
$selector = 'sb';
mkquery($selector,$_POST['sb']);
break;
case isset($_POST['issued']):
$selector = 'issued';
mkquery($selector,$_POST['issued']);
break;
case isset($_POST['tech']):
$selector = 'tech';
mkquery($selector,$_POST['tech']);
break;
default:
echo 'No input on form detected';
break;
}
a
$conn = null;

Related

Switch function outputting default instead of desired value

I'm trying to do a simple switch function with the following code.
$query = "SELECT * FROM entries where Venue='Condamine' and Year='2018' and
Event='$5,000 Novice' and herd='2' and scratched IN('n','l') ORDER BY Draw
ASC";
// Execute the query
$result = mysqli_query($con ,$query);
if (!$result){
die ("Could not query the database: <br />". mysqli_error());
}
// Change herds
function getherd($catch) {
switch($catch)
{
case '2':
return 'Herd Change';
break;
default:
return 'Damn!';
break;
}
}
$catch = $row["herd"];
echo "<tr>";
echo "<td bgcolor=#FFFFFF><strong> ". getherd($catch) ." </strong></td>";
echo "<td bgcolor=#FFFFFF> </td>";
echo "</tr>";
?>
My result is printing out the default value "Damn!" instead of the desired value "Herd Change" what am I doing wrong. I want to print out the words "Herd Change" if the value of the row herd = 2.
its most probably a typecasting issue
try
$catch = string($row["herd"]); and make sure the $catch is 2
Your code should be changed as below.
<?php
$query = "SELECT * FROM entries where Venue='Condamine' and Year='2018' and
Event='$5,000 Novice' and herd='2' and scratched IN('n','l') ORDER BY Draw
ASC";
// Execute the query
$result = mysqli_query($con ,$query);
if (!$result){
die ("Could not query the database: <br />". mysqli_error());
}
// Change herds
function getherd($catch) {
switch($catch)
{
case '2':
return 'Herd Change';
break;
default:
return 'Damn!';
//Break doesn't require in default case
}
}
//here you need to get results set from $result.
$html = "";
while ($row = mysqli_fetch_row($result)) {
$catch = $row["herd"];
$html += "<tr>";
$html += "<td bgcolor=#FFFFFF><strong> ". getherd($catch) ." </strong></td>";
$html += "<td bgcolor=#FFFFFF> </td>";
$html += "</tr>";
}
echo $html;
//It will print multiple rows, If query returns multiple rows.
?>
If your variable $catch contains integer value then use below syntax.
switch($catch){
case 2:
// your code
default:
// your code
}
In case of String value do the following,
switch($catch){
case "2":
// your code
default:
// your code
}
Switch case manual
It is not good practice to manually typecast the variable.
I hope it helps!

In my php script, my connection to the server works but my sql queries do not

The connection works, I don't get a connection error. But when I run the script I get an undefined index error and it outputs "0 results" although my table is populated for sure and I am searching for something that I know is in the table.
I am using MySQL workbench to manage the database and apache (xampp) to host the local server and run the PHP scripts. Could this be the problem? Is there a way for me to host the database in the same place as the apache website?
$sql="SELECT * FROM book_table WHERE Title LIKE $input OR Author LIKE $input OR Barcode LIKE $input";
$result = $conn->query($sql);
if ($result) {
while($row = $result->fetch_all()) {
echo "<br>Title: " . $row["Title"]. " - Author: " . $row["Author"];
}
} else {
echo " <br> 0 results";
}
My suggestion to you is PDO:
$dsn = 'mysql:host=localhost;dbname='.$dbname;//$dbName is the name of your database
$user = 'root';
$pass = '123';//use your login information here
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM book_table WHERE Title LIKE :info OR Author LIKE :info OR Barcode LIKE :info";
$ps = $db->prepare($query);
$ps->bindValue(':info', $input)
$ps->execute();
$result = $ps->fetchAll(PDO::FETCH_ASSOC);
//iterate over result
if (!empty($results)){
foreach ($result as $row) {
echo "<br>Title: " . $row["Title"]. " - Author: " . $row["Author"];
}
} else {
echo " <br> 0 results";
}
Also, remember to use the MySQL LIKE in the right way. When you want to match a part of a String, you need to use the % symbol.
Ex:
SELECT * FROM book_table WHERE Title LIKE "%goodbook%"
It will return all rows that has the "goodbook" as part of the Title.
You can try like this. Since you use mysqli_* I have make it prepared statements and bind_param.
Note: Not tested. So may need to adjust a bit.
$param = '$input';
$sql= $conn->prepare("SELECT * FROM book_table WHERE Title LIKE ? OR Author LIKE ? OR Barcode LIKE ?");
$sql->bind_param("s", $param);
$sql->execute();
if($res->num_rows > 0) {
while ($row = $res->fetch()) {
echo "<br>Title: " . $row["Title"]. " - Author: " . $row["Author"];
}
} else {
echo " <br> 0 results";
}

my pdo connection doesn't work

Echoing to my previous question about SQL-injection. I'm trying to set up a PDO connection.
For that I want to replace my old code with the new:
Here is the old
$conn = mysql_connect("localhost", "sec", "dubbelgeheim") or
die('Error: ' . mysql_error());
mysql_select_db("bookshop");
$SQL = "select * from productcomment where ProductId='" . $input . "'";
$result = mysql_query($SQL) or die('Error: ' . mysql_error());
$row = mysql_fetch_array($result);
if ($row['ProductId']) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
} else
echo "No Record!";
mysql_free_result($result);
mysql_close();
And here is the new:
$input = $_GET['input'];
if ($input) {
$user= 'sec';
$pass = 'dubbelgeheim';
try {
$dbConn = new PDO('mysql:host=127.0.0.1;dbname=bookshop', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$escaper = $db->real_escape_string($input);
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $escaper);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
while ($row = $result->fetch_assoc()) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
}
}
else {
echo 'No record!';
}
$result->free();
$db->close();
}
When I tried this new code.. It gives the following error:
Error!: SQLSTATE[HY000] [1045] Access denied for user
'sec'#'localhost' (using password: YES)
I also tried to replace localhost with 127.0.0.1.
My goal is to make my page secure for SQL-injection.
May anyone have a great solution!
The code looks ok at first glance.
Try this solution. It looks like this anonymus user might be the problem.
EDIT: (as suggedted in comments)
In summary:
The recommended solution is to drop this anonymous user. By executing
DROP USER ''#'localhost';

Parameter Passing (PHP)

I am trying to select a record in a database. I am having a problem with the function runSelect (function is to select a record in the database) I believe it might be with how I am passing my variables in the functions.
function select($pUserData){
echo "I am in function select." . "<br/>";
// Create the SQL query
$sqlQuery = "SELECT * FROM tablName WHERE id= " . $pUserData[0];
$con = openConnection();
$result = $con->query($sqlQuery);
$row = $result->fetch_row();
echo "hello";
echo "ID: " . $row[0] . "<br />";
echo "First Name: " . $row[1] . "<br />";
// Close connection
closeConnection($con);
}
function openConnection() {
$connection = new mysqli("localhost", "userName", "password", "databaseName");
if ( mysqli_connect_errno() ) {
echo "Error: Could not connect to database. Please try again later. " . "<br/>";
}
echo "in openConnection" . "<br/>";
return $connection;
}
function closeConnection($pCon) {
$pCon->close();
}
?>
Your code is open to SQL injection...
Only provide the data the function needs, not the entire input array.
Connecting and disconnecting to the db for every query is inefficient if you got multiple queries in the future. Let PHP disconnect from the DB when it exits until there is a need to microcontrol it (probably never) and you can manage your resources better.
Print the contents of $_POST with var_export or var_dump at the start of your program.
Print $result->num_rows in the runSelect function.
Add a few lines like this:
echo '<p>' . __LINE__ . '</p>';
I did some changes in the code to avoid errors and also made some fallback handling. Such changes have comments explaining them. I debug the following code and is working perfectly.
<?php
init();
function init(){
// Retrieve and store data from form
$uData = getData();
// Take an action based on value from user
switch($uData[5]){
case "select":
runSelect($uData);
echo "I need to select";
break;
case "insert":
runInsert($uData);
echo "I need to runInsert" . "<br/>";
break;
case "update":
runUpdate($uData);
echo "I need to runUpdate" . "<br/>";
break;
case "delete":
runDelete($uData);
break;
default:
break;
}
} // end init()
function getData() {
$id_num = isset($_REQUEST["id_num"]) ? $_REQUEST["id_num"] : "1"; //if no id is pass let's assume that the user wants the record with id 1
$first_name= isset($_REQUEST["first_name"]) ? $_REQUEST["first_name"] : "";
$last_name = isset($_REQUEST["last_name"]) ? $_REQUEST["last_name"] : "";
$major = isset($_REQUEST["major"]) ? $_REQUEST["major"] : "";
$year = isset($_REQUEST["year"]) ? $_REQUEST["year"] : "";
$action = isset($_REQUEST["action"]) ? $_REQUEST["action"] : "select"; //assume the default action as select
$userData = array($id_num, $first_name, $last_name, $major, $year, $action);
return $userData;
}
//function runSelect -------------------------------------------------------------------------------------------------
function runSelect($pUData){
echo "I am in runSelect" . "<br/>";
// Create the SQL query
$sqlQuery = "SELECT * FROM tblStudents WHERE id= " . $pUData[0];
// Create the connection
$con = getConnection();
// Execute query and save results
$result = $con->query($sqlQuery);
// Display results
$row = $result->fetch_row();
echo "hello";
echo "ID: " . $row[0] . "<br />";
echo "First Name: " . $row[1] . "<br />";
// Close connection
closeConnection($con);
}
//function getConnection -------------------------------------------------------------------------------------------------
function getConnection() {
$connection = new mysqli("localhost", "userName", "password", "databaseName");
if ( mysqli_connect_errno() ) {
echo "Error: Could not connect to database. Please try again later. " . "<br/>";
}
echo "in getConnection" . "<br/>";
return $connection;
}
//function closeConnection -------------------------------------------------------------------------------------------------
function closeConnection($pCon) {
$pCon->close();
}
?>
Based on the comments so far it sounds like the query didn't return a result (it's set to FALSE). Therefore when you attempt to fetch the row you're getting a fatal PHP error but you have error output turned off so you don't see it.
Check the value of $result and if it's FALSE check what the error is via:
http://www.php.net/manual/en/mysqli.error.php
Be aware that $_POST only retrieves parameters that have been POST'ed to the script (usually via a form submission). For parameters passed in via the URL then they would be populated in $_GET. If the request method (POST or GET) is not important then $_REQUEST can help beacause it gets populated with both POST and GET (and cookies) parameters:
http://php.net/manual/en/reserved.variables.php

MySQL select works in phpMyAdmin but my PHP returns no rows with the same call

Heres my code
<?php
session_start();
include('config.php');
if(isset($_GET['search_word']))
{
// echo $_GET['search_word'] . '<br />'; // debugging
$search_word = $_GET['search_word'];
$search_word = mysql_escape_string($search_word);
$search_word_fix = str_replace(" ","%",$search_word);
$query = "SELECT * FROM article WHERE article_title LIKE '%" . $search_word . "%' AND article_live = '1' ORDER BY article_id DESC";
// echo $query . '<br />'; // debugging
$sql = mysql_query($query);
$count = mysql_num_rows($sql);
// echo $count . '<br />'; // debugging
// echo mysql_num_rows($sql) . '<br />'; // debugging
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$msg=$row['article_title'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $msg);
echo $final_msg;
}
}
else
{
echo "No Results";
}
}?>
Can anyone see an issue with it? I cant pick out what is not working with this script and ive been staring at it for a while. It never makes it to the WHILE loop only the "No Results" and the count returns blank when i uncomment my debugging.
Count returning blank means your query failed for some reason.
Are you connecting to the db properly? Try using mysql_error() right after your query:
$error_msg = mysql_error();
Use mysql_real_escape_string() instead of mysql_escape_string() - it respects the character set so that you don't have UTF8 issues
If you're using this publicly, you may want to learn about using binds to eliminate the possibility of SQL injection via a library like PDO.
Here's a pretty good tutorial/introduction to PDO explaining why it's important!

Categories