Parameter Passing (PHP) - 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

Related

How do I pass this information to print it out in another document? PHP MySQL

I am having trouble echoing row data within the page I want to print it out to.
My function works, but only echoes the information because it is local (within the same function).
I'm trying to get this function to echo the database's information to another .php file (same program).
public function findByUsername($username) {
$sql = 'SELECT * FROM events WHERE username=? ';
$statement = DatabaseHelper::runQuery($this->connection, $sql, Array($username));
while ($row = $statement->fetch()) {
echo $row['username'] . "<br />";
echo $row['date'] . "<br />";
}
}
Here is the part of the other file I need to print the information from the function to:
<?php
if (isset($_SESSION["username"])) {
$eventDAO = new EventDAO($connection);
$event = $eventDAO->findByUsername($_SESSION["username"]);
foreach((array)$event as $e) {
echo $e->getUsername() . ' ' . $e->getDate() . '<br>';
}
}
?>
I'm trying to output the username/date.
Not 100% on this concept.
If you're simply trying to output username/date from one file to another, try using sessions.
public function findByUsername($username) {
$sql = 'SELECT * FROM events WHERE username=? ';
$statement = DatabaseHelper::runQuery($this->connection, $sql, Array($username));
while ($row = $statement->fetch()) {
echo $row['username'] . "<br />";
echo $row['date'] . "<br />";
$_SESSION['getuname'] = $row['username'];
$_SESSION['getdate'] = $row['date'];
}
}
You can then output the information on another php file simply by echoing it out.
echo "Username is ". $_SESSION['getuname'];

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

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;

php simple html dom return array?

I'm trying to create an app using the simple HTML DOM php script, but im running into a wall currently with it - hope you can help.
The aim is to read product numbers from mySQL database, concat these numbers with a url constant and then parse this resulting website for a specific class. The result should then be printed to the screen.
My problem is that the script is returning only the first result from the function array, i have tried a few things, such as trying to call $prices->children[4], but nothing seems to help.
When i trigger the function get_prices_array() with a url, it brings back multiple results -> but when i return this inside my while loop it only brings back the first result in the array.
Heres my code, hope you can point me in the right direction!
Thanks!
<?php
include('simple_html_dom.php');
function get_prices_array($url) {
$x = file_get_html($url);
foreach ($x->find('span.price')as $dom) {
$y = $dom->outertext;
return $y;
}
$x->clear();
}
$con = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$result = mysqli_query($con, "SELECT * FROM articles");
while ($row = mysqli_fetch_array($result)) {
$constant = '***';
$prices = get_prices_array($constant . $row["product_number"]);
echo $row["product_number"] . " - " . $prices . '<br />';
}
mysqli_close($con);
?>
// EDIT //
I changed the function get_prices_array() to loop through each span price class and add the result to an array, the array is then returned from the function. The first 5 results from the array are then stored to variables and added to the return string. Thanks for your help!
<?php
include('simple_html_dom.php');
function get_prices_array($url) {
$x = file_get_html($url);
$y = array();
foreach ($x->find('span.price')as $dom) {
$x = ($dom->outertext);
$y[] = $x;
}
return $y;
//$x->clear();
}
$con = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$result = mysqli_query($con, "SELECT * FROM articles");
while ($row = mysqli_fetch_array($result)) {
$constant = '***';
$prices = get_prices_array($constant . $row["product_number"]);
$pos1 = $prices[0];
$pos2 = $prices[1];
$pos3 = $prices[2];
$pos4 = $prices[3];
$pos5 = $prices[4];
echo $row["product_number"] . " - " . $pos1 . " - " . $pos2 . " - " . $pos3 . " - " . $pos4 . " - " . $pos5 .'<br />';
}
mysqli_close($con);
?>
I think problem is because of return used in foreach loop of function get_prices_array($url).
it is executing foreach loop only once. There is no meaning of loop if you are returning without condition inside loop.

How to pass a variable/s into while loop MySQLi

