Setting the result of an if statement - php

I am displaying a user's profile image. I have created an if statement to post a default profile image if a user has not updated their own. This is all working, but what I cannot figure out is how to echo or call for each without getting an error for the one not set.
For instance, if they do have a profile picture set, it posts fine, but then I get an error that the other variable is not defined and vise versa.
How should I be calling for this or what changes should I make in my code?
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if ($profilePic === NULL) {
$default_profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$set_profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $default_profile_img;
echo $set_profile_img; ?>
EDIT:
How profilepic gets defined:
$sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY id DESC LIMIT 1
";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param("s", $user_id);
$stmt->execute();
if (!$stmt->errno) {
// Handle error here
}
$stmt->bind_result($id, $user_id, $profilePic);

Just add $default_profile_img = null; and $set_profile_img = null; at the top of php code.
$default_profile_img = null;
$set_profile_img = null;
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if ($profilePic === NULL) {
$default_profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$set_profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $default_profile_img;
echo $set_profile_img; ?>

You just need to initialize the variables before the if..else statements so that it won't be undefined when you try to echo both of them.
$profile_img = "";
$default_profile_img = "";
if (...

Try this code. There is no need to use two different variables. This way, you won't get the warning.
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if (!isset($profilePic) OR $profilePic === NULL) {
$profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $profile_img; ?>

Related

php chat duplicate users prevent

i have problem, on my code i create chat, but duplicate users name, i try prevent but not success.... some can help?
my code:
$sql = "SELECT * FROM `inbox` WHERE `from`='".$_SESSION['username']."' OR `to`='".$_SESSION['username']."' ORDER by `data` DESC;";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$lastuser = "";
while($row = mysqli_fetch_array($result)) {
$chat_name = "";
if($row['from'] == $_SESSION['username']) {
$chat_name = $row['to'];
} else {
$chat_name = $row['from'];
}
if($lastuser != $chat_name) {
echo "
<a href='?user=".$chat_name."'>
<div class='inbox_users_box'>
<div class='inbox_imagenuser'>
<img class='inbox_image' src='".getAvatarOthers($chat_name)."'></img>
<div style='margin-top: 14px; float: left;'>".$chat_name."</div><span style='margin-top: 17px; margin-left: 5px;' class='".getonline_player($chat_name)."'></span>
<div style='clear:both;'></div>
</div>
<div class='inbox_lastmsgdata'>".$row['data']."</div>
</div>
<div style='clear:both;'></div>
</a>
";
$lastuser = $chat_name;
}
}
my chat : my chat picture
i want dont duplicate users..
You can save the filtered inbox entries in an array with the data to display, but only when the user isn't already in that array. This way it gets added only once. After that you print the array the way you like with a normal foreach() loop.
$users = array();
while ($row = mysqli_fetch_assoc($result);
// retrieve the data from MySQL
$chat_name = "";
if($row['from'] == $_SESSION['username']) {
$chat_name = $row['to'];
} else {
$chat_name = $row['from'];
}
$data = $row['data'];
// look if the user is already in the array
$found = false;
foreach ($users as $user) {
if ($user['name'] == $chat_name) {
$found = true;
break;
}
}
if ($found) {
continue;
}
// its not, so add it
$toAdd = array('name' => $chat_name, 'data' => $data);
$users[] = $toAdd;
}
/* display users */
foreach ($users as $user) {
$username = $user['name'];
$data = $user['data'];
// your HTML code here
}

Loop / insertion image

I'm trying to insert images into mysql. The script currently insert one image.
I have put that in the form: name="uploadImage[]" (to make an array).
I understand something is wrong in my code.
I appreciate any help and thank you in advance! :)
<?php
if (isset($_POST['btnSubmit']))
{
$uploaded_images = array();
foreach($_FILES['uploadImage']['name'] as $key=>$val)
{
$upload_dir = "uploads/";
$upload_file = $upload_dir . $_FILES['uploadImage']['name'][$key];
$filename = $_FILES['uploadImage']['name'][$key];
if (move_uploaded_file($_FILES['uploadImage']['tmp_name'][$key], $upload_file))
{
$uploaded_images[] = $upload_file;
$img0 = $filename[0];
$img1 = $filename[1];
$img2 = $filename[2];
$img3 = $filename[3];
$img4 = $filename[4];
echo $filename."<br />";
$created = date("Y:m:d h:i:s");
global $bdd;
$stmt= $bdd->prepare("INSERT INTO annonces_pro(id,ref_member,titre,intro,texte,activite,country,favorite,valid,is_ribbon,date_inserted)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$inserted = $stmt->execute(array('',$ref_member,$titre,$intro,$texte,$activite,$country,'','',$is_ribbon,$created));
$lastId = $bdd->lastInsertId();
global $bdd;
$stmt2 = $bdd->prepare("INSERT INTO annonces_pro_images(id,ref_member,image,is_cover,weight_image,date_published)
VALUES(?,?,?,?,?,?)");
$inserted2 =$stmt2->execute(array($lastId,$ref_member,$filename,'','',$created));
if ($inserted)
{
?>
<div class="alert alert-success" role="alert">
ok<br />
Insert another ad<br />
Back to homepage<br />
</div>
<?php
} else
{
?>
<div class="alert alert-danger" role="alert">Database error</div>
<?php
}
}
}
}
?>
removed global $bdd; as we are already in global scope, we don't need them
moved prepare statements out of the loop, as they only need to be prepared once.
added is_uploaded_file check to check if it's actually an uploaded file.
removed $img..=$filename[..]
changed foreach($_FILES['uploadImage']['name'] as $key => $file to foreach($_FILES['uploadImage'] as $file
for a better and secure version
<?php
if (isset($_POST['btnSubmit']))
{
$stmt= $bdd->prepare("INSERT INTO annonces_pro(id,ref_member,titre,intro,texte,activite,country,favorite,valid,is_ribbon,date_inserted) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt2 = $bdd->prepare("INSERT INTO annonces_pro_images(id,ref_member,image,is_cover,weight_image,date_published)
VALUES(?,?,?,?,?,?)");
$uploaded_images = array();
foreach($_FILES['uploadImage'] as $image)
{
$filename = $image['name'];
if (!is_uploaded_file($filename)) continue;
$upload_dir = "uploads/";
$upload_file = $upload_dir . $image['name'];
if (move_uploaded_file($image['tmp_name'], $upload_file))
{
$uploaded_images[] = $upload_file;
echo $filename."<br />";
$created = date("Y:m:d h:i:s");
$inserted = $stmt->execute(array('',$ref_member,$titre,$intro,$texte,$activite,$country,'','',$is_ribbon,$created));
$lastId = $bdd->lastInsertId();
$inserted2 =$stmt2->execute(array($lastId,$ref_member,$filename,'','',$created));
if ($inserted)
{
?>
<div class="alert alert-success" role="alert">
ok<br />
Insert another ad<br />
Back to homepage<br />
</div>
<?php
} else
{
?>
<div class="alert alert-danger" role="alert">Database error</div>
<?php
}
}
}
}
?>

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);
}
}
?>

IF statement will not work

I am trying to grab favorite posts from 'posts_fav' where the post id is of the row id. Then i want it to if the userid on the query equals the members id it will show 'yes' otherwise it will show 'No'.
Originial:
foreach ($usersfav as $rowfav) {
if ($rowfav["user_id"] == $member["id"])
{
echo 'yes';
}
else
{
echo 'no';
}
}
One of my attempts:
This changes all to the else function. Skips the check of the if as there needs to be a way I can get $rowfav[""] without needing
foreach ($usersfav as $rowfav) {
$sqlfav = "SELECT * FROM posts_fav WHERE post_id = '".$row["id"]."'";
$stmfav = $dbh->prepare($sqlfav);
$stmfav->execute();
$usersfav = $stmfav->fetchAll();
if ($rowfav["user_id"] == $member["id"])
{
echo 'yes';
}
else
{
echo 'no';
}
}
Update:
So I want the posts where rowfav["user_id"] and member["id"] match up to say 'Yes' and other posts without any rows that can be found to say 'no'
Full code:
$sql = "
SELECT *,
(SELECT profilepic FROM users WHERE users.username = users_profiles_comments.author) AS profilepic
FROM users_profiles_comments WHERE postid = '". $row["username"] ."' ORDER BY `id` DESC";
$stm = $dbh->prepare($sql);
$stm->execute();
$users = $stm->fetchAll();
foreach ($users as $row) {
echo ' <div class="row user-row">
<div class="col-xs-3 col-sm-2 col-md-2 col-lg-2">
<img class="img-thumbnail"
src="'.$row['profilepic'].'" width="150px;"
alt="User Pic">
</div>
<div class="col-xs-10 col-sm-10 col-md-10 col-lg-10">
<div class="panel panel-default">
<div class="panel-heading"><b>'. $row["author"] .'</b> - <small>'. $row["date"] .'</small>
';
if ($row["author"]) {
echo '<p style="float:right;">';
$sqlfav = "SELECT * FROM posts_fav WHERE post_id = '".$row["id"]."'";
$stmfav = $dbh->prepare($sqlfav);
$stmfav->execute();
$usersfav = $stmfav->fetchAll();
foreach ($usersfav as $rowfav) {
if (strcmp($rowfav["user_id"], $member["id"]) == 0)
{
echo '
Yes
';
}
else {
echo 'No';
} }
if (count($usersfav)!=0)
{
foreach ($usersfav as $rowfav)
{
if (strcmp($rowfav["user_id"], $member["id"]) == 0)
{
echo 'Yes';
}
}
}
else
{
echo 'No';
}
If I understood it right, you want to get the favourite posts of a user, and with that, get the information that it's his post or not.
You could, as a suggestion, let the check be done on the query, so your results would come already with the flag you want.
$sql = "SELECT posts_fav.*, posts.*, IF(posts.user_id = ?, 1, 0) as owns_post FROM posts_fav LEFT JOIN posts ON posts_fav.post_id = posts.id WHERE posts_fav.member_id = ?";
$query = $dbh->prepare($sql);
$query->bind_param("posts_member_id", $member["id"]);
$query->bind_param("member_id", $member["id"]);
$query->execute();
$rows = $query->fetchAll();
foreach($rows as $row) {
if($row["owns_post"]) {
echo "User owns the post";
} else {
echo "User does not own the post";
}
}
Not tested, no garantee that it even works. :-)

PHP MySQL Fetch Printing Help

Basically I have two files, group.php and class.Groups.php
I am trying to print out the 20 last messages posted to the group, however I cannot figure it out as I am pretty new to this! Any help welcomed.
The problem I am having is that the function I am calling is inside a class. Just dont know how to do the while loop and printing.
Would also welcome suggestions and feedback on my code structure & layout.
Thanks.
class.Groups.php
<?php include("config.php");
// Get Group Details
class Group {
var $groupID;
var $groupName;
var $groupDescription;
var $groupMessage;
function group_details($ID) {
$group_details = mysql_query("SELECT * FROM Groups WHERE GroupID = '".$ID."' LIMIT 1");
if (mysql_num_rows($group_details) == 1) {
$group_details_row = mysql_fetch_assoc($group_details);
$this->groupID = $group_details_row ['GroupID'];
$this->groupName = $group_details_row ['Name'];
$this->groupDescription = $group_details_row ['Description'];
}
}
function group_member($ID) {
$group_member = mysql_query("SELECT * FROM GroupMembers WHERE GroupID = '".$ID."' AND UserID = '".$_SESSION['UserID']."' LIMIT 1");
if (mysql_num_rows($group_member) == 1) {
return 1;
}
else {
return null;
}
}
function group_messages($ID) {
$group_messages = mysql_query("SELECT * FROM GroupMessages INNER JOIN Users ON Users.UserID = GroupMessages.UserID WHERE GroupID = '".$ID."' LIMIT 20");
while ($group_messages_row = mysql_fetch_assoc($group_messages)) {
$this->groupMessage = $group_messages_row['Message'];
}
}
}
?>
group.php
<?php include("includes/class.Groups.php");
$group = new Group;
$group->group_details($_GET['ID']);
if ($_SESSION['LoggedIn'] == 1) {
if ($group->group_member($_GET['ID'])) {
include("includes/header.php"); ?>
<div id="container">
<div id="menu"><?php include("includes/sidebar.php"); ?></div>
<div id="main">
<h2><?php echo $group->groupName; ?></h2>
<p><?php echo $group->groupDescription; ?></p>
<h3>Messages</h3>
<?php
while ($group->group_messages($_GET['ID'])) {
echo $group->groupMessage;
}
?>
</div>
</div>
<?php
}
else {
echo "You are not member of this group.";
}
}
?>
You cannot use $group->group_messages() inside a while, because:
It doesn't return anything (return evaluates to false)
It goes through all the rows in one call, while you are expecting it to return one row at a time
You can rewrite your class code to collect all rows in a variable, return it and the iterate on it using foreach loop
// class.Groups.php
function group_messages($ID) {
$group_messages = array();
$group_messages = mysql_query("SELECT * FROM GroupMessages INNER JOIN Users ON Users.UserID = GroupMessages.UserID WHERE GroupID = '".$ID."' LIMIT 20");
while ($group_messages_row = mysql_fetch_assoc($group_messages)) {
$group_messages[] = $group_messages_row['Message'];
}
return $group_messages;
}
// groups.php
<h3>Messages</h3>
<?php
foreach ($group->group_messages($_GET['ID']) as $group_message) {
echo $group_message;
}
?>
You seem to have an extra curly brace in this chuck of code:
<?php
while ($group->group_messages($_GET['ID'])) {
echo $group->groupMessage; }
} ?>

Categories