How to replace username with link in string? - php

I'm trying to check posts to see whether they mention another user, by using #username. I want to replace that with a link to the user's profile.
This is what I've got... I haven't got any errors, but usernames just go through as text without the link. I feel like $getUsers/$gU isn't returning the results to $checkString, but I can't see anything wrong.
function post()
{
global $me;
if($_POST['message'])
{
$getUsers = mysql_query("SELECT user_id, user_name FROM users");
while($gU = mysql_fetch_array($getUsers))
{
$checkString = strpos($_POST['message'], "#".$gU['user_name']."");
if($checkString !== false)
{
$replaceFrom = "#".$gU['user_name']."";
$replaceTo = "<a href=\'/user.php?id=".$gU['user_id']."\'>".$gU['user_name']."</a>";
$checked = str_replace($replaceFrom, $replaceTo, $_POST['message']);
}
else
{
$checked = $_POST['message'];
}
}
mysql_query("INSERT INTO test_table VALUES ('', '".$me['user_id']."', '".$_POST['topic']."', '".$checked."', UNIX_TIMESTAMP())");
index();
}
else {
echo "
<form action='?action=insert' method='post'>
<input type=text name=topic maxlength=40>
<br><textarea name=message cols=80 rows=9></textarea>
<br><input type='submit' STYLE='color: black; background-color: white;' value='Submit' class='btn'>
</form>
";
}
}

mysql_query("INSERT INTO test_table VALUES ('', '".$me['user_id']."', '".$_POST['topic']."', '".$_POST['message']."', UNIX_TIMESTAMP())");
should be
mysql_query("INSERT INTO test_table VALUES ('', '".$me['user_id']."', '".$_POST['topic']."', '".$checked."', UNIX_TIMESTAMP())");
As your user table will eventually grow, I'd suggest compiling a set of potential usernames by searching for #(\w+), preparing a statement looking for that username, iterating through the results and replacing all instances for every returned row with the link.

I think you could have simplify your question by excluding the MySQL part. From what I understand you are trying to replace user mention with an HTML anchor tag.
Instead of looping through all the available users you can use preg_replace_callback() to check if any tagged user exists in system.
Please review the example code below. To simplify things I have created two functions. parseTag() will inject the HTML anchor link if the user exist, otherwise the original tag will be kept. getUserId() will return the user id it exists in the system instead:
<?php
function parseTag($tagInfo){
list($fullTag, $username) = $tagInfo;
$uid = getUserId($username);
if ($uid) {
return "<a href='/url/to/user/{$uid}'>{$fullTag}</a>";
}
return $fullTag;
}
function getUserId($username){
$userList = [null, 'john', 'mary'];
return array_search($username, $userList);
}
$comment = "Hello #john, #doe does not exists";
$htmlComment = preg_replace_callback("/#([\w]+)/", "parseTag", $comment);
echo $htmlComment;
Output:
Hello <a href='/url/to/user/1'>#john</a>, #doe does not exists

Related

Mysql Keeps deleting the written ID but the ID Doesn't exist in Database

I have created a HTML form where you can delete the staff just by putting the ID which is directly connected to the database.
When I put the ID first time it will delete it if its existing but even if it doesnt exist it will still say that it just got deleted even though it was never there.
Here's the PHP part of it
<?php
if(isset($_POST['removeemployees']))
{
$error = "";
if(!isset($_POST['employeeID']))
{
$employeeID = "";
}
else
{
$employeeID = $_POST['employeeID'];
}
if(empty($employeeID))
{
// Empty Employee
$error .= "employeeID Cannot be Empty";
}
//echo "Your Firstname is : $firstname and last name is : $lastname";
if($error == "")
{
$sql = "DELETE FROM employees WHERE ID = $employeeID ";
$result = mysqli_query($con, $sql);
if(mysqli_affected_rows($result) > 1)
{
echo "Record Deleted";
}
else
{
echo "Error Deleting record:".mysqli_error($con);
}
}
else
{
echo $error;
}
}
?>
And here's the HTML part of it, which is simple and working okay.
<div class="removeemployee">
<h3> Remove Employees </h3>
<p>Employee ID</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<input type="text" name="employeeID"><br>
<br><input type="submit" name="removeemployees" value="Submit Information">
</form>
</div>
I' m trying to make it work like this: if the ID is existing you can delete it, if it's not existing it should say that this ID is not existing in database or something like that. At first I thought I have to collect all the data from Mysql then compare it with input ID and go from there but I'm not sure.
No rows to delete is not an error.
If there's an error, mysqli_execute() returns false, not a result object.
mysqli_execute() only returns a result object when the query is SELECT (or some other type that returns a result set); for modification queries it just returns true or false. The argument to mysqli_affected_rows() must be the connection, not the return value.
$sql = "DELETE FROM employees WHERE ID = ?";
$stmt = mysqli_prepare($con, $sql);
$stmt->bind_param("i", $employeeID);
$stmt->execute();
if(mysqli_affected_rows($con) > 1)
{
echo "Record Deleted";
}
else
{
echo "Employee ID does not exist";
}
I've also shown how to recode using a prepared statement to prevent SQL injection.

