Restricting Duplicate results in php mysqli - php

While selecting rows the data should be shown as:
but on the running code it is as:
My Codes:
<?php
$link = mysqli_connect("localhost", "root", "", "trial");
if(!$link){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$term = 'd';//mysqli_real_escape_string($link, $_REQUEST['term']);
if(isset($term)){
$sql = "SELECT * FROM rolls WHERE Place LIKE '%" . $term . "%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
if(mysqli_num_rows($result) > 1000){
echo "<p>There are many results please be more specific</p>";
}
else{
while($row = mysqli_fetch_array($result)){
echo "<p><a href='#". $row['Place'] ."'>" . $row['Place'] . "</a></p>";
}
mysqli_free_result($result);
}
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_close($link);
?>
On trying
$sql = "SELECT * FROM rolls WHERE Place LIKE '%" . $term . "%' LIMIT 1";
it only displays MANDYA, rest all are skipped

If you just want to display the place, use DISTINCT for showing unique values. Check out this query.
$sql = "SELECT DISTINCT(Place) FROM rolls WHERE Place LIKE '%" . $term . "%'";

Related

Displaying image with users product post information?

Im making a website like craigslist where people can make a posting of something they want to sell with a post title, post description, and email.
The problem:
I can pull all data from the db except for the image. When images are uploaded they are stored in C:\xampp\htdocs\uploads and the imagename is saved in the database with the rest of the info. Below is my php. Im trying to pull the name of the image from the db and use that to grab it like this
echo "<img src='uploads/".$image."' width='200'> ";
Im new to php so any tips are appreciated. Is this an ok method to store/retrieve user uploaded images?
Thanks
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "mydb"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql= "SELECT * FROM products";
$result = $con->query($sql);
$image = "SELECT image FROM products";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<img src='uploads/".$image."' width='200'> ";
echo "Title: " . $row["title"]. " Price: $" . $row["price"]. " <br> " . $row["description"]. " <br> " . $row["contact"] . " <br><br>";
}
} else {
echo "0 results";
}
$con->close();
?>
You need to use row same for image like:
$sql= "SELECT * FROM products";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<img src='uploads/".$row["image"]."' width='200'> ";
echo "Title: " . $row["title"]. " Price: $" . $row["price"]. " <br> " . $row["description"]. " <br> " . $row["contact"] . " <br><br>";
}
} else {
echo "0 results";
}
$con->close();

Statements after while loop not executing

I am trying to remove a user from the mailing list right before I perform the emailing to my users. However, the code responsible for this within the second while loop is not executing.
Can somebody see why this is?
<?php
$query = "SELECT * FROM remove_request";
$result = mysqli_query($dbc,$query);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$query = "DELETE FROM mail_table WHERE first_name='" . $row["first_name"]
. "' AND last_name='" . $row["last_name"]
. "' AND email_address='" . $row["email_address"] . "'";
$result = mysqli_query($dbc,$query);
echo $row["first_name"] . ' has been removed from the mail list.';
}
}
$query = "SELECT * FROM mail_table";
$result = mysqli_query($dbc,$query) or die('Error querying database');
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
mail($row["email_address"],$subject,$message,$headers);
echo 'email sent to ' . $row["first_name"] . "\n";
}
}
mysqli_close($dbc);
?>

Variable not recognised in INSERT but working in SELECT

Basically I am using the variable $shopid to recognise which shop has been chosen. I am now trying to create a comment system to enable each shop page to be commented on. My SELECT query is recognising $shopid and enabling me to use it, when I try to use the same variable in my INSERT, it simply posts 0.
<?php
database connection
session_start();
if (isset($_SESSION['logged'])){
$s_userID = $_SESSION['userID'];
$shopid = $_GET['page_id'];
$str_shops = '';
//bring shop data
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE shopID = '$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='result'><strong>" .
$row['image1'] . "<br><br>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br>" .
$row['website'] . "<br><br>" .
$row['openinghours'] . "<br><div class='justifytext'>" .
$row['more'] . "<br><br></div><strong>What do they sell?</strong><br><br><div class='justifytext'>" .
$row['sold'] . "<br><br></div></div>";
}
//post comment
mysqli_select_db($db_server, $db_database);
$comment = $_POST['comment'];
if ($comment != '') {
$query = "INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', '$shopid', '$comment')";
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
$commentmessage = "Thanks for your comment!";
}
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server)); $i = 0;
while($row = mysqli_fetch_array($result)){ $i++;
$str_comments.= "<p><div id='displaycomments'>" . $row['username']. ", " .
$row['commdate'] . ": <br>" .
$row['comment'] . "</div>";
}
}
echo $str_shops;
echo $commentmessage;
echo $str_comments;
mysqli_close($db_server);
?>
Can anyone see why this isn't working? I'm not getting an error, it is simply adding 0 to the shopID column in my table.
My guess would be that your shopID column would be of INT datatype and you are passing a string to it in your insert statement, thats why 0 is being stored.Try again by removing the single quotes around $shopid, like this-
INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', $shopid, '$comment')"
^^^^^^^ remove the single quotes

SQL Query succeeds but no information

