is_array for MySQL Select Statement with PHP - php

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.

Related

select query inside for each loop of PHP is not working

Good day! I am trying to get the user ids based on the names submitted on the input field. But the loop only returns the user id of the first selected user. Can somebody please help me?
Here's the code:
if(isset($_POST['proponent'])){
$proponent = mysqli_real_escape_string($con,$_POST['proponent']);
$myArray = explode(',', $proponent);
$posts = array();
foreach($myArray as $item) {
$query = "SELECT user_id FROM user WHERE CONCAT(fname, ' ', lname) = '$item'";
$get = mysqli_query($con, $query);
array_push($posts, mysqli_fetch_assoc($get));
print_r($posts);
}
}
Using mysqli_fetch_assoc only once will only get you the first row if it exists. So you will need to add this in a loop, say while loop like below in order for the mysqli_function to move it's pointer over the entire result set.
while($row = mysqli_fetch_assoc($get)){
$posts[] = $row;
}

How do I re-write this SQL statement to accept the array variable?

I am making an API call to retrieve user_name's from my database.
My first step is to make a call to retrieve all the player_id's. They are stored in $communityPlayersIds and currently output as below:
["2","31","31","32"]
I now want to make a second call to the database to fetch the user_name's of the id's that match.
$communityPlayerNames = array();
$communityPlayerNames = $dao->getPlayerNames($communityPlayersIds);
I have looked into it and seen I should use an IN command something like this:
public function getPlayerNames($player_ids)
{
$returnValue = array();
$sql = "SELECT user_name\n"
. "FROM users\n"
. "WHERE id IN ( '".$player_ids."')";
$result = $this->conn->query($sql);
if($result != null && (mysqli_num_rows($result) >= 1)){
while($row = $result -> fetch_array(MYSQLI_ASSOC)){
if(!empty($row)){
$returnValue[] = $row;
}
}
}
return $returnValue;
}
}
However this isn't working and returns this:
[{"user_name":null}]
If I echo ($sql) I get this:
SELECT user_name FROM users WHERE id IN ( '2,31,31,32')
Which looks correct does it not?
Where am I going wrong?
You essentially want your final query to look like this
Select user_name from users where id in (2,31,31,32) -- dupe 31 does no harm
Make sure your series of IDs are inside parentheses IN ($player_ids) and not just a single quote IN '$player_ids'
You can try building the IN-part of the SQL like this:
$returnValue = array();
$in_statement = "(";
foreach($player_ids as $player_id)
{
$in_statement = $in_statement.$player_id->player_id.",";
}
rtrim($in_statement, ",");
$in_statement = $in_statement.")";
$sql = "SELECT community_players.player_id\n"
. "from community_players\n"
. "where community_players.community_id in ".$in_statement."";
So just the middle-part is new, where the $in_statement gets build. And in your SQL you have to change the "=" to "IN". You can generate the IN-part shorter, but this way you can easier see how it's done, so you can fit it to your needs.
in your code you put ' after in which shows syntax error.
You can try
Assuming your
$communityPlayersIds has below value as array:
["2","31","31","32"]
if its not an array then convert it using json_decode()
and then try below query
$sql = "SELECT community_players.player_id\n"
. "from community_players\n"
. "where community_players.community_id IN (".join(",",$communityPlayersIds).")";

php query function / class

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);
}

How do you create a simple function to query the database? Mine isn't working!

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;
}

How to put MySQL cell values into variables named after column names in PHP

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

Categories