simple php - Mysql search not working properly - php

I have this code:
<?php
// Make a MySQL Connection
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."' OR LNAME='".$_POST['clientsearch']."' OR MAIL='".$_POST['clientsearch']."' OR TEL='".$_POST['clientsearch']."'"")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
echo "FName: ".$row['FNAME'];
echo "LNAME: ".$row['LNAME'];
echo "FName: ".$row['MAIL'];
echo "LNAME: ".$row['TEL'];
?>
The goal is to search my mysql database to find the result of $_POST['clientsearch'] in one of the fields and return the lines that have that word in it (it is always 1 word)
If I use this:
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."'"")
it seems to work. but it only searches in the FNAME column, not all of them. Also I only get the first result back. not all.
I'm starting php/mysql so I'm a little lost and don't know all functions yet. Could someone explain how I could fix my code up?
Thanks a lot for your help :)

For starters, you'll need to loop through each row in your result set if you're expecting more than 1 row. I illustrate how to do this with your original code.
<?php
// Make a MySQL Connection
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."' OR LNAME='".$_POST['clientsearch']."' OR MAIL='".$_POST['clientsearch']."' OR TEL='".$_POST['clientsearch']."'"")
or die(mysql_error());
// Print out the contents of the entry for each row in result
while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
echo "FName: ".$row['FNAME'];
echo "LNAME: ".$row['LNAME'];
echo "FName: ".$row['MAIL'];
echo "LNAME: ".$row['TEL'];
}
?>
Take a look in the PHP documentation on mysql_real_escape_string for starters on the injection stuff.
Also, as others stated you may be looking for the LIKE instead of = SQL syntax. Also, look into the % wild card for LIKE.

Not an answer to the question, but hopefully helpful. Try writing code like this:
$cs = mysql_escape_string($_POST['clientsearch']);
$result = mysql_query("
SELECT
*
FROM clients
WHERE
FNAME='$cs'
OR LNAME='$cs'
OR MAIL='$cs'
OR TEL='$cs'
");
Exactly how you indent is up to you. This approach helps a great deal with readability, and hence also debugging :)

Related

How to Remove JSON Object ID in php json encode function while using JSON_FORCE_OBJECT Param

Here is my PHP Code which fetches the data from DATABASE and shows as JSON Encode.
<?php
// Initialize variable for database credentials
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'sfm';
//Create database connection
$dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
//Check connection was successful
if ($dblink->connect_errno) {
printf("Failed to connect to database");
exit();
}
//Fetch 3 rows from actor table
$result = $dblink->query("SELECT quote, author FROM quote ORDER BY RAND() LIMIT 1");
//Initialize array variable
$dbdata = array();
//Fetch into associative array
while ( $row = $result->fetch_assoc()) {
$dbdata[]=$row;
}
echo json_encode($dbdata, JSON_FORCE_OBJECT);
?>
And Here is the Output I'm getting as JSON.
I Need my JSON Output Like this..
Help me.. Thanks in advance
As you are expecting just one row, you can ditch the loop and just fetch the first record, then encode just this row rather than an array of 1 row...
$row = $result->fetch_assoc();
echo json_encode($row, JSON_FORCE_OBJECT);
Not sure where the id comes from in the result, this may be just a case of adding it to the SQL select.

Need to Update the data from mysql

