Foreach loop prints only one name instead of several - php

Here I've written my code in the search.php file
if(isset($_POST['searchField'])){
$searchName = UserManager::searchName();
if(empty($_POST['searchField'])){
$error = 'Typ a name';
}else{
if(!isset($_POST['searchName'])){
$error = 'No result';
} else{
foreach($searchName as $name){
$succes = $name['firstName'] . " ". $name['lastName'];
}
}
}
}
Here is a part of the HTML where it prints the full names.
<div class="form-group">
<?php if(isset($error)): ?>
<p>
<?php echo $error; ?>
</p>
<?php endif; ?>
<?php if(isset($succes)): ?>
<p>
<?php echo $succes; ?>
</p>
<?php endif; ?>
</div>
Here is my function:
public static function searchName()
{
$conn = Db::getConnection();
$searchField = $_POST['searchField'];
$statement = ("SELECT * from tl_user WHERE firstname = :name OR lastname = :name");
$query = $conn->prepare($statement);
$query->bindValue(':name', $searchField);
//var_dump($searchField);
$query->execute();
//"SELECT * from tl_user WHERE firstName LIKE '%$searchName% OR lastName LIKE '%$searchName%"
$count = $query->fetchAll(PDO::FETCH_ASSOC);
var_dump($count);
return $count;
}
My question exactly is: if there are more people with the same lastName, it prints only 1 full name instead of several names.
In my function I've put 'var_dump($count);' to see if there is more than 1 array and there is, but it doesn't print
I'm a beginner, so I'm still learning :)

concatenate values into $succes using .= rather than overwriting it each time round the loop
$succes = '';
foreach($searchName as $name){
$succes .= $name['firstName'] . " ". $name['lastName'];
}

Related

Is this a correct way of using AND,OR in mysql?

