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 ));
Related
I'm using this script to get data from a database
$sql = "SELECT * FROM items WHERE catid = 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo $row['extra_fields'];
}
The output is:
[{"id":"1","value":"johndoe"},{"id":"2","value":"marydoe"}]
I want to extract/print only the value corresponding to "id":"1" (that in this case is 'johndoe'). I'm not able to extract it from the above data type.
To read JSON in PHP use
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields'];
// Do something with $array['id']
}
Did you realise you can directly go for that data in MySQL?
SELECT value FROM items WHERE id = 2;
edit:
Basically your query is
SELECT comma-separated column names or star for all, use only what you really need to save bandwidth, e.g. SELECT id, value
FROM table-name, e.g. FROM mytable
WHERE columnname = desired value, e.g. WHERE id = 2
You want to query only the required columns in the required rows. Imagine one day you would have to parse 1 million users every time you want to get an id... :)
The output is JSON. Use PHP's json_decode function.
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
foreach($array AS $item) {
echo $item['id'];
}
}
Currently this is the code that fits my needs:
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
$value = $array[0]->value;
}
You should do it in the mysql query part. For example, set the ID = 1 in the query.
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>"
?>
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've been searching for a few hours to find the right way to do this. Any help would be greatly appreciated.
I am looking for a way to count the number of fields that are NOT NULL in a defined row.
I would like to use mysql_query to convert the row into an array, skipping the empty fields. Then I want to take that array and find its size.
mysql_query(SELECT * FROM table)
$value = array(list, of, values, from, row, in, my, database);
echo sizeof($value); //value would be 8
I have also tried counting the fields using mysql_num_fields(), but don't know how to subtract the empty fields from the results.
$test = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_fields($test);
echo $num_rows; //but subtracting all fields that are NULL
Thank you in advance for your help.
An easier way to clean arrays is to use php's array_filter function without a callback parameter. By default that function is set to remove elements that contain a false (or a 0), null or a "".
//This prunes out 'false', '0', 'null' or ''
$my_array = array_filter($my_array);
First store the mysql row into array and then filter it and then count element using cont function
$result = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($result))
{
$row = array_filter($row); //remove empty values
$num_of_values_non_empty = count($row);
echo $num_of_values_non_empty;
}
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.