I have a simple function to SELECT from MySQL:
function dbSelect($query) {
$db = db(); // refers to a database connect function
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_array($result)) {
echo $row['f_name'] . ' : ' . $row['s_name'] . '</br>';
}
}
as you can see it accepts the $query var which would be:
$query = "SELECT * FROM user"; // or whatever
What I would like to do is pass the line:
echo $row['f_name'] . ' : ' . $row['s_name'] . '</br>';
as an arg in the function call, eg:
function dbSelect($query, $display)
and the $display be something like (which I would echo out under the while statement):
$display = $row['f_name'] . " : " . $row['s_name'] . "</br>";
The above line will give an undefined variable error, I know why.
How would I go about passing the $display to the function or defining it correctly?
ps. I know there is not any error checking, I'm just trying to figure this out, will add that later. :-)
Thanks for any help
Try this, to maintain separation from program logic to program output:
// some configuration file you include
$db = db(); // refers to a database connect function
// some common functions file
function dbSelect($query)
{
global $db;
$result = mysqli_query($db, $query);
return $result;
}
// output script
$records = dbSelect('SELECT * FROM somewhere');
// loop until cannot fetch any more rows from the record set
while ($row = mysqli_fetch_array($records))
{
echo $row['f_name'] . ' : ' . $row['s_name'] . '</br>';
}
Personally I would pass a template name into the function and have the template stored somewhere as a snippet of html which has standard replacement vars
So you may have something like this (note this won't work out the box will need some fiddling but its the concept)
define TEMPLATE_NAME = "<tr><td>%COL1%</td><td>%COL2</td></tr>";
$colstospitout = array('COL1'=>'f_name','COL2'=>'s_name');
function dbSelect($query,$reportcols,$templatename) {
while ($row = mysqli_fetch_array($result))
{
$template = str_replace("%COL1%",$reportcols['COL1'],$templatename);
$template = str_replace("%COL2%",$reportcols['COL2'],$templatename);
echo $template;
}
}
dbSelect($inputquery,$colstospitout,TEMPLATE_NAME);
There are two ways to do it. The proper way to do it would be to have this function only run the query and return the results. You could make another function that outputs the results. This way you have a clear separation of logic in your code.
However, if you know that you want it done in this way, something like this should work:
function dbSelect($query, $format) {
$db = db();
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_array($result))
{
echo preg_replace_callback("/\{\{\s*(\w+)\s*\}\}/", function($matches) use ($row) { $column = trim($matches[1]); return isset($row[$column]) ? $row[$column] : $matches[0]; }, $format);
}
}
Where the arguments could look something like:
dbSelect("SELECT * FROM user", "{{ f_name }} {{ s_name }}");
You can't pass it the way that you're passing it because $row doesn't exist when you call the function (because it gets defined inside of the function). In addition, your variables in would be evaluated once when the function is called, not each time in the while loop.
And before anyone makes a "suggestion": eval is not an option.

creating a page that displays ID info on a template

Updated with suggestion by others but still seem to be stuck.
I'm using this php code here to display info from my database using the ID. I created a link on my main page that looks like this.
<h1><?php echo $row_getDisplay['title']; ?></a></h1>
I have so when they click on the title of the article that it takes them to my php fiel which I named fetch.php and the code below is what is in there. I have built this around someone else's work. For some reason I can't get passed the first "else" statement. so I keep getting "you must select a valid location" I'm fairly new to php so I don't really understand why the code is failing.
<?php require_once('Connections/XXXXXX.php'); ?>
<?php
if (isset($_GET['id']) == false) // check if id has been set
{
echo "You must select a location"; // if not, display this error
exit;
} else {
$id = (int) $_GET['id'];
if (is_numeric($id) == false)
**{
echo "You must select a valid location.";
} else {**
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE post_id ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
Any help is appreciated. If you are able to find a better solution for me that would be great.
You shouldnt use $HTTP_GET_VARS its deprecated and unless its turned on it wont be populated. use $_GET instead.
if (isset($_GET['id']) == false)
Use $_GET for your if statement:
if (isset($_GET['id']) == false)
Also, you need to convert your $_GET value to an integer, because it is currently a string.
Right after that if statement above, in the else, put this:
$id = (int) $_GET['id'];
That way your is_numeric() will work properly.
Try this;
<?php
require_once('Connections/XXXXXX.php');
if (isset($_GET['id'])) // check if id has been set
{
$id = $_GET['id'];
if (is_numeric($id) == false)
{
echo "You must select a valid location.";
} else {
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE locationid = 'news.post_id' ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
else{
echo "You must select a location"; // if not, display this error
exit;
}
?>
Also, I need a clarification about news.post_id, from where are you grabbing this?

Categories