PHP echo break tag

In my PHP script, there are 3 echo, based on the conditionals
echo "Error"
echo "User already existed"
echo "Success"
One of the echo will be passed to my android apps, if (s.equals("Success")), where s is the echo message.
But the echo I got when the registration success is <br />, according to the logcat. For User already existed have no problem.
Since s is not Success, I can't start another activity which is depended on the string. Can anyone explain how the break tag got echoed? The registration information successfully inserted into database, though.
elseif ($roleID == "C") {
$sql6 = "SELECT runnerID FROM tr_customer WHERE customerID = '$newID'";
$check4 = mysqli_fetch_array(mysqli_query($con,$sql6));
if(!isset($check4)) {
// add into db
$customerID = $roleID . $newID;
$sql7 = "INSERT INTO tr_customer(customerID, name, phoneNo, locationID, roleID, email) VALUES ('$customerID', '$name', '$phoneNo', '$locationID', '$roleID', '$email')";
if(mysqli_query($con,$sql7)) {
echo "Success";
}
} else {
$newID = checkExist();
}
I would examine the code where the variable is defined. If you could post that part of the code as an edit then perhaps someone can review it for you as well. There is just not enough information here to discern where your error is coming from.
EDIT:
Consider changing the way you check for a successful update.
$result = mysqli_query($con,$sql7);
if(mysqli_num_rows($result) == 1){
echo "Success";
}

POST method and arrays

This is my first php project. I have created a website where users can upload their picture and then view the pictures of other users, one person at a time (similar to the old hotornot.com). The code below works as follows:
I create an array (called $allusers) containing all members except for the user who is currently logged in ($user).
I create an array (called $usersiviewed) of all members who $user has previously either liked (stored in the likeprofile table) or disliked (stored in the dislikeprofile table). The first column of likeprofile and dislikeprofile has the name of users who did the liking/disliking, second column contains the name of the member they liked/disliked.
I use the array_diff to strip out $usersiviewed from $allusers. This is the list of users who $user can view (ie, people they have not already liked or disliked in the past).
Now the problem is when I click the like button, it updates the likeprofile table with the name of the NEXT person in the array (i.e., not the person who's picture I am currently looking at but person who's picture appears next). Additionally, if I refresh the current page, the person who's profile appears on the current page automatically gets 'liked' by me. I would really appreciate any advice on this.
<?php
// viewprofiles.php
include_once("header.php");
echo $user.' is currently logged in<br><br>';
echo <<<_END
<form method="post" action="viewprofiles.php"><pre>
<input type="submit" name ="choice" value="LIKE" />
<input type="submit" name ="choice" value="NEXT PROFILE" />
</pre></form>
_END;
$allusers = array();
//Create the $allusers array, comprised of all users except me
$result = queryMysql("SELECT * FROM members");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;
$allusers[$j] = $row[0];
}
//Create the $i_like_these_users array, comprised of all users i liked
$result = queryMysql("SELECT * FROM likeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_like_these_users[$j] = $row[1];
}
//Create the $i_dislike_these_users array, comprised of all users i disliked
$result = queryMysql("SELECT * FROM dislikeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_dislike_these_users[$j] = $row[1];
}
//Create the $usersiviewed array, comprised of all users i have either liked or disliked
if (is_array($i_like_these_users) && is_array($i_dislike_these_users))
{
$usersiviewed = array_merge($i_like_these_users,$i_dislike_these_users);
}
elseif(is_array($i_like_these_users))
{
$usersiviewed = $i_like_these_users;
}
else
{
$usersiviewed = $i_dislike_these_users;
}
// this removes from the array $allusers (i.e., profiles i can view) all $usersviewed (i.e., all the profiles i have already either liked/disliked)
if (is_array($usersiviewed))
{
$peopleicanview = array_diff($allusers, $usersiviewed);
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
else {
$peopleicanview = $allusers;
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
$current_user_profile = $peopleicanview[0];
echo 'check out '.$current_user_profile.'s picture <br />';
if (file_exists("$current_user_profile.jpg"))
{echo "<img src='$current_user_profile.jpg' align='left' />";}
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['choice']) && $_POST['choice'] == 'LIKE')
{
$ilike = $current_user_profile;
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$ilike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['choice']) && $_POST['choice'] == 'NEXT PROFILE')
{
$idontlike = $current_user_profile;
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$idontlike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
?>
Because when you refresh page it sends previus value of
Form again...and problem when u like a user it being liked next user.. There there is something in yor for loop while fetching row ...insted of for loop try once while loop ...i hope it will solve ur problem
You are calculating the $iLike variable with the currently loaded user and then updating the database with that user.
You should probably change your application logic a bit:
pass the user ID of the user you liked or did not like as a POST parameter in addition to the like/didn't like variable
move the form processing logic to the top of your page (or better yet separate out your form processing from HTML display)
Also, it's best not to use the mysql_* extensions in PHP. Use mysqli or PDO.
Try to make two different forms. One with "LIKE", another with "NEXT" to avoid liking from the same form
When you submit your form - your page refreshes, so in string $current_user_profile = $peopleicanview[0]; array $peopleicanview doesn't have user from previuos page (before submitting) you have to attach it, e.g. in hidden field
<form method="post" action="viewprofiles.php">
<input type="hidden" name="current_user" value="$current_user_profile" />
<input type="submit" name ="choice" value="like" />
</form>
<form method="post" action="viewprofiles.php">
<input type="submit" name ="go" value="next" />
</form>
and INSERT it later
"INSERT INTO likeprofile VALUES" . "('$user', '".$_POST['current_user']."')"
ps remove <pre> from your form
Lets start by simplifying and organizing the code.
<?php
// viewprofiles.php
include_once("header.php");
//if form is sent, process the vote.
//Do this first so that the user voted on wont be in results later(view same user again)
//use the user from hidden form field, see below
$userToVoteOn = isset($_POST['user-to-vote-on']) ? $_POST['user-to-vote-on'] : '';
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['like']))
{
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['dislike']))
{
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
//now we can create array of available users.
$currentProfileUser = array();
//Create the $currentProfileUser array,contains data for next user.
//join the 2 other tables here to save php processing later.
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
and `user` <> '$user'
LIMIT 1");
//no need for a counter or loop, you only need the first result.
if(mysql_num_rows > 0)
{
$row = mysql_fetch_assoc($result);
$current_user_profile = $row['user'];
}
else
$current_user_profile = false;
echo $user.' is currently logged in<br><br>';
//make sure you have a user
if($current_user_profile !== false): ?>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="like" value="LIKE" />
</form>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="dislike" value="NEXT PROFILE" />
</form>
check out <?=$current_user_profile?>'s picture <br />
<?php if (file_exists("$current_user_profile.jpg")): ?>
<img src='<?=$current_user_profile.jpg?>' align='left' />
<?php endif; //end check if image exists ?>
<?php else: //no users found ?>
Sorry, there are no new users to view
<?php endif; //end check if users exists. ?>
You'll notice I changed the code a lot. The order you were checking the vote was the main reason for the issue. But over complicating the code makes it very difficult to see what's happening and why. Make an effort to organize your code in the order you expect them to run rather a vote is cast or not, I also made an effort to separate the markup from the logic. This makes for less of a mess of code to dig through when looking for the bug.
I also used sub queries in the original query to avoid a bunch of unnecessary php code. You could easily have used JOIN with the same outcome, but I think this is a clearer representation of what's happening. Also please use mysqli instead of the deprecaded mysql in the future, and be aware of SQL injection attacks and makes use of real_escape_string at the very least.
Hope it works out for you. Also I didn't test this code. Might be a few errors.

Getting two variables from one radio button?

http://i.stack.imgur.com/Gy3o0.png
That is what the site looks like now. What I want to do is when you click on the approve registration on the table, it will extract the value of the id no and the name of that particular record. I thought i was on the right track. I knew how to get the id no. But it doesn't get the value of the name at the same time.
This is how the code looks like:
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr>";
echo "<td><form method=post action=approvedmayor.php><input type='radio' name=id value='$id'></td>";
}
approvedmayor.php
$query = mysql_query("insert into tbcandidates VALUES ($id, '$name', 'mayor')");
if ($query)
{
echo "You appproved ";
echo $name;
}
else
echo "error";
you can try like this...
<?php
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr><td><a href='approvedmayor.php?id=$id&name=$name'>Approve</a></td></tr>";
}
?>
in this type don't use the form, and Approve button... try this alone
Actually it is bad practice to insert that kind of data directly from POST data.
If you have all these candidates already stored in the database, you should run a SELECT query in your approvedmayor.php first, and if the candidate still exists, insert it's data to another table.
$query = mysql_query('SELECT * FROM `candidates` WHERE `id` = '.$id.' LIMIT 1');
if(mysql_num_rows($query)) {
$candidate = mysql_fetch_assoc($query);
$insertQuery = mysql_query("insert into tbcandidates VALUES ($candidate['id'], $candidate['name'], $candidate['mayor'])");
if ($insertQuery) {
echo "You appproved ";
echo $name;
} else echo "error";
} else echo 'This candidate is no longer available';
I understand your question,
But thats not the best way go ahead, Before we move let us understand some little elements functions
Radio Button : Its an input type element, that allows the user to choose only one [ 1 ] of option given list.
Check Boxes : Its an input type element, that allows the user to select n number of options or selections from give list.
Fore info - http://www.w3schools.com/html/html_forms.asp
Now comming to your question..
You need to modify your code to check boxes as below
<input type='checkbox' name=id[] value='$id'>
Notice : elements name is in Array mode.. ie whenever a user one or more than one, the values are stored in array.
Once the values are stored in array, call it / use if however you want.
For your mentioned code
echo "<form method=post action=approvedmayor.php>';
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr>";
echo "<td><input type='radio' name=id[] value='$id'></td>";
}
echo "</form>";
approvedmayor.php
$temp_app_arr = $_POST['id'];
foreach ($temp_app_arr as $pos => $val) {
$query = mysql_query("insert into tbcandidates VALUES ('$val', '$name', 'mayor')");
if ($query) {
echo "You appproved ";
echo $name;
} else {
echo "error";
}
}
And i believe this should gonna be good code / algorithm for your project.

