php +codeigniter sql query - php

I want to do a query in my model from a table known as jurisdictions. Now I want this query to provide a valid MySQL result resource. I.e I want to pass the result to mysql_fetch_array(). If I pass in $query = $this->db->query(). I get an error saying that the passed in argument is invalid. I was wondering how can I convert $query to a MySQL result recource.

Well, if you want to have a MySQL resource, you should be using mysql_query.
Codeigniter already has a method which will give you one row at a time: row_array (actually, it has two, the other is just row, but that returns an object, not an array). If you want to get numeric indexes on the result of result_array, use array_values:
$result = $this->db->query( "SELECT 'foo' as foo_rules FROM DUAL" );
$aso_arr = $result->row_array(); // assoc. array w/o numeric indexes
echo $aso_arr[ 'foo_rules' ];
$num_arr = array_values( $aso_arr );
echo $num_arr[ 0 ];
If you would like the entire result of the selection, then use result and result_array (they have behavior similar to row and row_array, only they return the whole result set in an array)
EDIT
I repeat my first sentence, but you can get the MySQL resource this way:
$result = $this->db->query( "SELECT 'foo' as foo_rules FROM DUAL" );
$resource = $result->result_id;
But, since this is not documented, it should not be considered supported or even expected behavior. Be forewarned.

If I'm understanding you correctly then why not just use the available methods of:
$query->result();
or
$query->result_array();
Choose whichever to suit your needs.

Related

Mysql returns duplicate results with numbered key