Okay so my code works pretty well so far, it all goes through, my only problem is that when I try and print the unordered list and it's contents I get nothing. When I view my source code I have <ul> </ul>. There's a space, so surely something is happening.
This is my code, I have commented it slightly but what's happening is obvious:
$uname = mysqli_real_escape_string($link, $_SESSION['Username']); //Get username ready
$sql = mysqli_query($link, "SELECT * FROM users WHERE Username = '" . $uname . "'"); //SQL Query result
if(!$sql)
{
echo "Error retrieving User ID. Please try again. MySQL Error: " . mysqli_error($link);
}
elseif($row = mysqli_fetch_assoc($sql))
{
$uid = $row['UserID']; //Obtain UserID
}
else
{
echo "Error: " . mysqli_error($link) . "<br />" . $uname . " / " . $sql . " / " . $uid;
}
mysqli_free_result($sql);
$sql = mysqli_query($link, "SELECT * FROM auditions"); //Get everything from the auditions table
if(!$sql)
{
echo "Error retrieving auditions. Please try again later. Error: " . mysqli_error($link);
}
elseif($row = mysqli_fetch_assoc($sql))
{
if(mysqli_num_rows($sql)==0)
{
echo "Sorry, there are currently no open auditions. Please try back at a later date.";
}
else
{
echo "<ul>";
while($row = mysqli_fetch_assoc($sql))
{
echo "<li><a href='auditions.php?id=" . $row['AudID'] . "'>" . $row['AudName'] . "</a></li>";
}
echo "</ul>";
}
}
else
{
echo "Error: " . mysqli_error($link);
}
Where am I going wrong? The only thing it doesn't do is actually pick up any results and I've put some data into the table so there are entries! Otherwise it would say there aren't any. I've reversed this so it shows the message if there aren't 0 entries and that works. What am I doing wrong guys?
Thanks in advance.
You are fetching the result twice. Instead, only fetch the result in the while loop:
<?php
$sql = mysqli_query($link, "SELECT * FROM auditions"); //Get everything from the auditions table
if(!$sql)
{
echo "Error retrieving auditions. Please try again later. Error: " . mysqli_error($link);
}
else{
if(mysqli_num_rows($sql)==0)
{
echo "Sorry, there are currently no open auditions. Please try back at a later date.";
}
else
{
echo "<ul>";
while($row = mysqli_fetch_assoc($sql))
{
echo "<li><a href='auditions.php?id=" . $row['AudID'] . "'>" . $row['AudName'] . "</a></li>";
}
echo "</ul>";
}
}
?>
See this link for more information regarding mysql_fetch_assoc

PDO Search Engine Trouble

I am trying to make an advanced search engine, one in which you can search by first name, last name, zip, city, state, phone, cell phone and email.
I have managed to get it to search by first name, but you have to type the first name correctly as with anything else, I took out everything else but the first name search to find my problem yet, I have yet to find it, Here is a MySQL version of my search code that I am trying to convert to PDO.
MySQL:
<?php
//This is only displayed if they have submitted the form
if ($searching =="yes") {
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
if ($f == "")
if ($info == "")
if ($zip == "")
if ($state == "")
if ($email == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("xxx", "xxxx", "xxx") or die(mysql_error());
mysql_select_db("xxxx") or die(mysql_error());
// We preform a bit of filtering
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM users WHERE fname
LIKE '%" . mysql_real_escape_string($find) . "%' AND lname
LIKE '%" . mysql_real_escape_string($f) . "%' AND info
LIKE '%" . mysql_real_escape_string($info) . "%' AND zip
LIKE '%" . mysql_real_escape_string($zip) . "%' AND state
LIKE '%" . mysql_real_escape_string($state) . "%' AND email
LIKE '%" . mysql_real_escape_string($city) . "%' AND city
LIKE '%" . mysql_real_escape_string($email) . "%'");
?>
<?php
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo "<hr><br>First Name: ";
echo $result['fname'];
echo "<br>Last Name: ";
echo $result['lname'];
echo "<br>Home Phone: ";
echo $result['info'];
echo "<br>Cell Phone: ";
echo $result['cp'];
echo "<br>City: ";
echo $result['city'];
echo "<br>State: ";
echo $result['state'];
echo "<br>Zip: ";
echo $result['zip'];
echo "<br>Email: ";
echo $result['email'];
echo "<br><hr>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:
</b> " .$find;
}
?>
Now here is my PDO version:
<?
$dsn = 'mysql:host=xxx;dbname=xxx;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'xxx','xxx', $opt);
$stmt = $pdo->prepare("SELECT * FROM users WHERE fname= ?");
if ($stmt->execute(array($fname)));
while ($row = $stmt->fetch()) {
print $row['fname'] . "<br>";
print $row['lname'] . "\t<br>";
print $row['info'] . "\n<br>";
print $row['cp'] . "\n<br>";
print $row['state'] . "\n<br>";
print $row['city'] . "\n<br>";
print $row['zip'] . "\n<br>";
print $row['email'] . "\n<br>";
}
?>
Tips, advice, and comments are welcome and appreciated.
I guess you would build a sql-string and use parameters.
You would not include into your sql fields that the user left empty.
// **EDIT** check if there's any user-input...
if (!isset($_POST['fname']) && !isset($_POST['lname'])) { // add all your input-fields
echo "<p>please enter a search term!</p>";
echo 'try again";
exit();
}
$sql = '';
$bind = array();
if (strlen($_POST[‘firstname‘]) > 0) { // assuming your form-method is "post"
$sql .= 'AND fname LIKE :fname ';
$bind['fname'] = '%'.$_POST['firstname'].'%';
}
if (strlen($_POST['lastname']) > 0)
$sql .= 'AND lname LIKE :lname ';
$bind['lname'] = '%'.$_POST['lastname'].'%';
}
// ...
// do this will all of your input-fields...
$sql = 'SELECT * FROM users WHERE ' . trim($sql, 'AND') . ' ORDER BY lname';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($bind));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// go ahead and display your results with foreach...
Your biggest problem is you’re using AND instead of OR in your WHERE clause. Change it to this:
SELECT *
FROM `table`
WHERE `name` LIKE '%string%'
OR `zip` LIKE '%string%'
// AND SO ON

Categories