<?php
if(isset($_POST['Search']))
{
$num = $_POST['num'];
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'vasuki';
mysql_select_db($dbname);
$Result = mysql_query("SELECT id, name, age FROM details WHERE id = '$num'");
while($row = mysql_fetch_array($Result)) {
$name = $row['name'] ;
$age = $row['age'];
echo "<div style='top: 273px;
margin-left: 60px;
position: absolute;left: 30px;'>
<table border='1'><tr><th>Name</th>
<th> Age </th></tr>
<tr><td>".$name."</td>
<td>".$age."</td>
<td>Edit</td></tr>
</table></div>";
}
I will explain the concept first :
In first page I insert the person details. and In second page in need to update the details. The above program is for my second page. To update I am searching data using the name and age. If I get the particular person data I need to click Edit and It should go to my 1st page and I need to Update the data.
I completed my html codes. I need to know php code to connect SQL.
Can anyone help on this ?
If you want to redirect to another page, in form you need to add action="otherpage.php" and in that other file you need to write something like:
if (!empty($_GET['newValue']) {
mysql_query("update details set name='".$_GET['name']."', age='".$_GET['age']."' WHERE id=".$_GET['id']."");
header("location: index.php");
exit;
}
This is approximate approach and there a few things you should change like mysql to mysqli or PDO (because deprecated) with prepared statements and escape all inputs.

SQL query and PHP

I have following code.
<?php
$server = „host databaze“;
$dbuser = „jmeno uzivatele“;
$dbpass = „heslo uzivatele“;
$dbname = „jmeno databaze“;
mysql_connect($server, $dbuser, $dbpass);
mysql_select_db($dbname);
$result = mysql_query(„SELECT jméno FROM nazevtabulky WHERE id=3“);
echo $result;
?>
there is syntax error on line with mysql_query(„SELECT jméno FROM nazevtabulky WHERE id=3“);
I cant solve problem but I think it is not working because mysql_query(„SELECT jméno FROM nazevtabulky WHERE id=3“); not returns string.. Pls help
the problem appears to be in either:
Czech-style quotations - you should use "", not „“ (may be similar on settings above that)
Czech-style naming - the column is probably called jmeno, not jméno.
Make sure you are using double quotes ("")
$result = mysql_query("SELECT jmeno FROM nazevtabulky WHERE id=3");

How can I get a specific data using SQL select query?

I am trying to make a blog site.For this purpose I need to use a specific data from a specific field from my database table.To do that I wrote these code.
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
echo $img;
?>
My database connection is OK.It should print like this user_img1.jpg. But it prints the whole sql query like select image from news where uid=1. I run this code on phpmyadmin. It works! But it does not work in my php script.How can I do now?
You can not give the query as it is and expect result like in phpadmin.
For this first of all you have to connect to your DB like this
$con = mysqli_connect("localhost","my_user","my_password","my_db");
execute required query like this
$query22 = "select image from news where uid = 1";
$result22 = mysqli_query($con, $query22) or die (mysqli_error());
Get the result and display like this
while($rows = mysqli_fetch_array($result22, MYSQLI_BOTH))
{
echo "<br>Values in db: " . $rows['columnname'];
}
Also i advice you to take a look at these tutorials
http://codular.com/php-mysqli
http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/
Please read some PHP 101 kind of tutorials on how to use PHP.
To get data from DB (in almost any language)
You need to connect to a DB. The connection gets you some sort of resource
You formulate your query (which you seem to have done)
You execute the query against the DB that you connected to (step #1)
You get a result (set)
You iterate over the result set to get the individual result(s); in your case the result set would be just one result (or row).
The examples to do this in PHP are very basic; please do your own lookup on net. This one seems good enough to get you started - http://www.w3schools.com/php/php_mysql_intro.asp
Try this,
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
$result=mysql_query($img);
while($row=mysql_fetch_array($result)){
echo '<img src="your_path_to_image/'.$row['image'].'" /> - '.$row['image'];
}
?>

How does one implement a MySQL database into a webpage?

I am a complete database newbie. So far, I know that I can connect to MySQL using PHP's mysql_connect() command, but apart from that, I really don't see how to take that data and put it onto a web page.
a) are there ways other than mysql_connect()
b) lets say I had a table of data in mysql and all I wanted was for that table (for example: list of names and telephone numbers) to now appear on my web page. I can't for the life of me find a tutorial for this.
<?
$database_name = "dbname";
$mysql_host = "localhost"; //almost always 'localhost'
$database_user = "dbuser";
$database_pwd = "dbpass";
$dbc = mysql_connect($mysql_host, $database_user, $database_pwd);
if(!$dbc)
{
die("We are currently experiencing very heavy traffic to our site, please be patient and try again shortly.");
}
$db = mysql_select_db($database_name);
if(!$db)
{
die("Failed to connect to database - check your database name.");
}
$sql = "SELECT * FROM `table` WHERE `field`= 'value'";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
// code here
// access variables like the following:
echo $row['field'].'<br />';
echo $row['field2'];
}
?>
Check out mysql_fetch_assoc mysql_fetch_array and mysql_fetch_object
This is the very basics, you will want to search for tutorials. There are many about.

Categories