My array is empty when I'm binding an id variable. The table contains 5 columns that I'd like in an array. This is what I tried:
$records = array();
$id = 22;
if($results = $db->prepare("SELECT * FROM categories WHERE id = ?")) {
$results->bind_param('i', $id);
$results->execute();
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results->free();
}
}
print_r($records);
you are binding param 'i' but using a '?' placeholder. Use one of these:
if($results = $db->query("SELECT * FROM categories WHERE id = ?")) {
$results->bind_param(1, $id);
or
if($results = $db->query("SELECT * FROM categories WHERE id = :i")) {
$results->bind_param(':i', $id);
See http://www.php.net/manual/en/pdostatement.bindparam.php for more examples.
Related
I have this function which returns only one row, How can I modify the function so that it returns more than one row?
public function getVisitors($UserID)
{
$returnValue = array();
$sql = "select * from udtVisitors WHERE UserID = '".$UserID. "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
There is a function in mysqli to do so, called fetch_all(), so, to answer your question literally, it would be
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ".intval($UserID);
return $this->conn->query($sql)->fetch_all();
}
However, this would not be right because you aren't using prepared statements. So the proper function would be like
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $UserID);
$stmt->execute();
$res = $stmt->get_result();
return $res->fetch_all();
}
I would suggest storing them in an associative array:
$returnValue = array();
while($row = mysqli_fetch_array($result)){
$returnValue[] = array('column1' => $row['column1'], 'column2' => $row['column2']); /* JUST REPLACE NECESSARY COLUMN NAME AND PREFERRED NAME FOR ITS ASSOCIATION WITH THE VALUE */
} /* END OF LOOP */
return $returnValue;
When you call the returned value, you can do something like:
echo $returnValue[0]['column1']; /* CALL THE column1 ON THE FIRST SET OF ARRAY */
echo $returnValue[3]['column2']; /* CALL THE column2 ON THE FOURTH SET OF ARRAY */
You can still call all the values using a loop.
$counter = count($returnValue);
for($x = 0; $x < $counter; $x++){
echo '<br>'.$rowy[$x]['column1'].' - '.$rowy[$x]['column2'];
}
I need to merge categories and subcategories into one array. Here is code.
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
while($rows = $q->fetch()){
$cat[] = $rows['id'];
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $rows['id']);
$q->execute();
while($row = $q->fetch()){
$list[] = $row['id'];
}
$data = array_push($cat, $list);
echo $data;
}
I am getting 2 value when printing instead ids numbers
are you want to merge $cat and $list?
you can try:
array_merge($cat, $list);
I solved this problem with the help of this post combine-results-from-two-pdo-queries
$id = '1';
$results = array();
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
while($rows = $q->fetch(PDO::FETCH_ASSOC)){
$results[] = $rows['id'];
}
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $id);
$q->execute();
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$results[] = $row['id'];
}
var_dump($results);
I think what you want is this:
$sql = 'select * from category where id = ?';
$q = $db->prepare($sql);
$q->bindParam(1, $id);
$q->execute();
$data = array();
while($rows = $q->fetch()){
$cat[] = $rows['id'];
$s = 'select * from category where category_id = ?';
$q = $db->prepare($s);
$q->bindParam(1, $rows['id']);
$q->execute();
while($row = $q->fetch()){
$list[] = $row['id'];
}
$data = array_merge($data, $cat, $list);
//$data = array_unique($data);
print_r($data);
}
Notice the $data = array(); before the while loop. With array_merge you merge categories and subcategories with the $data array into the data array.
If you happen to get duplicted value you do not need or want, simply uncomment $data = array_unique($data); and it will erase duplicated entries for you.
Please clarify your question, if I do not address your problem and I will update my answer.
Have fun, may the source be with you.
I'm having a hard time getting this search results with pagination code to work. It does successfully grab the search keyword entered in the html form on another page and brings it into this search.php page. if I echo $search I see the keyword on the page. But I get no results even though I should for the query. Can anyone see what might be going on?
require "PDO_Pagination.php";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
echo $search;
$pagination->rowCount("SELECT * FROM stories WHERE stories.genre = $search");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories WHERE stories.genre = $search ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
else
{
$pagination->rowCount("SELECT * FROM stories");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
$query = "SELECT * FROM stories";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
$query .= " WHERE genre LIKE '%$search%'";
}
// No need for else statement.
$pagination->rowCount($query);
$pagination->config(3, 5);
$query .= " ORDER BY SID ASC LIMIT {$pagination->start_row}, {$pagination->max_rows}";
$stmt = $connection->prepare($query);
$stmt->execute();
$model = $stmt->fetchAll();
var_dump($model);
In your query do:
WHERE stories.genre LIKE '%string%');
instead of:
WHERE stories.genre = 'string');
Because the equals will want to literally equal the field.
please be easy on me, i just started learning PDO and still finding my way how to convert my mysqli to PDO.
so i have a function to get the contents from my database
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($sql);
$row = $sql->fetchAll(PDO::FETCH_ASSOC);
return $row;
}
normally when i return $row in mysqli, i would define fetch_assoc() in my while loop.
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$content = $row['content'];
}
Now, since (PDO::FETCH_ASSOC) is already declared in my function.
how would i properly create my while loop to print the values in PDO?
[edit]
updated code
i will be declaring my while loop outside of the function. so i need something to return from my function but i dont know what that is..
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($query);
$row = $sql->execute();
return $row;
}
this is my while loop outside the function.
$sql = getContent();
while ($row = $sql->fetchAll(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$content = $row['content'];
}
With fetchAll() you don't have to use while at all. As this function returns an array, you have to use foreach() instead:
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($query);
$sql->execute();
return $sql->fetchAll();
}
$data = getContent();
foreach($data as $row) {
$id = $row['id'];
$content = $row['content'];
}
I am trying to do following
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return return json_encode(array('Result'=>$row);
Works and fetches all entries in a table make then JSON Array and send them,
However I want to make a query where selected ids must be send in a JSON Array
E.g 10, 20, 30
I assume that this will be done in a For loop perhaps
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
$row = $statement->fetch(PDO::FETCH_OBJ)))
Now suppose i have id's = 10,20,30 i want to append all of them in a JSON Array How can i do that?
just like return json_encode(array('Result'=>$row);
Edited Code
function GetMyMembers()
{
$myId = trim($_REQUEST['myId']);
try {
$conn = $this->GetDBConnection();
$statement = $conn->prepare('SELECT valId FROM memList WHERE myId=:myId' );
$statement->bindParam(':myId', $myId, PDO::PARAM_INT);
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
// $row contains ALL THE ID'S
$placeholders = str_repeat('?,', count($row));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM players WHERE id IN ($placeholders)";
$statement = $conn->prepare($sql);
$statement->execute($row);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return $rows;
}
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[$row['id']] = $row;
}
return json_encode(array('Result'=>$data));
Btw, using raw API is not convenient. With Database abstraction library your code can be as short as 2 following lines:
$data = $db->getInd("id",'SELECT * FROM myTable');
return json_encode(array('Result'=>$data));
Edit:
if you have an array of ids, you need more complex code
$ids = array(1,2,3);
$data = array();
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
foreach ($ids as $id) {
$statement->bindValue(':id', $id, PDO::PARAM_STR);
$statement->execute();
$data[] = $statement->fetch(PDO::FETCH_OBJ);
}
return json_encode(array('Result'=>$data));
But while using Database abstraction library, there will be the same 2 lines:
$data = $db->getAll('SELECT * FROM myTable where id IN (?a)', $ids);
return json_encode(array('Result'=>$data));
Edit2:
if you need ids only
$statement = $conn->prepare('SELECT id FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[] = $row['id'];
}
return json_encode(array('Result'=>$data));
while using Database abstraction library, it's still 2 lines:
$ids = $db->getCol('SELECT id FROM myTable');
return json_encode(array('Result'=>$ids));
$ids = array(1,2,3);
$placeholders = str_repeat('?,', count($ids));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM table WHERE id IN ($placeholders)";
$sth = $dbh->prepare($sql);
$sth->execute($ids);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
echo json_encode(array('Result' => $rows));
Based on additional comments:
Best option:
$sql = '
SELECT *
FROM table1 AS t1
INNER JOIN table2 t2
ON t2.foreign_key = t1.id
';
or
$sql = 'SELECT id FROM table1';
$sth = $dbh->prepare($sth);
$sth->execute();
$ids = $sth->fetchColumn();
//next look above