PHP convert mysql row into array to find its size - php

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

Related

How to extract string value of array from database?

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

Understanding fetch_assoc()

I am trying to understand how/why fetch_assoc works the way it does.
I have the following piece of code:
$results = $connectToDb->fetch("SELECT * FROM customer");
$resultsArray = $results->fetch_assoc();
print_r($resultsArray); //print_r 1
while($row = $results->fetch_assoc()){
print_r($row); //print_r 2
}
The query returns 3 rows from a table.
Why does the 1st print_r return only the 1st row of the queried data but the 2nd print_r returns all 3? How does putting fetch_assoc into a while loop tell it to do the action more than once? I read that fetch_assoc returns either an associative array or NULL but I'm struggling to understand how the while loop "tells" fetch_assoc to fetch the next row, if that makes sense?
Thank you.
Lets try to understand your code and how it works:
$results = $connectToDb->fetch("SELECT * FROM customer");
A variable $results has a collection of rows which are returned by a query. The size of the collection can be from 0 to n.
$resultsArray = $results->fetch_assoc();
This line fetch the first element from the collection. If the collection is empty it will return NULL.
while($row = $results->fetch_assoc()){
}
It can be decoupled in the following steps:
Calculate $row = $results->fetch_assoc() and return array with elements or NULL.
Substitute $row = $results->fetch_assoc() in while with gotten value and get the following statements: while(array(with elements)) or while(NULL).
If it's while(array(with elements)) it resolves the while condition in True and allow to perform an iteration.
If it's while(NULL) it resolves the while condition in False and exits the loop.
I think it useful:
function get_posts(){
$posts = array();
if ($result = $mysqli->query("SELECT id, post_userid, name, lang, country, post_image, post_date, post_date_updated FROM posts ORDER BY `post_date` DESC ;")) {
while ($row = $result->fetch_assoc())
{
$posts[$row['id']] = $row ;
}
} else {
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
return $posts;
}
in your case, if you want to print 3 rows each by each, you need to call this $result->fetch_assoc() as a three times.
for example, when you call the first time first row will be fetched and removed from array list. then 2 rows remain now.
in Second call second row will fetched and removed from array list.then 1 row remain now.
so you can call 3 times because you have a 3 rows. it will give null value if you call fourth times.because array list is empty now.
now come to the while($row = $results->fetch_assoc() this also do the same job which we discussed above.

How to find out automatically the numeric index of an specific MySQL column in PHP?

I´m new to PHP and SQL and it´s the first time I post here, hope I do it right =)
I need to find out the numeric index from an certain field in my database. Thing is I´m not done with the database structure yet, so for this specific field I´d like to have it automated so I won't have to change the code every time I add or remove columns.
I also need it to have BOTH index types so I can call the columns by name in part of the code and by index for automated parts of it.
I´ve managed to achieve the result I wanted trough an very ugly code, because all the array_search and array_keys I´ve tried didn´t work out for some reason.
Here is the snippet of my working but ugly code. Do you have an more elegant solution?
Thanks in advance for your answers, and for all I´ve learned so far from reading other peoples questions!
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes) or die(mysql_error());
$c = 0; // This block is to find out where the column "cont1" is and assign it to $cont1
$d=array_keys($student);
$cont1=0;
foreach ($student as $a=>$b){
if ($a==='cont1') {
$cont1=$d[$c-1];
}
$c++;
}
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$students[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$students[$i+2]."</li>";
echo "</ul></p>";
}
}
Finding the numeric index:
$student = mysqli_fetch_array($dadosRes,MYSQLI_ASSOC) or die(mysql_error());
$numericIndex = array_search("cont1",array_keys($student));
Giving MYSQLI_ASSOC will force the query to fetch only the associative keys; otherwise it will give you both numeric and associative array.
PHP function, array_search in this case, requires the third parameter set to TRUE:
<?php
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes, MYSQLI_BOTH) or die(mysql_error());
$student_keys = array_keys($student);
$cont1 = $student_keys[array_search("cont1", $student_keys, true) - 1];
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$student[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$student[$i+2]."</li>";
echo "</ul></p>";
}
}
?>
MYSQLI_BOTH is used in the mysqli_fetch_array function because first the array is searched for the column name, then later the array is looped over with numeric indexes. This results in the $student array having integer 0 as the first element and therefore causing array_search to choke. Adding true as the third parameter causes a === comparison unchoking the function. :) (Explanation: PHP array_search consistently returns first key of array )

Trying to get field data to fit into if inarray() check

Just wondering if anyone can help me with this problem...
I want to be able to check if a certain ID (user for example is logged on) The ID's of these users will be pulled from a table, and then fed into an array and then checked if it is in there.
However when I pull the data the if inarray() no longer works as it would if I just typed it in straight within the code instead of pulling it.
I want to pull approved ID's through so they can access a certain link essentially!
Any help would be appreciated! Thanks!
<?php
mssql_select_db("$ins", $con);
$result = mssql_query("SELECT ID FROM Event WHERE EventPublic LIKE 'Yes' AND EventDate >= GETDATE() -1 ORDER BY EventDate ASC ");
while($row = mssql_fetch_array($result))
{
$test = "". $row['ID'] .",";
}
$tests = explode(',', $test);
if (in_array("2, 48", $tests)) {
echo "WOO";
}
else
{
echo "BOO";
}
mssql_close($con);
?>
in array should be an actual array
in_array(array('2', '48'), $tests)
also, it would be better to put
$tests = array();
before the while loop, then change the code inside the loop to read
$tests[] = $row['ID'];
then you can do away with the '$tests = explode(...' line.
Your having the issue with your in_array test because you are comparing an array and with a string in the following line:
if (in_array("2, 48", $tests))
The above line checks if the string "2, 48" exist in the array. But the array will have 2 as one element and 48 as a separate element. To fix this you can search for each element individually with something like:
if(in_array('2',$tests) || in_array('48',$tests))

create array from mysql query php

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.

Categories