I have a custom html page which posts to php variables which then fills out custom sql queries.
function load_table($db, $old_table, $startRow, $nameColumn, $ipColumn, $addressColumn, $cityColumn, $stateColumn, $zipColumn, $countryColumn)
{
$select = "SELECT $nameColumn, $ipColumn, $addressColumn, $cityColumn, $stateColumn, $zipColumn, $countryColumn FROM " .$old_table.";";
$q = mysqli_query($db, $select);
return $q;
}
It works perfectly when all the variables are holding a value, but I need a way to dynamically assert this query, so that if the user is missing a column, i.e zip code is not in their table, it will still run without ruining the query.
$array = array();
if ($nameColumn)
$array[] = $nameColumn;
if ($ipColumn)
$array[] = $ipColumn;
// etc...
$cols = implode(',', $array);
if ($cols)
{
$select = "SELECT $cols FROM $old_table;";
$q = mysqli_query($db, $select);
return $q;
}
Or you can use
$select = "SELECT ".(($nameColumn != '')?$nameColumn.",":"")." .......";
See also: http://br2.php.net/manual/en/function.func-get-args.php
Put all your variables in an array then do the following:
function load_table($db, $old_table, $startRow, array $columns) {
$columns = array_filter($columns, 'strlen'); // removes empty values
$select = "SELECT " . implode(",", $columns) . " FROM " .$old_table.";";
$q = mysqli_query($db, $select);
return $q;
}
You can give it a default:
function load_table($db, $old_table, $startRow, $nameColumn="Default name", $ipColumn, $addressColumn, $cityColumn, $stateColumn, $zipColumn, $countryColumn)
In this case $nameColumn will always have a value unless otherwise specified
Related
My php knowledge is fairly limited but I've recently needed to update a number of web pages from an older version of php 5.2 to php 7.3.
I've managed to update most of the mysql references to mysqli etc and get things working correctly, however there is one page that makes use of a calendar and I'm really struggling with this section and the fetch_field part in particular as any examples I have found don't seem to be in a similar format.
The code I need to update is below;
require_once('Connections/connAsh.php');
mysql_select_db($database_connAsh, $connAsh);
function selectonerow($fieldsarray, $table, $uniquefield, $uniquevalue)
{
//The required fields can be passed as an array with the field names or as a comma separated value string
if (is_array($fieldsarray)) {
$fields = implode(", ", $fieldsarray);
} else {
$fields = $fieldsarray;
}
//performs the query
$result = mysql_query("SELECT $fields FROM $table WHERE $uniquefield = '$uniquevalue'") or die("Could not perform select query - " . mysql_error());
$num_rows = mysql_num_rows($result);
//if query result is empty, returns NULL, otherwise, returns an array containing the selected fields and their values
if ($num_rows == NULL) {
return NULL;
} else {
$queryresult = array();
$num_fields = mysql_num_fields($result);
$i = 0;
while ($i < $num_fields) {
$currfield = mysql_fetch_field($result, $i);
$queryresult[$currfield->name] = mysql_result($result, 0, $currfield->name);
$i++;
}
return $queryresult;
}
}
My attempts at editing this are;
require_once('../Connections/connAsh.php')
$connAsh->select_db($database_connAsh);
function selectonerow($fieldsarray, $table, $uniquefield, $uniquevalue)
{
//The required fields can be passed as an array with the field names or as a comma separated value string
if (is_array($fieldsarray)) {
$fields = implode(", ", $fieldsarray);
} else {
$fields = $fieldsarray;
}
//performs the query
$result = $connAsh->query("SELECT $fields FROM $table WHERE $uniquefield = '$uniquevalue'") or die("Could not perform select query - " . mysqli_error());
$num_rows = mysqli_num_rows($result);
//if query result is empty, returns NULL, otherwise, returns an array containing the selected fields and their values
if ($num_rows == NULL) {
return NULL;
} else {
$queryresult = array();
$num_fields = mysqli_num_fields($result);
$i = 0;
while ($i < $num_fields) {
$currfield = mysqli_fetch_field($result);
$queryresult[$currfield->name] = mysqli_fetch_array($result, MYSQLI_BOTH);
$i++;
}
return $queryresult;
}
}
The original function is wrong on so many levels. And there is no point in recreating its functionality.
Basically all you are bargaining for here is just a few SQL keywords. But these keywords contribute for readability.
For some reason you decided to outsmart several generations of programmers who are pretty happy with SQL syntax, and make unreadable gibberish
$row = selectonerow("some, foo, bar", "baz", "id", [$uniquevalue]);
instead of almost natural English
$row = selectonerow("SELECT some, foo, bar FROM baz WHERE id=?", [$uniquevalue]);
Come on. It doesn't worth.
Make your function accept a regular SQL query, not a limited unintelligible mess.
function selectonerow(mysqli $conn, string $sql, array $params = []): array
{
if ($params) {
$stmt = $conn->prepare($sql);
$stmt = $mysqli->prepare($sql);
$stmt->bind_param(str_repeat("s", count($params), ...$params);
$stmt->execute();
$result = $stmt->get_result()
} else {
$result = $conn->query($sql);
}
return $result->fetch_assoc();
}
This function will let you to use any query. For example, need a row with max price?
$row = selectonerow("SELECT * FROM baz ORDER BY price DESC LIMIT 1");
Need a more complex condition? No problem
$sql = "SELECT * FROM baz WHERE email=? AND activated > ?";
$row = selectonerow($sql, [$email, $date]);
and so on. Any SQL. Any condition.
I would recommend to get rid of this function or replace it with a function suggested by YCS.
If you really want to continue using this function consider the following fixes. You made the code inside extremely complicated and you forgot to pass the connection variable into the function. I have simplified it:
// open the DB connection properly inside Connections/connAsh.php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connAsh = new mysqli('host', 'user', 'pass', $database_connAsh);
$connAsh->set_charset('utf8mb4');
// your function:
function selectonerow(mysqli $connAsh, $fieldsarray, $table, $uniquefield, $uniquevalue): array
{
//The required fields can be passed as an array with the field names or as a comma separated value string
if (is_array($fieldsarray)) {
$fields = implode(", ", $fieldsarray);
} else {
$fields = $fieldsarray;
}
//performs the query
$stmt = $connAsh->prepare("SELECT $fields FROM $table WHERE $uniquefield = ?");
$stmt->bind_param('s', $uniquevalue);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
This is your function, but with a lot of noise removed. I added $connAsh in the function's signature, so you must pass it in every time you call this function. The function will always return an array; if no records are fetched the array will be empty. This is the recommended way. Also remember to always use prepared statements!
This seems like it should be really straightforward, but I keep getting unexpected output. I'm trying to access specified rows in a SQL database which each contain a numerical value and then calculate the sum of those values. PHP is concatenating the values as if they were strings even after I've set the datatype of the values to float. My code:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
$population_value = is_array($population_value) ? $population_value : array($population_value);
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I have also tried:
$total = array("");
foreach($population_value as $value){
floatval($value);
array_push($total, $value);
echo $value;
}
echo array_sum($total);
My output is always something like: 100002000030000
with 10,000 20,000 and 30,000 being the values of each population.
I've successfully calculated sums using foreach with values that weren't retrieved from MySQL.
What is going on here?
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
//This is actually rewriting the array or NOT adding the value to it.
$population_value = is_array($population_value) ? $population_value : array($population_value);
//ok, so you're going to repeatedly output this?
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I think what you want is this:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
$population_value=array(); //Initialize the array so we can just add to it.
while($row = mysqli_fetch_assoc($result)) {
$population_value[]= intval($row['population_value']); //Just making sure we get a number.
echo end($population_value); //We could output the row again, or just grab the last element of the array we added.
}
//Now that the array is fully populated and we've made sure it's only numbers, we output the grand total.
echo array_sum($population_value);
First, don't initialize the array with an empty string. Do this instead:
$total = array();
or with the new style:
$total = [ ];
Second, rewrite the floatval thing like this:
array_push($total, floatval($value));
That should fix it...
The following code is intended to use levenshtein() to compare a user-input word to the values in a column of a MySQL table:
$searched=$_POST['searched'];
$sql = "SELECT * FROM `word_list`;";
$result = mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
$title = $row['word'];
$sound = levenshtein($searched, $title);
if ($sound < 4) {
echo $title;
}
?>
My confusion stems from the mechanics of actually looping in the values of the "word" column of the table as a variable for the second string int he levenshtein function.
Ultimately, I'd like to loop the values from that column into the $title variable, and echo the values that produce a levenshtein distance less than 4, but I cannot seem to return any output.
Using a while loop is correct in your example. But you are mixing the mysql and the mysqli extension:
$result = mysqli_query($conn,$sql);
...
while($row=mysql_fetch_assoc($result))
You'll have to use mysqli_fetch_assoc() instead.
Also you are missing a closing } at the end of the while loop. The complete example should look like this:
$searched = $_POST['searched'];
$sql = "SELECT * FROM `word_list`;";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
$title = $row['word'];
$sound = levenshtein($searched, $title);
if ($sound < 4) {
echo $title;
}
}
It must be Monday, the heat or me being stupid (prob the latter), but for the life of me I cannot get a simple php function to work.
I have a simple query
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
Which I want to run through a function: say:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
while($row = mysql_fetch_array($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}
So that I can call the function in numerious places with differeing "inputs". Then loop through the results with a foreach loop.
Works fine the first time the function is called, but always gives errors there after.
As said "It must be Monday, the heat or me being stupid (prob the latter)".
Suggestions please as I really only want 1 function to call rather than rewrite the query each and every time.
This is the error message
Fatal error: [] operator not supported for strings in C:\xampp\htdocs\functions.php on line 270
function functionname($input){
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$input'");
$result = array('field1' => array()
'field2' => array()
);
while($row = mysql_fetch_array($sql)) :
$result['field1'][] = $row['field1'];
$result['field2'][] = $row['field2'];
endwhile;
mysql_free_result($sql);
return $result;
}
it seems that somewhere the $field1 or $field2 are converted to strings and you cant apply the [] to a string...
i'd say that you have to do:
$field1 = array();
$field2 = array();
before the WHILE loop
The problem is that you so called arrays are strings!
global $field1;
global $field2;
var_dump($feild1,$feild2); //Will tell you that there strings
Read the error properly !
[] operator not supported for strings
And the only place your using the [] is withing the $feild - X values
GLOBAL must work because the error is telling you a data-type, i.e string so they must have been imported into scope.
another thing, why you selecting all columns when your only using 2 of them, change your query to so:
$sql = mysql_query("SELECT feild1,feild2 FROM table WHERE field_name = '$input'");
another thing is that your using mysql_fetch_array witch returns an integer indexed array, where as you want mysql_fetch_assoc to get the keys.
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
What I would do
function SomeFunction($variable,&$array_a,&$array_b)
{
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$variable'");
while($row = mysql_fetch_assoc($sql))
{
$array_a[] = $row['field1'];
$array_b[] = $row['field2'];
}
mysql_free_result($sql);
}
Then use like so.
$a = array();
$b = array();
SomeFunction('Hello World',&$a,&$b);
In my opinion, it's pretty unusual and even useless approach at all.
This function is too localized.
To make a general purpose function would be a way better.
<?
function dbgetarr(){
$a = array();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
$res = mysql_query($query);
if (!$res) {
trigger_error("dbgetarr: ".mysql_error()." in ".$query);
return FALSE;
} else {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
and then call it like this
$data = dbgetarr("SELECT field1,field2 FROM table WHERE field_name = %s",$input);
foreach ($data as $row) {
echo $row['field1']." ".$row['field1']."<br>\n";
}
To understand your issue, we need the error, however, are you sure you are going about this in the right way?
Why do you need to call the function multiple times if you are just changing the value of the input field?
You could improve your SQL statement to return the complete result set that you need the first time.. i.e. SELECT * FROM table GROUP BY field_name;
Not sure if that approach works in your scenario, but in general you should aim to reduce the number of round trips to your database.
I don't know, i right or not. But i advise to try this:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM `table` WHERE `field_name` = '" . $input . "'");
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}
I want to make a simple function that I can call on to query my database. I pass the "where" part of the query to it and in the code below, my $q variable is correct. However, what should I then do to be able to use the data? I'm so confused at how to do something I'm sure is extremely easy. Any help is greatly appreciated!
function getListings($where_clause)
{
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q,$dbh);
foreach (mysql_fetch_array($result) as $row) {
$listingdata[] = $row;
}
return $listingdata;
}
Your function should be like this:
function getListings($where_clause, $dbh)
{
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q, $dbh);
$listingdata = array();
while($row = mysql_fetch_array($result))
$listingdata[] = $row;
return $listingdata;
}
Improvements over your function:
Adds MySQL link $dbh in function arguments. Passit, otherwise query will not work.
Use while loop instead of foreach. Read more here.
Initialize listingdata array so that when there is no rows returned, you still get an empty array instead of nothing.
Do you have a valid db connection? You'll need to create the connection (apparently named $dbh) within the function, pass it in as an argument, or load it into the function's scope as a global in order for $result = mysql_query($q,$dbh); to work.
You need to use while, not foreach, with mysql_fetch_array, or else only the first row will be fetched and you'll be iterating over the columns in that row.
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q,$dbh);
while (($row = mysql_fetch_array($result)) != false)
{
$listingdata[] = $row;
}
Always add error handling in your code. That way you'll see what is going wrong.
$result = mysql_query($q,$dbh);
if (!$result) {
trigger_error('Invalid query: ' . mysql_error()." in ".$q);
}
Here is a function which will save you some time. First Argument tablename, then condition(where), fields and the order. A simple query will look like this : query_db('tablename');
function query_db($tbl_name,$condition = "`ID` > 0",$fields = "*",$order="`ID` DESC"){
$query="SELECT ".$fields." FROM `".$tbl_name."` WHERE ".$condition." ORDER BY".$order;
$query=$con->query($query);
$row_data=array();
while($rows = $query->fetch_array()){
$row_data[] = $rows;
}
return $row_data;
}