PHP mySQL search script for website - php

I highly appreciate that you try to help me.
My problem is this script:
<?php include("inc/incfiles/header.inc.php"); ?>
<?php
$list_user_info = $_GET['q'];
if ($list_user_info != "") {
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
$user_list = $get_user_list['username'];
$user_profile = "profile.php?user=".$user_list;
$profilepic_info = $get_user_list['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/avatar.png";
}
else {
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
if ($user_list != "") {
?>
<br>
<h2>Search</h2>
<hr color="#FF8000"></hr>
<div class="SearchList">
<br><br>
<div style="float: left;">
<img src="<?php echo $profilepic_info; ?>" height="50" width="50">
</div>
<?php echo "<h1>".$user_list."</h1>"; ?>
</div>
<?php
}
else {
echo "<br><h3>User was not found</h3>";
}
}
else {
echo "<br><h3>You must specify a search query</h3>";
}
?>
I am creating a search script that takes the mysql databse information and shows the result associated to the search query. My script is the above, but keep in mind the sql connection is established in an extern scipt.
The problem is that i want the script to first check if the user is found with the search query in the username row, and then get the entre information from that user and display it. If the user is not found with the username query, it should try and compare the search query with the name row, and then with the last name row. If no result is displayed it should then return an else statement with an error, e.g. "No user wsas found"
Yours sincerely,
Victor Achton

Do the query as Muhammet Arslan ... but just counting the rows would be faster ...
if(mysql_num_rows($get_user_info)){
//not found
}
you should add a "Limit 1" at the end if you are just interested in one result (or none).
But read about prepared statements
pdo.prepared-statements.php
This is how it should be done in 2013!

Something like this but you don't need 3 queries for this. you can always use OR in mysql statements
$handle1 = mysql_query("SELECT * FROM users WHERE username = $username"); // Username
if (($row = mysql_fetch_assoc($handle1) !== false) {
// username is found
} else {
$handle2 = mysql_query("SELECT * FROM users WHERE name = $name"); // name
if (($row = mysql_fetch_assoc($handle2) !== false) {
// name is found
} else {
$handle3 = mysql_query("SELECT * FROM users WHERE lastname = $lastname"); // Last name
if (($row = mysql_fetch_assoc($handle3) !== false) {
// last name is found
} else {
// nothing found
}
}
}

Already you did ,but you can improve it by using "AND" or "OR" on ur sql statement.
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info' or name = '$list_user_info' or last_name = '$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
if(empty($get_user_list))
{
echo "No User was found";
}
and you should control $list_user_info or u can hacked.

Here some adapted copy pasting from php.net
Connect
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
fetch data
$stmt = $dbh->prepare("SELECT * FROM users where name LIKE '%?%'");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
the rest is your programing ...
And do some reading it's very dangerous to use copied code without understanding !

Related

PDO and While function in PHP not working

Hey guys so i really have a problem in php and i have been working on it for like an hour and i can get it to work. So in my database i have two tables:
usuarios and menus
So each user have a menu assigned like this:
usuarios
id email ....... menus
1 email ...... 1,2,3,4
where 1,2,3,4 is text that i will explode and convert it into an array so latter i can get the menus checking the menu id's.
menus
id url .....
1 profile ..........
2 messages ..........
3 log out ..........
4 support ..........
I dont know why it is not working, please help.
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));}
// Checks the user id from his session (session has been already started in headers)
if($stmt->rowCount() > 0){
$row = $stmt->fetch();
$menus = $row['menus'];
//Gets the menus
$menus = explode(",", $menus);
//Converts the text into an array.
$i = 0;
$menusize = sizeof($menus);
//Checks how big is $menus array
$menusize = $menusize -1;
//This is because $i=0 and not 1
while ($i == $menusize) {
try{
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
$stmt->execute(array(':menus'=>$menus[$i]));
$row = $stmt->fetch();
if ($section==$row['url']) {
echo '<li class="liselected"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}else{
echo '<li class="menuelement"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
$i++;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Here is the problem, in this while
} else {
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}else{
header("Location:index.php");
}
?>
I have checked and what happends is that $i doesnt seems to be incrementing, i have been working on it but nothing seems to do it.
Thank you all for your support!
You should do it a little bit differently altogether, like storing the menu's in different rows but for now:
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
# When you set the $_SESSION['id'] and you're sure it's sanitized you don't have to prepare a query. Instead execute it directly.
# Preparing is useful for user submitted data or running the same query more then once with different values (seen below)
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
// This part of the code does not match your description of your database.
$row = $stmt->fetch();
$menu = explode(",", $row['menus']);
// end
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
try{
foreach($menu as $value){
$stmt->execute(array(':menus'=>$value));
$row = $stmt->fetch();
$css_class = ($section == $row['url']) ? 'liselected' : 'menuelement';
echo '<li class="'.$css_class.'"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
} else {
header("Location:index.php");
}
?>
Please note that I only prepared the query once, this is the proper way to do it. Preparing takes server performance, but once prepared you can rebind the values.
Also, I changed the loop to a foreach loop, easier to maintain.
There where also some bracket issues in the code, my advice always code in the same way so these issues are easy to spot.

passed variable returns empty in url on target page

I am going out of my mind as it is. I am trying to pass a variable from a page that shows all albums thumbnail image and name to a page that will display all the pictures in that gallery using that passed variable, but the variable is empty in the url on the target page. I have seen similar cases on the web and on this site and I've applied the suggestions but it's still the same. Here is the code that lists the thumbnail and passes the variable(id).
<?php
include ("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
$albums = mysqli_query($conn,"SELECT * FROM albums");
if (mysqli_num_rows($albums) == 0) {
echo "You have no album to display. Please upload an album using the form above to get started. ";
}
else{
echo "Albums created so far:<br><br>";
echo "<table rows = '4'><tr>";
while ($thumb = mysqli_fetch_array($albums)) {
echo '<td><a href ="view.php?id="'.$thumb['id'].'"/><img src = "'.$thumb['thumbnail'].'"/><br>'.$thumb['album_name'].'<br>'.$thumb['id'].'</a></td>';
}
echo "</tr></table>";
}
?>
The code for getting the passed variable is as follows:
<?php
include("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
$db = mysqli_select_db($conn,dbname);
if (isset($_GET['id'])) {
$album_id = $_GET['id'];
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn,$pic);
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
}
else{
echo "Pictures in the gallery:<br><br>";
while ($result = mysqli_fetch_assoc($picQuery)) {
echo "<img src='".$result['photo_path']."'/>";
}
}
}
?>
Please help as i have spent the last two days trying to get it right.
First, your's code is weak against sql injections:
$album_id = $_GET['id']; // here
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
Use either $album_id = intval($_GET['id']) or prepared statements functionality.
Second, add debug lines to your code, like:
<?php
include("config.php");
if (isset($_GET['id'])) {
$album_id = intval($_GET['id']);
var_dump($album_id); // should print actual passed id
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
var_dump($conn _id); // should print conn resource value
$db = mysqli_select_db($conn, dbname);
var_dump($db); // should print 'true' if db select is ok
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn, $pic);
var_dump($picQuery); // should print query resource value
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
} else {
echo "Pictures in the gallery:<br><br>";
while (($result = mysqli_fetch_assoc($picQuery)) !== false) {
var_dump($result ); // should print fetched assoc array
echo "<img src='".$result['photo_path']."'/>";
}
}
}
Notice $album_id = intval($_GET['id']) and while (($result = mysqli_fetch_assoc($picQuery)) !== false) parts
Then follow link view.php?id=<existing-album-id> and observe debug result. On which step debug output differs from expected - there problem is.

check if MySQL table is empty

I want to check if my table is empty I've tried this "which I think that is the solution"
$test_empty="SELECT *FROM objectif where 1 ";
if(empty($test_empty))
{
echo "I m here";
}
But it seems that it doesn't work.
Depending on how you are connecting to your database (for example, using mysqli):
$db = new mysqli("localhost","username","password","dbname");
$check = $db->query("SELECT COUNT(*) FROM objectif");
if ($check->num_rows == 0 || $check->fetch_field() == 0){
echo "table is empty";
}else{
echo "table is not empty";
}
Currently, your code isn't actually connecting to the database or querying the table - you are essentially just checking if the variable $query is empty (which it never will be, as it contains a string!
Running a query to fetch the number of records and checking that as per the code above is one way to do this.
Use this
$mysqli = new mysqli("localhost","root","","db");
if ($result = $mysqli->query("SELECT * FROM `table` LIMIT 1"))
{
if ($obj = $result->fetch_object())
{
echo "NOT EMPTY";
}
else
{
echo "empty";
}
$result->close();
}
$mysqli->close();
Please try below code :
$test_empty="SELECT * FROM objectif";
$query = mysql_query($test_empty);
if(mysql_affected_rows() > 0)
{
echo "It is Empty";
}

Check if row in table is 'equal' to other row

I have the following code to check if a row exists in MySQL:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT 1 FROM files WHERE id='$code' LIMIT 1");
if (mysql_fetch_row($result)) {
echo 'Exists';
} else {
echo 'Does not exist';
}
}
?>
This works fine. But I need to change it a bit. I have the following fields:
id, title, url, type. When someone uses the code above ^ to check if a row exists, I need a variable to get the url from the same row, so I can redirect the user to there.
Do you have any idea how I can do that?
Thanks in advance! :)
Try this:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT * FROM files WHERE id=" . $code . " LIMIT 1");
if (mysql_num_rows($result) > 0) {
while($rows = mysql_fetch_array($result)) {
echo 'Exists';
$url = $rows['url'];
}
} else {
echo 'Does not exist';
}
}
?>
It is quite simple. I think you don't show any effort to find the solution by yourself.
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT url FROM files WHERE id='$code' LIMIT 1");
if ($result) {
$url = mysql_fetch_row($resultado);
} else {
echo 'Does not exist';
}
}
<?php
$sql_query = "SELECT * FROM test WHERE userid ='$userid'";
$result1 =mysql_query($sql_query);
if(mysql_num_rows($result1)>0){
while($post = mysql_fetch_array($result1))
{
$url = $post['url'];
}
}
?>
If mysql_num_rows($result1)>0 it means row is existed fir the given user id

