I'm trying to pull an array to use on another query but it's not working, because the last comma.
<?php
include"connection.php";
$pos = mysqli_query($not,"SELECT * FROM equipos");
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
$logos = implode(",", $logos);
$enjuego = mysqli_query($not,"SELECT * FROM partidos WHERE dprt='ftbls'");
while($part=mysqli_fetch_array($enjuego)){
$liga=$part['serie'];
$eq1= $part['eq1'];
$eq1s= strtoupper($eq1);
$eq2= $part['eq2'];
$eq2s= strtoupper($eq2);
echo $logos[$eq1].'<br>';
}
?>
It gives me the same error over and over again.
This is the closest I came but just doesn’t work.
Can someone tell me what am I doing wrong?
The error I get is: Warning: Illegal string offset 'gua' in line 22
You have several problems with your code:
You never created an array
You constantly overwrite $logos
Your usage of substr_replace() indicates a deeper problem.
Here's a better approach:
Build the array.
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
There are many ways condense an array into a string. I encourage you to browse the manual on PHP Array Functions. In your case, you are interested in implode()
$logos = implode(",", $logos);
Note: The value for $logos smells. You should construct your arrays to hold data, not formatting.
For example:
$logos[$row['abrv']] = $row['logo'];
Output:
print_r($logos);
What you want can be achieved in many ways, but let's look at your code, there are quite a few things wrong in there.
Semantically meaningless variable names like pos, not, equipos, abrv. Only logo and result are good variable names.
Using the * selector in database queries. Don't do that, instead select the exact fields you need, it's better for performance, maintainability, code readability, testability, ... need I say more?
Fetching per row and running code on each row when what you actually want is an array containing all rows. Solution:
$result = mysqli_query($not, "SELECT * FROM equipos");
$logos = mysqli_fetch_all($result, MYSQLI_ASSOC);
Concatenating subarrays by using strings, that's not how it works, what you could do:
while($row = mysqli_fetch_assoc($result))
{
$logos[][$row['abrv']] = $row['logo'];
}
But as I said, that's not necessary.
Overwriting your variable $logos with each iteration of the loop. You'd need to do $logos[] = ....
Typically, implode is useful for such cases.
Without knowing what exactly you want to do, take this as a first hint:
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
$logos = implode(",", $logos);
The simplest way I would have thought is just to change the query and fetch the array into that -
<?php
include_once("connection.php");
$result = mysqli_query($not,"SELECT abrv, logo FROM equipos");
$rows = mysqli_fetch_array($result, MYSQLI_ASSOC);
// display the result
echo "<pre>"
print_r($rows);
echo "</pre>"
?>
Related
I have this text string varchar type i get from database echo.
how to extract it and count the value :
in the database it save as string ["1","2","3"] in varchar.
how to count this as 3 item using php?
my sql code is :
$sql2 = "SELECT * FROM il_dcl_stloc1_value WHERE record_field_id = '$exc_prt_id'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$exc_prt_id1 = $row2['value'];
echo "$exc_prt_id1"; // this will result ["1","2","3"]
}
There are tons of ways you can do this, but if you just care about the count, not the values, and they will always come in this format, you can just use
$count = count(explode(",", $exc_prt_id1));
You can also do a
$count = count(json_decode($exc_prt_id1));
If you want the values, run the above code without the count.
$arr = json_decode($exc_prt_id1);
This will result in a PHP array.
While the 2nd option is generally preferred and is better practice, the 1st one might be of use in certain cases. If there is anything unclear, just ask :)
Try this way
$exc_prt_id1= str_replace("[","",$exc_prt_id1);
$exc_prt_id1= str_replace("]","",$exc_prt_id1);
$exc_prt_id1= str_replace('"','',$exc_prt_id1);
$invoiceArr = explode(",",$exc_prt_id1);
$count = count(explode(",", $invoiceArr ));
I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>
What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}
I've read through some other posts that were similar but I can't seem to get a good implementation of them. I'm calling a php script from another program that needs the results returned in one variable, space or comma separated. The php connects to a db (no problem there) and runs a query that will return 2 to 6 or so matching rows. I need those results together in one variable but can't seem to get it.
Here's where I'm stuck.
$t = "SELECT user FROM call_times WHERE client='$clientid' AND start <= $date AND end >= $date";
$result = mysql_query($t) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$temp = $row['user'];
}
echo $temp;
The query runs fine, but you can see from the code what I'm trying (and failing) to do in the lower part. I need $temp to hold a list of results (ex: 5567889 57479992 4335780 (each of which is a different entry in user column)).
Thanks so much!
$array = array();
while ($row = mysql_fetch_array($result)) {
$array[] = $row['user'];
}
$string = implode(" ", $array);
Now $string has the space-separated values of the user column.
Good luck!
Try group_concat() and you won't need PHP to manipulate the results.
I have a little problem that I don't understand. I have a db that has an owner and type (and more off course). I want to get a list of all the type values that has owner equal to the current user, but I get only two result
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ORDER BY id DESC ";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
prints out:
Array ( [0] => 18 [type] => 18 )
and
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ";
prints out:
Array ( [0] => 16 [type] => 16 )
And the result should be something like 19, 19, 18, 17, 16 in an array. Thats all the types that has me as set as owner.
I have got this working now:
for ($x = 0; $x < mysql_num_rows($result); $x++){
$row = mysql_fetch_assoc($result);
echo $row['type'];
}
Here I print out all the values correctly, but I need to create an array with all the values. I though I could use array_push, but there most be a better way of doing it. I thought I would get all the type values with a simple mysql query.
Very often this is done in a while loop:
$types = array();
while(($row = mysql_fetch_assoc($result))) {
$types[] = $row['type'];
}
Have a look at the examples in the documentation.
The mysql_fetch_* methods will always get the next element of the result set:
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
That is why the while loops works. If there aren't any rows anymore $row will be false and the while loop exists.
It only seems that mysql_fetch_array gets more than one row, because by default it gets the result as normal and as associative value:
By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
Your example shows it best, you get the same value 18 and you can access it via $v[0] or $v['type'].
THE CORRECT WAY ************************ THE CORRECT WAY
while($rows[] = mysqli_fetch_assoc($result));
array_pop($rows); // pop the last row off, which is an empty row
You do need to iterate through...
$typeArray = array();
$query = "select * from whatever";
$result = mysql_query($query);
if ($result) {
while ($record = mysql_fetch_array($results)) $typeArray[] = $record['type'];
}
while($row = mysql_fetch_assoc($result)) {
echo $row['type'];
}
You could also make life easier using a wrapper, e.g. with ADODb:
$myarray=$db->GetCol("SELECT type FROM cars ".
"WHERE owner=? and selling=0",
array($_SESSION['username']));
A good wrapper will do all your escaping for you too, making things easier to read.
$type_array = array();
while($row = mysql_fetch_assoc($result)) {
$type_array[] = $row['type'];
}
You may want to go look at the SQL Injection article on Wikipedia. Look under the "Hexadecimal Conversion" part to find a small function to do your SQL commands and return an array with the information in it.
https://en.wikipedia.org/wiki/SQL_injection
I wrote the dosql() function because I got tired of having my SQL commands executing all over the place, forgetting to check for errors, and being able to log all of my commands to a log file for later viewing if need be. The routine is free for whoever wants to use it for whatever purpose. I actually have expanded on the function a bit because I wanted it to do more but this basic function is a good starting point for getting the output back from an SQL call.