Logic in while-statement - php

For a search I am using this code snippet:
$stmt = $dbh->prepare('SELECT id,username FROM `users` WHERE `username` LIKE :keyword');
$keyword = "%".$data."%";
$stmt->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['user'] = utf8_encode($row['username']);
array_push($return_arr,$row_array);
}
Instead of getting only those value´s which are "LIKE keyword", I get every result from my table "users", why is this happening?

You should check if $data is empty before preparing the query:
if(!empty($data) && is_string($data)){
$stmt = $dbh->prepare('SELECT id,username FROM `users` WHERE `username` LIKE :keyword');
$keyword = "%".$data."%";
$stmt->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['user'] = utf8_encode($row['username']);
array_push($return_arr,$row_array);
}
} else {
// Do something else
}

Related

Why does the function of two database queries show me only the result of the first query?

The output of the following shows me the result of the first query, but not the second. When I make the queries without function it works.
function builtFooter($catactive, $catlink)
{
global $conn;
$sql = "SELECT catid, catname_de AS name, catlink as link, extern, extlink FROM categories WHERE catactive=? AND catlink!=? ORDER BY catsort";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $catactive, $catlink);
$stmt->execute();
$result = $stmt->get_result();
while ($cat = $result->fetch_assoc()) {
$resArr[] = $cat;
echo '<h3>' . $cat['name'] . '</h3>';
$cities = "SELECT COUNT(a.ad_id) AS ANZ,a.region, b.city, b.citylink FROM ads a, neueorte b WHERE a.zeigen=? AND a.gesperrt=? AND FIND_IN_SET(?, a.portale) AND a.catid=? AND b.po_id=a.region GROUP BY a.region ORDER BY ANZ DESC LIMIT 0,50";
$stmt = $conn->prepare($cities);
$zeigen = 'ja';
$gesperrt = 'no';
$category = $cat['catid'];
$stmt->bind_param("ssss", $zeigen, $gesperrt, $portalnumber, $category);
$stmt->execute();
$result = $stmt->get_result();
while ($city = $result->fetch_assoc()) {
$resArr[] = $city;
echo ' ' . $city['city'] . ' <br />';
}
}
}
builtFooter('yes', 'markt');
This queries are working fine, and I get the result I want:
$catactive = 'yes';
$catlink = 'markt';
$sql = "SELECT catid, catname_de AS name, catlink as link, extern, extlink FROM categories WHERE catactive=? AND catlink!=? ORDER BY catsort";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $catactive, $catlink);
$stmt->execute();
$result = $stmt->get_result();
while ($cat = $result->fetch_assoc()) {
$resArr[] = $cat;
echo '<h3>'.$cat['name'].'</h3>';
$cities = "SELECT COUNT(a.ad_id) AS ANZ,a.region, b.city, b.citylink FROM ads a, neueorte b WHERE a.zeigen=? AND a.gesperrt=? AND FIND_IN_SET(?, a.portale) AND a.catid=? AND b.po_id=a.region GROUP BY a.region ORDER BY ANZ DESC LIMIT 0,50";
$stmt = $conn->prepare($cities);
$zeigen = 'ja';
$gesperrt = 'no';
$category = $cat['catid'];
$stmt->bind_param("ssss", $zeigen, $gesperrt, $portalnumber, $category);
$stmt->execute();
$r = $stmt->get_result();
while ($city = $r->fetch_assoc()) {
$resArr[] = $city;
echo' '.$city['city'].' <br />';
}
}
But when I built a function, I do not get the results of the secode query:
function builtFooter($catactive,$catlink){
global $conn;
$sql = "SELECT catid, catname_de AS name, catlink as link, extern, extlink FROM categories WHERE catactive=? AND catlink!=? ORDER BY catsort";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $catactive, $catlink);
$stmt->execute();
$result = $stmt->get_result();
while ($cat = $result->fetch_assoc()) {
$resArr[] = $cat;
echo '<h3>'.$cat['name'].'</h3>';
$cities = "SELECT COUNT(a.ad_id) AS ANZ,a.region, b.city, b.citylink FROM ads a, neueorte b WHERE a.zeigen=? AND a.gesperrt=? AND FIND_IN_SET(?, a.portale) AND a.catid=? AND b.po_id=a.region GROUP BY a.region ORDER BY ANZ DESC LIMIT 0,50";
$stmt = $conn->prepare($cities);
$zeigen = 'ja';
$gesperrt = 'no';
$category = $cat['catid'];
$stmt->bind_param("ssss", $zeigen, $gesperrt, $portalnumber, $category);
$stmt->execute();
$r = $stmt->get_result();
while ($city = $r->fetch_assoc()) {
$resArr[] = $city;
echo' '.$city['city'].' <br />';
}
}
}
builtFooter('yes','markt');
I have the tables categories, ads, neueorte. I want built footer links, so I want the categorie as a h3 tag and the cities grouped by city where ads are placed. I hope I made it right, I am new to this page.