PDO version of mysql_num_rows($result)==0) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Alternative for mysql_num_rows using PDO
^ I believe it isn't the same question - The other authors code is different to mine, which needed a different answer. I successfully got my answer from this post and marked it as answered. Everything is working fine now (no help from the other 'duplicate' thread.
I want to display a "No Client Found" message if no results are found, Is there a PDO method to the following code?:
$result = mysql_query($sql) or die(mysql_error()."<br />".$sql);
if(mysql_num_rows($result)==0) {
echo "No Client Found";
I tried the following...
<?php
$db = new PDO('mysql:host=localhost;dbname=XXXXXXXXXXXX;charset=utf8','XXXXXXXXXXXX', 'XXXXXXXXXXXX');
$query = $db->query('SELECT * FROM client');
if ($query == FALSE) {
echo "No Clients Found";
}
else
{
foreach($query as $row)
{
<some code here>
}
}
?>
Am I missing something?
I've read: http://php.net/manual/en/pdostatement.rowcount.php but hasn't helped
<?php
$db = new PDO('mysql:host=localhost;dbname=XXXXXXXXXXXX;charset=utf8','XXXXXXXXXXXX', 'XXXXXXXXXXXX');
$query = $db->query('SELECT * FROM client WHERE ID = 10');
if ($query->rowCount() != 1) {
echo "No Clients Found";
}
else
{
foreach($query as $row)
{
<some code here>
}
}
?>
In PDO, rowCount method is used to count the returned results. Your query must select some thing unique, like an email address or username if you want to check for unique existence, else, if you want at least find one row, change the condition to this:
if ($db->rowCount() == 0)
There is a tutorial: PDO for MySQL developers.
PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement in some databases. Documentation The code below uses SELECT COUNT(*) and fetchColumn(). Also prepared statements and try & catch blocks to catch exceptions.
<?php
// Get parameters from URL
$id = $_GET["client"];
try {
$db = new PDO('mysql:host=localhost;dbname=XXXX;charset=utf8', 'XXXX', 'XXXX');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare COUNT statement
$stmt1 = $db->prepare("SELECT COUNT(*) FROM client WHERE client = ?");
// Assign parameters
$stmt1->bindParam(1,$id);
$stmt1->execute();
// Check the number of rows that match the SELECT statement
if($stmt1->fetchColumn() == 0) {
echo "No Clients Found";
}else{
//echo "Clients Found";
// Prepare Real statement
$stmt2 = $db->prepare("SELECT * FROM client WHERE client = ?");
// Assign parameters
$stmt2->bindParam(1,$id);
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
$stmt2->execute();
while($row = $stmt2->fetch()) {
//YOUR CODE HERE FROM
// Title
echo '<div id="portfolio_detail">';
//etc.etc TO
echo '<div><img src="'."/client/".$row[client].'_3.png"/></div>';
echo '</div>';
}//End while
}//End if else
}//End try
catch(PDOException $e) {
echo "I'm sorry I'm afraid you have an Error. ". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", myfile.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
//Close the connection
$db = null;
?>

Categories