Can't insert value in db

I have a strange thing over here. I'm trying to insert a value in my database but it's not working for some reason. I have this code:
PHP:
<input type='file' name='images[]' />
<input type="text" name="newproject_name" id="tags"/>
<input type='text' name='order[]' value='$b' />
$project = new Project();
$project->photo = $_FILES['images']['name'][$key];
$project->order = $_POST['order'][$key];
$projectnaam = $_POST['newproject_name'];
if($project->createProject($_DB)) {
echo "OK";
} else {
echo "NOT OK";
}
}
FUNCTION:
class Project {
public function createProject($db) {
$sql = "INSERT INTO tblProject (
project,
photo,
order) // If you remove this line, the function is working
VALUES(
'".$db->escape($this->project)."',
'".$db->escape($this->photo)."',
'".$db->escape($this->order)."' // If you remove this line, the function is working
)";
return $db->insert($sql);
}
}
Strange thing is, when I delete the order-lines, the function is working just fine. I really don't know what I'm doing wrong...
ORDER is a reserved word. If you use backticks around the column name you should be good:
$sql = "INSERT INTO tblProject (
`project`,
`photo`,
`order`)
VALUES(
'".$db->escape($this->project)."',
'".$db->escape($this->photo)."',
'".$db->escape($this->order)."'
)";
I suggest you change the order column name to position or display_order.

Categories