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);
}
Related
I have a database table with two fields both id and value and I'd like to add the two entries for value together and then echo out the total of the sum.
So far I've been able to display both entries for value by using the following.
function showTotal() {
global $connection;
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
if (!$result) {
die('Query FAILED' . mysqli_error());
} else if (isset($failed)) {
echo "Failed";
}
while ($row = mysqli_fetch_assoc($result)) {
$value = $row['value'];
echo "$value";
}
}
What I really want is these values added together rather than displaying alongside each other.
Thanks
James
I haven't tested it, but something like this could potentially be a one-liner.
echo array_sum( array_column( mysqli_fetch_all( $result, MYSQLI_ASSOC), 'value' ) );
That said, if you do not need all the results, this is a better option:
$result = mysqli_query( 'SELECT SUM(value) AS mysum FROM table' );
echo mysqli_fetch_array($result, MYSQLI_ASSOC)['mysum'];
Using php you could sum up the values like so:
$value = 0;
while ($row = mysqli_fetch_assoc($result)) {
$value += $row['value'];
}
echo $value;
While I personally would opt to go with the solution offered by #jm, PHP does offer another way with its array_sum(), as follows:
<?php
$value = 0;
while ($row[] = mysqli_fetch_assoc($result)) {}
echo array_sum($row['value']);
See Manual
Note: you could change the fetching of the result by using mysqli_fetch_all, if you have the MySQL native driver; see here.
I have a basic PHP function that I am working with. Sometimes, it is passed an array of variables, and other times it is just passed one variable. So, currently, I have something like this:
<?
function do_this($user_id_array) {
$user_ids = array();
foreach ($user_id_array as $single_user_id) {
$sql = 'SELECT username FROM users
WHERE id = $single_unit';
while($row = mysql_fetch_assoc($result)) {
array_push($user_ids, $row['id'];
}
}
return $user_ids;
}
?>
My issue is this: If I call the function and send it only one variable (and not an array), it (obviously) gives me the following error: Invalid argument supplied for foreach()
My question is: How can I change this function in the most efficient way with the least amount of code? Do I have to use an if is_array() statement and just create 2 SELECT statements, one for each case (array and non-array)?
Many thanks!
I see several options:
Pass an array even if it's one element long
Test for is_array() and act accordingly
Add another argument which states whether to check for an int or an array.
I'd go with options 1 or 2, as option 3 is error prone.
Also, there might be a better solution to your problem, you shouldn't have a single query for every user, you should instead use the IN keyword in MySQL, something like this:
$users = (is_array($user_id_array)) ? implode(',',$user_id_array) : $user_id_array;
$query = "SELECT `username` FROM `users` WHERE `id` IN({$users})";
wow. that's a lot of queries. What about to delete foreach and do something like
if (is_array($user_id_array)){
$sql = 'SELECT username,id FROM users
WHERE id IN ('.implode(",", $user_id_array).')';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$users[$row['id']] = $row;
}
}
You can write:
$user_id_array = (array)$user_id_array;
if (!is_array($user_id_array))
$user_id_array = array($user_id_array);
function do_this($user_id_array) {
$ids = array_map('intval', (array)$user_id_array);
$sql = 'SELECT username FROM users
WHERE id IN(' . implode(',', $ids) . ')';
$result = mysql_query($sql);
$usernames = array();
while ($row = mysql_fetch_assoc($result)) {
$usernames[] = row['id'];
}
return $usernames;
}
First line makes sure that you have an array ((array)$user_id_array) and that all values are valid integers. Then a single SQL query is executed for all user ids.
I am querying a database to get 6 values in my params table suing this;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$param = $row['value'] ;
}
is this right, if so is their away i can add one to the variable name each time round so i get $param1, $param2....
I dont want to have to send a query to the database for each param, is it possible to get them all like this?
The simpliest way is to use an array:
$result = mysql_query("SELECT * FROM params");
$param = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$param[$i] = $row['value'] ;
$i++;
}
Than you get $param[0], $param[1], ...
You can create variable names like this:
${'var'.1}
${'var'.'1.cat'}
${'var'.$x}
${$y.$x}
and so on.
This seems like a design flaw. But what you can do is:
$count = 1;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$paramname = 'param' . $count++;
$$paramname = $row['value'] ;
}
You may find the list function useful - http://php.net/manual/en/function.list.php
list($param1,$param2,$param3,$param4,$param5,$param6) = mysql_fetch_row($result);
Probably more use when using descriptive variables, just a thought.
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;
}
This code selects cell values in MySQL and manually adds them to PHP variables:
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)) {
$col1 = $rows['col1'];
$col2 = $rows['col2'];
$col3 = $rows['col3'];
.....
}
This is obviously unmanageable for multiple and large tables.
What's a better way to automatically generate the variable names and values without manually entering all the column names on all tables?
I think this is what you're looking for
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($rows as $key => $value) {
$$key = $value;
}
}
You could use extract() for that. But I'd keep the values in the array.
..SELECT x,y,z FROM ..
while( false!==($rows=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
extract($rows);
echo $x;
...
}
Wouldn't it be more convenient having associative arrays? That way you can call your variables with their column name as you describe plus you have the benefit of having them bundled in one unit which is much better if you need to pass more than one of them to any function or view or whatever.
so I would use mysql_fetch_assoc and that's it.
I don't recommend having a variable for each row, I used to do the same to simplify writing HTML later:
echo "<tr><td>$name</td><td>$count</td></tr>";
Instead of:
echo "<tr><td>{$row['name']}</td><td>{$row['count']}</td></tr>";
Until I found a better and more readable way do it using mysql_fetch_object
while ($row = mysql_fetch_object($result)) {
:
echo "<tr><td>{$row->name}</td><td>{$row->count}</td></tr>";
:
}
Use variable variables:
Code example:
$a = 'col1';
$$a = 'somevalue';
echo $col1;
will output 'somevalue'.
http://www.php.net/manual/en/language.variables.variable.php