I have the following code:
public static function selectBy(Database $database, $columnName, $value){
$connection = $database->getConnection();
$stmt = $connection->prepare('
SELECT * FROM `Logs`
WHERE ' . $columnName . ' = ?;');
$stmt->bind_param('s', $value);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
$finalResult[] = $row;
}
return $finalResult;
And it's implementation:
$logsArray = Log::selectBy($this->database, "ID", "423");
foreach($logsArray as $key=>$logArray){
foreach($logArray as $anotherKey=>$log){
echo $log . "<br />";
}
}
I am trying to find a way to target only specific row fields that we're returned from the database, for example, echo only the IP of the first log that was returned.
another example is to assign all the fields that we're return to a Log object, one field to a variable at a time, or all at once.
The result will be a row of objects, of type "Log" that reflect what's in the database.
One more problem I have encountered is that I have an extra field in each row of the two dimensional array returned by fetch_assoc(), which is called "array + an incrementing number", for example:
Array 0
Array 1
Array 2
Clearly it's the array number inside the first array, using foreach it goes over it by default.
Any way to ignore it using foreach? Or remove / avoid inserting them in the first place?
Thanks in advance.
Related
I would like to check if a given value exists in a mysql table. If yes; I would like to get the value of another column of that row.
Now I have:
$teinsertengetal=$_GET['getal'];
// start
$i = 0;
$ikhadingezetArray = array();
$result = $conn->query("SELECT getal, hoevaakingezet FROM ingezettegetallen");
while ($row = mysqli_fetch_assoc($result))
{
$ikhadingezetArray[$i]['getallen'] = $row['getal'];
$ikhadingezetArray[$i]['hoevaakingezets'] = $row['hoevaakingezet'];
$i++;
}
foreach($ikhadingezetArray as $value)
{
echo $value . "<br>";
}
My problem is that the foreach only echos "Array", not the values within the array.
And then I have to check if $teinsertengetal is in the array (the field "getal" in $ikhadingezetArray). If yes; I want the value of "hoevaakingezet" from the same row number of the array.
I hope you understand what I mean. Maybe it's not the best way I could do this?
Thank you in advance!
edit: the echo is just to check if the right values were inserted in the array.
For example:
Table "ingezettegetallen"
getal
hoevaakingezet
6
2
48
4
$teinsertengetal = 48
Now I would like check if 48 is in the column "getal". If yes (and it is in this example) I would like to store the value "4" in a variable (like $hoevaakingezetdus).
Put the check in the query, rather than fetching the entire table.
$stmt = $conn->prepare("
SELECT hoevaakingezet
FROM ingezettegetallen
WHERE getal = ?");
$stmt->bind_param("s", $teinsertengetal);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['hoevaakingezet'] . "<br>";
}
I'm trying to convert sqlite query into json. I have the following table with two columns name and age. When I print the query the format doesn't seem to be correct. why am I getting an extra key value pair?
<?php
$db = new SQLite3('info.db');
$results = $db->query('SELECT * FROM info');
while ($row = $results->fetchArray()) {
$jsonArray[] = $row;
}
echo json_encode($jsonArray)
?>
output
[{"0":"billy","name":"billy","1":"20","age":"20"}]
desired output
[{"name":"billy","age":"20"}]
Change query to get only those column which are required:
$results = $db->query('SELECT name,age FROM info');
// if you want all column then only use *
And then use SQLITE3_ASSOC
while($row = $results->fetchArray(SQLITE3_ASSOC)){
Reference:- SQLite3Result::fetchArray
Parameters
mode
Controls how the next row will be returned to the caller. This
value must be one of either SQLITE3_ASSOC, SQLITE3_NUM, or
SQLITE3_BOTH.
SQLITE3_ASSOC: returns an array indexed by column name as returned in
the corresponding result set
SQLITE3_NUM: returns an array indexed by column number as returned in
the corresponding result set, starting at column 0
SQLITE3_BOTH: returns an array indexed by both column name and number
as returned in the corresponding result set, starting at column 0
Follow an example:
<?php
$db = new SQLite3('info.db');
$results = $db->query('SELECT * FROM info');
$data = array();
while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
array_push($data, $row);
}
echo json_encode($data);
?>
http://php.net/manual/en/pdostatement.fetch.php
say you can use this if you using pdo
$result = $sth->fetch(PDO::FETCH_OBJ);
$sth is your query
$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.
Sorry for the incredibly newbie question, but I can see myself drifting into bad practices if I don't ask.
I have a PHP method that I want to return all the values of a given database column, in order to place the contents in a dropdown menu for a HTML form. I could obviously construct the whole HTML in the PHP method and return that as a string, but I imagine this is pretty bad practice.
Since PHP methods can only return one value, I imagine I'll need to call the method several times to populate the dropdown menu, or pass an array from the method.
What would be a good solution to this (presumably) common problem? Thanks.
Well, an array is one value, containing tons of other values. So just have your method return a array of results.
edit: as Hammerstein points out you could use objects but its as good/bad as arrays depending on context. Very similar.
You could use an object as your return type. So;
class MyReturnValue
{
public $Value1;
public $Value2;
}
function getMyValues()
{
$results = GetDatabaseValues( ); // Assume this returns an associative array
$result = new MyReturnValue();
$result.Value1 = $results["Value1"];
$result.Value2 = $results["Value2"];
}
Then in your code, you can refer to $result.Value1 etc.
There is no PHP function to do this, so you will have to form an array from the results.
$column = array()
$query = mysql_query("SELECT * FROM table ORDER BY id ASC");
while($row = mysql_fetch_array($query)){
$column[] = $row[$key]
}
Then pass $column to your view(HTML)
foreach($column as $value)
{
echo "<li>" . $value . "</li>";
}
You can have arrays in arrays, so if you have a table with several columns you could assign them to an array as separate arrays:
$all_results = array();
foreach($rowInDatabase as $key => $value){
// each row will be an array with a key of column name and value of column content depending how you get the data from the DB.
$colname = $key;
$colVal = $value; //this is an array
$all_results[$colname] = $colVal; //append the current row to the array
}
}
code like this will populate your array with an array per row of the table so if there are ten rows and five columns you could get row 2 column 3 with $all_results[1][2]; (as they start from 0).
Not quite sure I understand what you want to do fully, but you could always pass the result back from the method, and then loop through it in your HTML.
Your method would be something like:
public function my_method()
{
$result = $db->query($sql_here);
return $result;
}
And then your HTML would be
<select>
<?
$result = $class->my_method();
while($row = $result->fetch_assoc())
{
echo '<option>'.$row['some_col'].'</option>';
}
?>
</select>
I am building a function that acts like Drupal's variable_initialize() function that pulls all key/value pairs into a global variable. I am trying to find the proper parameters I need to put into fetchAll() to remove the row number and get basically what fetch(PDO::FETCH_ASSOC) does but for all returned rows.
I basically want fetchAll to return:
Array {
[name] = value,
[name2] = value2,
[name3] = value3,
}
The variable table is a simple 2 column table (name)|(value)
function variable_init() {
global $db, $variable;
$query = "SELECT * FROM variable";
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(); //need help here
foreach($result as $name => $value) {
$variable[$name] = $value;
}
}
I have tried PDO_COLUMN/PDO_GROUP/etc... but I can't seem to offset the array to remove the row numbers. Thanks.
I think you may be getting confused about what PDOStatement::fetchAll() returns.
The method returns all rows (arrays or objects, depending on fetch style) in an array.
Try this
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$variable[$row['name']] = $row['value'];
}