PHP MYSQLI Query is failing

When trying to run a MYSQLI command in PHP, Its coming back failing.
function DB_query($query, $params = []) {
$conn = DB_connect();
if ($params)
{
$stmt = $conn->prepare($query);
$types = str_repeat('s', count($params));
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = mysqli_query($conn, $query);
}
if ($result)
{
$result = mysqli_fetch_all($result);
return $result;
} else {
return mysqli_affected_rows($conn);
}
}
Here is my query:
DB_query("SELECT count(*) FROM members WHERE email = ? LIMIT 1",[$email])
It runs on:
$result = mysqli_fetch_all($result);
The results from $result: array(1)([0]=>array(1)([0]=>(int)1))
Here is my query:
DB_query("SELECT id, username, password FROM members WHERE email = ? LIMIT 1",[$email]);
It runs on:
$result = mysqli_fetch_all($result);
The results from $result: > array(0)
I have tried changing out the "mysqli_fetch_all" to fetch_all, but I cant figure it out. I need both query to run through the same function.
I cant figure out why the last query is returning nothing in the array.
<?php
$sql = "SELECT * FROM members WHERE email = '".$email."'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_row($result)) {
echo $row[0];
echo $row[1];
echo $row[2];
}
?>
Alternatively, you can use mysqli_fetch_array and use $row['fieldname'] inside the loop.

How would i retrieve the rows from Select Statement

I need to store the rows in an array but can't seem to get it to work, the code is below:
I am sure $result = $stmt->get_result(); does not work.
When i test in the browser output is empty.
<?php
include "connect.php";
$uid = $_REQUEST["U_ID"];
$stmt = $mysqli->prepare("SELECT * FROM U_User WHERE U_ID = ?");
$stmt->bind_param("d", $uid);
$stmt->execute();
$stmt->fetch();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc())
{
$users[] = $row;
}
$stmt->close();
$arr = array('user' => $users);
echo json_encode($arr);
mysqli_close($conn);
?>
Just like php_nub_qq said. I switched to PDO works great.
<?php
include "connect.php";
$uid = $_REQUEST["U_ID"];
$q = $conn->prepare("SELECT * FROM U_User WHERE U_ID = :uid");
$q->execute(array(':uid' => $uid));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
$users[] = $r;
}
$q = $conn->prepare("SELECT * FROM P_Post u WHERE P_U_ID = :uid");
$q->execute(array(':uid' => $uid));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
$posts[] = $r;
}
$q = $conn->prepare("SELECT * FROM T_Thread u WHERE T_U_ID = :uid");
$q->execute(array(':uid' => $uid));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
$threads[] = $r;
}
$arr = array('user' => $users, 'post' => $posts, 'thread' => $threads);
echo json_encode($arr);
$conn = null;
?>

inserting selected row mysql

I would like to use the row that I have selected and echoed to insert to a table again.
So what I want is row to_user. how should I define $to_user to get to_user row?
$to_user = $row['to_user']; //this gives me undefined variable error
$stmt = $mydb->prepare("insert into `messages`(`to_user`) values(?)");
echo $mydb->error;
$stmt->bind_param('s', $to_user);
$stmt->execute();
$stmt = $mydb->prepare("SELECT * FROM messages where id = ? ");
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['to_user'];}
$row['to_user'];
$stmt = $mydb->prepare("insert into `messages`(`to_user`) values(?)");
echo $mydb->error;
$stmt->bind_param('s', $row['tu_user']);
$stmt->execute();
//get the last inserted id and store it in a var
$lastInserted = $mydb->lastInsertId();
$stmt = $mydb->prepare("SELECT * FROM messages where id = ? ");
$stmt->bind_param('s', $lastInserted);
$stmt->execute();
$result = $stmt->get_result();
//for testing
//print_r($result);
// echo $result;
while ($row = $result->fetch_assoc()) {
echo $row['to_user'];}

JSON parse Mysql query result in php pdo

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

Categories