Im working on a private message system just like in a simple forum website. But im not sure if the SELECT query is in correct way.
Im trying to show every message on the chat box therefore for example userA sent a message to userB and userB might sent another message to userA. But im keep getting "problem" string (which is in else statement, wouldnt query...).
$alici = $_GET['user'];
$username = $_SESSION['username'];
$mesajlar = $con->prepare("SELECT * FROM messages WHERE sender_name=:s AND receiver_name=:r OR sender_name=:s2, AND receiver_name=:r2");
$mesajlar->execute([':s'=>$username, ':r'=>$alici, ':s2'=>$alici, ':r2'=>$username]);
if ($mesajlar->rowCount() > 0) {
foreach ($mesajlar as $mesajlar_each) {
$sender_name = $mesajlar_each['sender_name'];
$receiver_name = $mesajlar_each['receiver_name'];
$messsage = $mesajlar_each['message_text'];
if($sender_name == $username){
?>
<div class="grey-message">
Me
<p> <?php echo $message; ?> </p>
</div>
<?php
}
else{
?>
<div class="white-message">
<?php echo $sender_name; ?>
<p><?php echo $message; ?> </p>
</div>
<?php
}
}
}
else{
//problem
echo "problem";
}
?>
```
I might write that this way:
$query = "
SELECT c.olumns
, y.ou
, a.ctually
, n.eed
FROM messages m
WHERE (:s,:r) IN ((m.sender_name,m.receiver_name)
,(m.receiver_name,m.sender_name))";
$mesajlar = $pdo->prepare($query);
$mesajlar->execute(['s' => $username,'r' => $alici]);
$result = $stmt->fetch();

I can echo all my data on my website, but I can't put all of it in my html

Alright, so this is my code:
require_once"database.php";
$result = $db->query("SELECT * FROM reserveringen");
if($result->num_rows != 0) {
while($rows = $result->fetch_assoc()) {
$Email = $rows["Email"];
$Tijd = $rows["Tijd"];
}
}
I want to get all of the rows from my table called "reserveringen" and place it inside my html. When I type echo("$Email $Tijd") it gives me all the Emailaddresses and Tijd that I need. But when I type $message = "$Email $Tijd"; and put the $message in my html it only gives me 1 Email and 1 Tijd. Does anyone know what I'm doing wrong?
EDIT:
<?php if($message) { ?>
<p><?= $message; ?></p>
<?php } ?>
As i though you assign $message in the while loop and overwrite it each iteration, so at the end the last element is stored in the variable.
If you then print it outside of the loop only the last element get's printed.
So what you could do is, make $message a array and print it with a loop like this:
$message = array();
while($rows = $result->fetch_assoc()) {
$Email = $rows["Email"];
$Tijd = $rows["Tijd"];
$message[] = "$Email $Tijd";
}
And then you can print it like this:
<?php
if(!empty($message)) {
foreach($message as $value) {
?>
<p><?= $value; ?></p>
<?php
} //end foreach
} //end if
?>
(Or if you want you can output the values directly in the while loop)

How to create a PHP function that contain a MySQL query?

Hello at the moment I'm using a PHP file called select_Type.php that contain a MySQL query to create a <select></select> Box into HTML. I'm using include_once to link my admin.php and ./Includes/select_Type.php. I already created a file called ./Includes/functions.php where all my querys should be set in PHP functions.
I would like to learn more about functions.
Admin page admin.php where the <select></select> is :
<?php
session_start();
include_once './Includes/functions.php';
CheckLogIn('Superadmin');
SelectType();
//require_once './Includes/select_Type.php';
require_once './Includes/register.php';
?>
select_type.php :
<?php
require_once 'functions.php';
$querySQL = "SELECT * FROM tbltype";
$queryResult = GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)){
$dataArrayType[] = $row;
}
?>
What I tried:
<?php
function SelectType() {
GLOBAL $_POST;
$querySQL = "SELECT * FROM tblType";
$queryResult=GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayType[] = $row;
}
}
?>
What am I doing wrong ?
Thanks in advance :)
Thank you all especially Déjà vu !!!!!
You were all very helpfull.
The problem was, how most of you told me: I didn't returned the value.
Before:
<?php
function SelectType() {
GLOBAL $_POST;
$querySQL = "SELECT * FROM tblType";
$queryResult=GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayType[] = $row;
}
}
?>
Now:
I deleted the GLOBAL $_POST becauce $_POST is already GLOBAL.(Thanks to ɴ ᴀ ᴛ ʜ)
<?php
function SelectType() {
$querySQL = "SELECT * FROM tblType";
$queryResult=GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayType[] = $row;
}
return $dataArrayType;
}
?>
admin.php
I put my function SelectType() in my foreach. Et voila!
<select type="text" id="register_type" name="register_type" required>
<?php
foreach (SelectType() as $row) {
echo "<option value='" . $row['idType'] . "'>" . $row['dtType'] . '</option>';
}
?>
</select>
You can use this:
function sel($table,$field="*", $condition="1",$sort="" ){
if($sort!='') $sort="order by $sort ";
//echo "select $field from $table where $condition $sort ";
$sel_query=mysql_query("select $field from $table where $condition $sort ");
//$sel_result=array();
while($temp_res=#mysql_fetch_array($sel_query))
{
$sel_result[]=$temp_res;
}
return isset($sel_result)?$sel_result: 0;
}
And get result:
$temp_res=sel("post","*"," userid ='".$frnd['friend']."' ORDER BY id DESC");
if($temp_res)foreach($temp_res as $row){
echo $row['content'];
}

using php code inside an echo

My question to you is how do I get the code below to echo its entirety? I have multiples of these that I need to echo using while and I have toyed with it but have yet to figure out what to do. The answers I have seen, I have tried but they just don't work on my code. I need to have all this code here in one bunch but I am having an issue inserting the "like button" section. The issue starts at
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
and here's the full code
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo '
<div class="wrapper">
<div class="submissions">
<div class="logo-logo"><h2>Questions.</h2>
<div class="checkboxes">'.$row['formtype'].'
</div>
</div>
<div class="top-submit">
&#8220'. $row["actual_quote"] . '”
</div>
<div class="poster">- '. $row["poster"].'
<div class = "like">- '.
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
$dislikes = (empty($_POST['dislike'])) ? : $_POST['dislike'] ;
$ip = $_SERVER['REMOTE_ADDR'];
if(isset($_POST['like'])){
$likes1 = $likes+1;
$voted1 = $voted+1;
$query2 = $db->prepare("INSERT INTO voters (voted, ip) VALUES ( :voted, :ip)");
$query2->bindParam(':voted', $voted1, PDO::PARAM_STR);
$query2->bindParam(':ip', $ip, PDO::PARAM_STR);
$query2->execute();
header("Location: like.php?");
$update1 = $db->prepare("INSERT INTO votes (likes) VALUES ( :likes)");
$update1->bindParam(':likes', $likes1, PDO::PARAM_STR);
$update1->execute();
}
if(isset($_POST['dislike'])){
$dislikes1 = $dislikes+1;
$voted1 = $voted+1;
$query2 = $db->prepare("INSERT INTO voters (voted, ip) VALUES ( :voted, :ip)");
$query2->bindParam(':voted', $voted1, PDO::PARAM_STR);
$query2->bindParam(':ip', $ip, PDO::PARAM_STR);
$query2->execute();
header("Location: like.php?");
$update1 = $db->prepare("INSERT INTO votes (dislikes) VALUES ( :dislikes)");
$update1->bindParam(':dislikes', $dislikes1, PDO::PARAM_STR);
$update1->execute();
}
$stmt = $db->query("SELECT * FROM voters");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row3 = $stmt->fetch();
echo "Likes: $likes <br /> Dislikes: $dislikes<br />";
if(isset($row3['voted'])){
if(isset($row3['ip'])){
echo "You have already voted for this.";
}
} else {
echo "<form action = '' method = 'post'> <input type = 'submit' name = 'like' value = 'like'> <input type = 'submit' name = 'dislike' value = 'dislike'></form>";
}'
</div>
<!-- use select to get the items to stay on the page-->
</div>
</div>
</div>
';
}
There may be a very simple solution but I have searched everywhere for it. I have tried using a . at the end but it doesn't like that. Any suggestions?
EDIT I have changed one portion, the whole code starting at $likes and ending after else{} has been put as this:
<div class = "like">';
include("like.php");
echo'</div>
You don't. You stop your echo, do your other code, and start echoing again.
echo 'foo';
bar();
echo 'baz';
You shouldn't use echo in this way.
Try to keep your HTML in variable and concatenate all needed additional HTML using dot after checking all necessary conditions.
$output = '<div>blahblah</div>';
if ($somedatafromDB == true) {
$output .= '<p>true!!</p>';
} else {
$output .= '<p>false :/</p>';
}
// and finally
echo $output;
An issue might also be the ternary operator:
Your code is currently
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
Try to change it to
$likes = (empty($_POST['like'])) ? 0 : $_POST['like'];
You need to specify what you would like to return if the $_POST['like'] is empty.
The ternary operator (x?y:z) returns y if x is true, else it returns z. In your case y is missing which might cause an error during execution.
A good practice is ini_set("display_errors", "on"); at the beginning of the script for debugging purposes.

Update the query to combat google bot hacking

I have a code in php where i m clikcing on women products or any other link for any other product.On click of which i m going to next page and passing the product name in querystring.
And then in next page i m using my sql query,which will give me the list of products which u clicked on first page.There are lot of queries in my project like this one.This query is quite prone to Google bots hacking with SQL injection.Following is the code
<html>
<head>
</head>
<body>
<ul id="list">
<li><h3>tops</h3></li>
<li><h3>suits</h3></li>
<li><h3>jeans</h3></li>
<li><h3>more</h3></li>
</ul>
</body>
</html
Search.php
<?php
$mysqli = new mysqli('localhost', 'root', '', 'shop');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
}
?>
<html>
<head>
</head>
<body>
<?php
session_start();
$lcSearchVal=$_GET['name'];
//echo "hi";
$lcSearcharr=explode("-",$lcSearchVal);
$result=count($lcSearchVal);
//echo $result;
$parts = array();
$parts1=array();
foreach( $lcSearcharr as $lcSearchWord ){
$parts[] = '`PNAME` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
$parts1[] = '`TAGS` LIKE "%'.$lcSearchWord.'%"';
//$parts[] = '`CATEGORY` LIKE "%'.$lcSearchWord.'%"';
}
$stmt = $mysqli->prepare('SELECT * FROM xml where'.'PNAME LIKE ?');
var_dump($stmt);
$parts='%women%';
$stmt->bind_param('s',$parts);
$list=array();
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
$list[]=$row;
}
}
$stmt->close();
$mysqli->close();
foreach($list as $array)
{
?>
<div class="image">
<img src="<?php echo $array['IMAGEURL']?>" width="200px" height="200px"/></a>
<?php
}
?>
</div>
</body>
</html>
The query i m using above is quite prone to Google Bot hacking.Please guide me what should i change in this query so that Google Bot wont be able to hack my application with mysql injection..There are some other similar queries in my application to this one.Please guys help me on this.
The reason this is open to SQL injection is that you have not escaped the input.
For example you have the line:-
$parts[] = '`PNAME` LIKE "%'.$lcSearchWord.'%"';
If someone had used a link something like as follows (ignoring the encoding to get it to work in a URL):-
search.php?name=fred%' UNION SELECT * FROM users #
the SQL you would land up with would be something like:-
SELECT * FROM xml WHERE (`PNAME` LIKE "%fred%' UNION SELECT * FROM users #%")limit '.$offset.', '.$limit1.'
then they can execute a query to get data from the other table (possibly one containing the passwords, etc), with just a bit of patience getting the right number of columns, etc.
If you switch to mysqli_* you can use parameterised queries, but these are a minor pain when the SQL itself changes (as yours does in this case with a variable number of LIKE statements).
The simple solution would be to use mysql_real_escape_string() / mysqli_real_escape_string() on the variable you use in the SQL.
foreach( $lcSearcharr as $lcSearchWord )
{
$parts[] = '`PNAME` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
$parts1[] = '`TAGS` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
//$parts[] = '`CATEGORY` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
}
It is worth switching to mysqli_* if you can.
EDIT
Played with script using mysqli_() and a class and function to cope with variable numbers of parameters
<?php
session_start();
$mysqli = new mysqli('localhost', 'root', '', 'shop');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
}
?>
<html>
<head>
</head>
<body>
<?php
if (array_key_exists('name', $_GET))
{
$lcSearchVal = $_GET['name'];
$lcSearcharr = explode("-",$lcSearchVal);
$result = count($lcSearchVal);
$parts = array();
foreach( $lcSearcharr as $lcSearchWord ){
$parts[] = "%$lcSearchWord%";
}
$bindParam = new BindParam();
$parms = array();
foreach($parts as $aPart)
{
$parms[] = ' PNAME LIKE ? ';
$bindParam->add('s', $aPart);
}
$query = 'SELECT IMAGEURL FROM xml where '.implode(' OR ', $parms);
$stmt = $mysqli->prepare($query);
if ($stmt)
{
call_user_func_array(array($stmt, "bind_param"), refValues($bindParam->get()));
if ($stmt->execute())
{
while ($row = $stmt->fetch())
{
echo '<div class="image"><img src="'.$row['IMAGEURL'].'" width="200px" height="200px"/></a>';
}
}
else
{
echo $mysqli->error;
}
$stmt->close();
$mysqli->close();
}
else
{
echo $mysqli->error;
}
}
else
{
?>
<ul id="list">
<li><h3>tops</h3></li>
<li><h3>suits</h3></li>
<li><h3>jeans</h3></li>
<li><h3>more</h3></li>
</ul>
<?php
}
?>
</div>
</body>
</html>
<?php
function refValues($arr)
{
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value) $refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
class BindParam
{
private $values = array(), $types = '';
public function add( $type, $value )
{
$this->values[] = $value;
$this->types .= $type;
}
public function get()
{
return array_merge(array($this->types), $this->values);
}
}
?>

Categories