I did a SELECT query on MySQL and get this as result.
The problem is how can I remove the 2nd duplicated results at for instance we use the 1st item in the list. "0":"1" is a duplicate for "id":"1" I would rather use "id" instead of "0" as the key later on the the app. How could I remove this to simplify the results. I do notice that the "0" means the 1st column as the successive columns does add up by 1.
Here's the $query I run.
SELECT id FROM clubsinformation WHERE :comparisonTime < updateTime
This is caused by most likely the fetching mode, you need to fetch it by associative indices only because right now you're including both associative and numeric index fetching:
No matter what DB API you got, MySQLi or PDO, just set it to associative.
So that it turn it doesn't include the numeric indices, only the column names as keys:
So this would roughly look like in code (from looking at your query placeholders, it seems PDO, so I'll draft a PDO example):
$data = array(); // container
$query = 'SELECT * FROM clubsinformation WHERE :comparisonTime < updateTime';
$select = $db->prepare($query);
$select->bindValue(':comparisonTime', $comparisonTime);
$select->execute();
while($row = $select->fetch(PDO::FETCH_ASSOC)) { // associative
$data[] = $row; // only includes column names
}
// then finally, encode
echo json_encode($data);
// OR SIMPLY
// $data = $select->fetchAll(PDO::FETCH_ASSOC); // associative
// echo json_encode($data);
That fetching is by way of PDO API. If you're using MySQLi you can still use the basic idea.

counting rows in php with sql

For an application I'm trying to count the total of friends. I want to do this with a function but it isn't returning anything. It tells me this:
Warning: mysqli_query() expects at least 2 parameters, 1 given
But I only need one parameter. I think I'm totally wrong.
This is the function:
public function GetTotalOfFriends($user_id){
$db = new Db();
$select = "SELECT COUNT FROM friendship WHERE (friendship_recipient_id ='" . $user_id ."' OR friendship_applicant_id = '" . $user_id . "') AND friendship_status = 'accepted'";
$result = $db->conn->query($select);
$row = mysqli_query($result);
$total = $row[0];
echo $total;
I'm trying to print it out in this way:
$friend = new Friendship;
$numberoffriends = $friend->GetTotalOfFriends($user_id);
<?php echo $numberoffriends; ?>
You are mixing up a couple of things. The line $result = $db->conn->query($select); already seems to execute a query, but then you try to bypass your database wrapper by passing that query result again to mysqli_query.
Apart from that, I think your query itself is also wrong. COUNT needs a parameter, indicating a field or value to count. Quite often COUNT(*) is used, but COUNT('x') might be more efficient in some cases. You can also use a specific field name, and COUNT will count the non-null values for you.
The result you got is a mysql_result object, which you need to use to get to the actual data of the query result.
The documentation of this object is here and I suggest that you read it thoroughly.
One possible way to do this is using this:
$resultArray = $result->fetch_row();
This will result in the first (and only) row of your query. It is represented as an array, with one value (since your query returns only one column). You can fetch that value like this:
return $resultArray[0];
You could also use any of the other fetch methods if you want your data in a different fashion.

mysql query to retrieve every single row of data

$q = "SELECT * FROM user";
$res = mysqli_query($conn, $q) or die(mysql_error());
$userList = "";
while($user = mysqli_fetch_array($res))
{
$userList .= $user['userList'].";;";
}
echo $userList;
I don't understand the while part:
Why assign the mysqli_fetch_array to $user using while?
How can the $user have index of userList?
Why concatenate with ;;?
To answer your questions:
i) mysqli_fetch_array() has two possible return values. It either returns an array of the current row that the database result set pointer points to, then advances the pointer to the next row, or it returns false if you have reached the end of the result set. The while() evaluates the value that is set to $row either continuing the loop if it is an array or stopping the loop if $row equals false
ii) The $user array has both numerical indexes for each field (i.e. 0,1,2,... [#fields - 1]) and associative indexes of the column names for the table (i.e. 'field1', 'field2', etc.). In this case one of the fields in the database is userList, so accessing $user['userList'] returns that column value for the row being worked with. BNote that the query itself would have beeter been written as SELECT userList FROM user since that is the only field you are interested in. There is no reason whatsoever to select and transfer all field data if you have no need for it. It is also rarely useful to use just mysqli_fetch_array(), as you rarely need both numerical and associative indexes on the record.It is usually best to specifically request ther associative or numerical array result depending on which you need.
iii) This code is simply building a string rather than an array of results which might be more common. For whatever reason the code writer decided values in the string should be separated by ;;.

How to get a PDO Fetch( ) to return as string

How can I get a PDO to return the data as a string not an array? I am not sure this is possible so if not is there a way to convert the array to a string after it has been processed?
My code which is returning the string is:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);
I have tried different fetch types such as FETCH_CLASS FETCH_OBJ
You can do it like this:
echo $stmt->fetchColumn();
Or:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result[0];
$result = $statement->fetchColumn();
This work for me, the only thing I noticed here is that fetchColumn() always refer to first column on your table. You need to adjust / re-position the only column needed to the first-column on your table or make an Sql query i.e "SELECT" query to get the only column needed. Thanks

How do I fetch a single field from a mysql query in one line with php?

php and mysql...
the query:
$sql = "SELECT keyterm
FROM keyterms
WHERE keyterm_id = $keyterm_id";
$result = mysqli_query($dbcon,$sql); // returns a single result
fetch results:
$keyterm = mysqli_fetch_assoc($result);
$keyterm = $keyterm["keyterm"];
what is the equivalent of the last two lines in a single line?
You need to use fetch_object() because PHP allows you to chain the ->operator directly onto the return value of a function, which you cannot do with the [ ] operator.
$keyterm = $result->fetch_object()->keyterm;
Or, procedural style:
$keyterm = mysqli_fetch_object($result)->keyterm;
extract() (take care):
extract(mysqli_fetch_assoc($result));
You will get a warning when mysqli_fetch_assoc() returns FALSE (non-array). Field/Column name must be named as the variable.
Edit: Made it bold as some might have not read that.
If you only fetch a single column, you can also use:
$keyterm = current(mysql_fetch_array($result));
Works since PHP5. It just gets the first entry from the array (whether indexed or associative), and assigns it to the variable. That's the cheapest option here.

Categories