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.
Related
The same code used as below works fine, but when you un-comment the function and try to call the function, it does not behave the same?
Am trying to standardize the CRUD using functions, but running into issues.
The print_r does not display the output when called inside a function but works when called as is outside of a function
the return value does not return when called via a function
I would like to get the return values via the function and decide what to do next.
Appreciate if you could help me out. Thanks
<?php
//function verifyemail($p_email) {
echo "insde function - " . $p_email;
try {
// $p_email = "r#gmail.com";
include 'db.php';
connectDB('msme_db',1) ;
$sql = "select count(*) as p_exists from msme_users where user_email = '$p_email' ;" ;
echo $sql ;
$result = $__conn->prepare($sql);
$result->execute();
$result->setFetchMode(PDO::FETCH_ASSOC);
$row = $result->fetch() ;
//print_r ($row);
if ($row)
{
$i = $row['p_exists'] ;
return $row !== false ? $row : 'x';
}
} catch (PDOException $e) {
echo " in catch" ;
die("Error occurred:" . $e->getMessage());
}
//} // End of Function
//$email = "r#gmail.com";
//echo sprintf('Email %s is %s', $mail, verifyemail($email)) ;
print_r($row) ;
?>
Problems I see:
1. you have return command in if statement
if ($row)
{
$i = $row['p_exists'] ;
return $row !== false ? $row : 'x';
}
so if is true then you return from function and if is not true then you don't
check this by putting echo inside and see if you see anything
if ($row)
{
echo 'IF Statemen in line: ' . __LINE__ . '<br>' . PHP_EOL;
$i = $row['p_exists'] ;
return $row !== false ? $row : 'x';
}
you should rewrite the code so you always return form the function and use if statement only to assign value to $i or $row
ie like that:
function verifyemail($p_email) {
echo "insde function - " . $p_email;
try {
// $p_email = "r#gmail.com";
include 'db.php';
connectDB('msme_db',1) ;
$sql = "select count(*) as p_exists from msme_users where user_email = '$p_email' ;" ;
echo $sql ;
$result = $__conn->prepare($sql);
$result->execute();
$result->setFetchMode(PDO::FETCH_ASSOC);
$row = $result->fetch() ;
//print_r ($row);
if ($row)
{
$i = $row['p_exists'] ; //<== where do you use $i?
$row !== false ? $row : 'x';
}
} catch (PDOException $e) {
echo " in catch" ;
die("Error occurred:" . $e->getMessage());
}
return $row; //<== here you rentrun from the function
}
// End of Function
// ^ here is place for the comment, not in the line where } is
//$email = "r#gmail.com";
//echo sprintf('Email %s is %s', $mail, verifyemail($email)) ;
print_r($row) ;
?>
If you use return statement without the function body so in the global code scope you end the php script execution
so the code
print_r($row) ;
is never executed
to summarize - put echo statements
echo 'line: ' . __LINE__ . '<br>' . PHP_EOL;
into if statement and other places and check numbers with the code and you'll probably see what you havn't seen where your execution flows where not.
and move return statement outside if statement, perfectly at the end of the function.
I'm trying to fill in the different options on a form calling objects from a database using a different php file. Here is my code:
PHP Code (functions.php):
<?php /* Gets values from sql and inserts into html options values */
function selectOptions($column, $table){
// fetch records
$sql = "SELECT" . $column. "FROM" . $table. "ORDER BY Id";
$result = $conn->query($sql);
//check there are more than 0 rows
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option>' .$row['$column']. '</option>';
}
}
else {
echo '<option>No results!</option>'; } } ?>
HTML code:
<?php
require "php/dbconnect.php";
require "php/functions.php";
?>
<select class="form-control">
<option>SUBJECT</option>
<?php
selectOptions("Subjects", "general_subjects");
?>
</select>
I use this function multiple times for different forms, so I figured having it in its own file would be the best approach but it does not work. When I use the function without variables inside the index.php file, it seems to work. I don't know what I am doing wrong
EDIT: Image of what it should be doing Image of index.php
Add spaces to your sql query. Also you need to access the $column variable properly. You shouldn't wrap it around single quotes as it is a variable. You also have a variable scope issue as $conn does not exist
function selectOptions($conn, $column, $table) {
// fetch records
$sql = "SELECT `" . $column . "` FROM `" . $table . "` ORDER BY Id"; #add spaces
$result = $conn->query($sql);
//check there are more than 0 rows
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option>' . $row[$column] . '</option>'; #remove single quotes
}
} else {
echo '<option>No results!</option>';
}
}
When you call the above function, add the echo keyword
<?php
echo selectOptions($conn, "Subjects", "general_subjects"); #echo the function
?>
Would you try editing your function.php sql part like this
$sql = "SELECT " . $column. " FROM " . $table. " ORDER BY Id";
i think the spaces is the reason that it's not returning data
I have a table
Now.i have a function in my JS
function add()
{
<?php
include('conn.php');
$rs = mysql_query("select * from position");
$row = mysql_fetch_array($rs);
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo "add2()";
?>}
function add2(){
AddAddress("<?php echo $ss;?>","<?php echo $sss;?>/<?php echo $ssss;?><br /><?php echo $sssss;?>/<?php echo $ssssss;?>");
}
How to get the every date from my table?
Something like this?
function add() {
<?php
include('conn.php');
$rs = mysql_query("select * from position");
while ( $row = mysql_fetch_array($rs) ) {
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo 'AddAddress("' . $ss . '","' . $sss . '/' . $ssss . '<br />' . $sssss . '/' . $ssssss . '");';
}
?>
}
Didn't text the echo 'AddAddress....' line so I hop eI got all the single and double quotes in the right place??
Performing POST requests using Ajax here is an example of sending data from js to php.
also stop naming your vars s,ss,sss,ssss you will have no idea what they mean when you read your code tomorrow..
and try not to use mysql_* functions they have been deprecated switch to mysqli or pdo
I got what would you like to do. In your PHP file:
function add(){
<?php
include('conn.php');
$rs = mysql_query("select * from position");
echo "var data = [] ; "
while($row = mysql_fetch_assoc($rs)){
echo "
data.push({
name: '{$row['Name']}',
nowb: '{$row['nowb']}',
totalb: '{$row['totalb']}',
nowc: '{$row['nowc']}',
totalc: '{$row['totalc']}'
}); \n\r " ;
}
?>
add2(data);
}
function add2(data){
for (var i in data){
var row = data[i] ;
AddAddress(row.name, row.nowb, row.totalb, row.nowc, row.totalc);
}
}
If I understand the question correctly you want to know how to loop through an array in php.
$row = mysql_fetch_array($rs);
foreach($row as $value){
//Do something
}
Read up on it in the docs
http://php.net/manual/en/control-structures.foreach.php
This question already has answers here:
mysqli/mysql query inside function not working [duplicate]
(2 answers)
Closed 9 years ago.
I'm trying to load some data from a database using PHP, but for some reason it doesn't work when I put it inside a function. If I try the code without a function, it works fine:
//$dbc connection
$call1 = 0;
$output = '';
$query = "select * from artists order by lname limit $call1, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
However, when I change the code to be inside a function, I don't get anything from the database (or at least it won't return anything):
//$dbc connection
$call1 = 0;
$output = '';
function loadArtists($call){
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
}
loadArtists($call1);
What am I doing wrong here?
You cannot use $dbc in your function, because it is a global variable.
You can use either
function loadArtists($call){
global $dbc;
...
}
to make $dbc known to loadArtists() or pass it as a second parameter
function loadArtists($dbc, $call){
...
}
and call it as
loadArtists($dbc, $call1);
As I mentioned in one of my comments, using global to fix the scope of your connection is poor practice. The correct way to pass your connection is like so:
$dbc = mysqli_connect("localhost", "my_user", "my_password", "world");
$call1 = 0;
$output = '';
function loadArtists($call, $dbc){
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
}
loadArtists($call1, $dbc);
Declaring your username and password on the same page as the code you're executing every time you want to make a DB connection is bad practice because:
You could potentially have more than one page to edit if you move to a different host or a different environment than the dev environment.
If you declare it outside of the root you can limit access to the DB password from FTP accounts.
I like to use a function for the connection so this way if the connection closes you can reopen it at will (reducing server overhead). Also you don't have to set it as a global var inside the function (not a good idea because of several reasons).
So for those reasons, this connection should be outside (below) the root.
/../safe/connection.php
function openSQL() {
$conn = mysqli('localhost', 'my_user', 'my_password', 'my_db');
return $conn;
}
functions.php
require_once($_SERVER['DOCUMENT_ROOT'].'/../safe/connection.php');
function loadArtists($call){
$dbc = openSQL();
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
mysqli_close($dbc);
return $output;
}
$myOutput = loadArtists(4);
The problem is variable scope. That variable does not exist within your function.
There are three ways to deal with that:
Make it global, that means an outside variable is readible from within a function. (Note that using global variables is often considered a security concern.)
global $dbc;
You can pass that variable into the function as an argument
function loadArtists($connection, $call) { ... }
you can make a class and that class variable will now be useable inside of class functions:
class Artists {
public $dbc;
public function __construct() {
$this->dbc = open_the_db_connection(); //etc?
}
public function loadArtists($call) {
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($this->dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
return $output;
}
}
It looks like a scoping issue to me. The $output you reference in the function isn't the same as the $output you defined outside the function.
You should change your function to the following:
function loadArtists($call){
$output = "";
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
return $output;
}
$output = loadArtists($call1);
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