Beginner MySQL database search - not getting results - php

I am having my first attempts to a search engine:
I have a database called "global" and a table called "mpl" which contains 11 columns (Named: Customer, Part No, Descripton, Country Of Origin, and several other) with multiple rows for parts.
What i aim to do with the code below - is to get the Description and Country Of Origin displayed for the Part No the user has entered to the search field.
Form:
<form action="search.php" method="post">
<input type="text" name="find" /><br />
<input type="submit" value="Search" /> </form>
And the PHP:
$host = "localhost";
$dbuser = "root";
$dbpass = " ";
$db = "global";
$con = mysql_connect($host, $dbuser, $dbpass);
if(!$con){ die(mysql_error());
}
$select = mysql_select_db($db, $con);
if(!$select){ die(mysql_error());
}
$item = $_REQUEST['find'];
$data = mysql_query("SELECT * FROM mpl WHERE 'Part No' ='".$item."'");
while($row = mysql_fetch_array($data)){
echo $row['Description']. "<br>";
echo $row['Country Of Origin']. "<br><p>";
}
?>
Can someone tell me what am i doing wrong? Once i enter anything to my form 'find' - i get no results. If i run the search using LIKE instead of "=" with no value - it displays a bunch of Descriptions and Country of origin - this means i have connected to my DB correctly. This is driving me nuts..I feel i have messed up the mysql_query() part somehow - but i can't figure out which part.

You are using the wrong characters to escape the Part No column name in your query. Escape them with the backticks (`) and it should be fine.
$data = mysql_query("SELECT * FROM mpl WHERE `Part No` ='".$item."'");
Also, you should validate the user's query to prevent SQL injection.

A lot of people here have already pointed out possible and actual errors in your code, but here's the combined solution. Firstly I converted your code to mysqli which is the correct way of connecting to a mySQL database. The way you were connecting is out of date, and not recommended. Secondly I added some code to stop sql injection. Thirdly, I changed 'Part No' to `Part No``(ignore the second back tick) in your query.
<?php
$mysqli = new mysqli('localhost', 'root', DB_PASSWORD, 'global');
/* check connection */
if ($mysqli->connect_error)
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
/* escape string from sql injection */
$item = $mysqli->real_escape_string($_POST['find']);
/* query database */
$result = $mysqli->query("SELECT * FROM `mpl` WHERE `Part No` = '".$item."'");
while ($col = $result->fetch_array(MYSQLI_ASSOC))
echo '<p>' . $col['Description'] . '<br />' . $col['Country Of Origin'] . '</p>';
$result->close();
/* don't forget to close the connection */
$mysqli->close();
?>

What if you change:
$item = $_REQUEST['find'];
to
$item = $_POST['find'];
Also some function like mysql_select_db() are deprecated and going to be removed. See:
http://php.net/manual/en/function.mysql-select-db.php

Try changing this potion.
$item = $_REQUEST['find']; $data = mysql_query("SELECT * FROM mpl WHERE 'Part No' ='".$item."'");
to this
$item = $_POST['find'];
$data = mysql_query("SELECT * FROM mpl WHERE Part No ='$item'");

do something like this in your request to remove any possible whitespaces and normalize to upper case for select string.
$item = strtoupper(trim($_REQUEST['find']));
And do this in your SQL: to normalize as well.
$data = mysql_query("SELECT * FROM mpl WHERE UPPER(TRIM('Part No')) ='".$item."'");
You are basically not getting an exact match on your where clause

First off, I agree with Quentin; you should be using a database API like PDO or Mysqli. Secondly, it looks like people can search for parts by their part numbers or descriptions. Assuming the part numbers are numeric and the descriptions are strings... check the type of input and run the query accordingly.
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "global";
// Establish a database connection and select one.
// Try using one of the database API's.
// Then compose your sql by checking for the type of input from the form.
// Since your request method is a POST, then just look in the `_POST` superglobal.
$item = $_POST['find'];
if( is_numeric($item) ){
$sql = "SELECT * FROM mpl WHERE 'Part No' = {$item}";
}else{
$sql = "SELECT * FROM mpl WHERE 'Description' LIKE '%{$item}%'";
}
// Then perform the query.

Related

UPDATE to current date (PHP)

im trying to update date on the table. YYYY-MM-DD HH-MM-SS.
There is the code i have.
It takes information from table and after that I want it to set date in that table to current time
<?php
$username = "root";
$password = "sawasq";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$code = $_POST['kodas'];
$code = stripslashes($code);
$sql = mysql_query("SELECT * FROM dviraciai WHERE ID='$code'");
$Pavadinimas = 'Pavadinimas';
$Metai = 'Metai';
$Status = 'Status';
$rows = mysql_fetch_assoc($sql);
echo 'Pavadinimas: ' . $rows[$Pavadinimas] . '<br>';
echo 'Metai: ' . $rows[$Metai] . '<br>';
echo 'Status: ' . $rows[$Status] . '<br>';
$sql2 = mysql_query("UPDATE Dviraciai WHERE ID='$code' SET date=CONCAT(CURDATE(),' ',time(mytime))");
mysql_close();
?>
I get $code from input.
Dviraciai is my table.
I dont get any error. But when i enter my $code it shows the info but doesnt change time in table after I restart phpMyAdmin
Your query is totally wrong, and since you never bother checking for errors and simply ASSUME nothing could ever go wrong...
Update syntax is
UPDATE ... SET ... WHERE...
You have the set/where reversed. And note that restarting phpmyadmin is beyond pointless. It's a MANAGEMENT INTERFACE. It's not the database itself. It's like trying to change the outcome of a tv show by turning your tv on/off.... the show's going to end up broadcasting the same ending no matter what you to do with your TV.
Never assume success with DB operations. Even if your SQL is 100% syntactically perfect (and yours definitely isn't), there's far too many OTHER reasons for a query to fail. Assuming success is, frankly, just plain stupid. Always assume failure, check for failure, and treat success as a pleasant surprise. At bare minimum, have something like this:
$result = mysql_query(...) or die(mysql_error());

Deleting student data in msqli with php

I have just migrated my page from mysql to msqli. Now, deleting data is confusing. Here is my code in Admin_Delete.php
require 'Connect.php';
$id = intval($_GET['id']);
$query = "DELETE * FROM student_information WHERE student_id='$_GET[id]'";
// not using return value, and add some debug info
mysqli_query($query) or die(mysql_error().PHP_EOL.$query);
// let's see if anything actually happened...
$rowsDeleted = mysqli_affected_rows();
if($rowsDeleted == 0) {
error_log("Nothing deleted for this query:".PHP_EOL.$query);
}
echo "<script language='javascript' type='text/javascript'>alert('$rowsDeleted row(s) deleted!')</script>";
echo "<script language='javascript' type='text/javascript'>window.open('Admin_Home.php','_self')</script>";
?>
This is my configuration to fix these.
Connect.php
<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "123456";
$dbname = "student";
$link_id = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link_id));
?>
A couple of problems.
The reference to mysql_error should be mysqli_error($link_id).
The reference to mysqli_query should be mysqli_query($link_id, $query).
The reference to mysqli_affected_rows should be mysqli_affected_rows($link_id)
Also, you've used intval, to get an integer value from $_GET, but you're using reference to $_GET in the SQL text. If you aren't going to use a prepared statement, then you should be using mysqli_real_escape_string function to make potentially "unsafe" values "safe" for inclusion in SQL text.
$sql = " ... WHERE id='" . mysqli_real_escape_string($link_id, $id) . "'";
Syntax for DELETE statement is not correct. Either omit the *
DELETE FROM student_information WHERE ...
Or qualify the * with a table reference, or table alias
DELETE s.* FROM student_information s WHERE ...

Trying to search ID and Display selected information

I have made a search box so that you can enter the product id that you wish to gain the information of. When i input data in the product id box, there are no results returned, anyone know what im doing wrong? I think that 'while ($row = mysql_fetch_array($result)) {' is wrong but not too sure as everything ive tried didn't work.
<div class="searchbox">
<form action="Search.php" method="get">
<fieldset>
<input name="search" id="search" placeholder="Search for a Product" type="text" />
<input id="submit" type="button" />
</fieldset>
</form>
</div>
<div id="content">
<ul>
<?php
// connect to the database
include('base.php');
$search = mysql_real_escape_string($_GET['search']);
$query = "SELECT * FROM Product WHERE ProductID LIKE '%{$search}%'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<li><span class='name'><b>{$row['ProductID']}</b></span></li>";
}
Don't use mysql specific syntax, It's outdated and can get you into real trouble later on, especially if you decide to use sqlite or postgresql.
Use a PDO connection, you can init one like this:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
Then you should make sure that you actually have the variable:
$search = isset($_GET['search']) ? $_GET['search'] : false;
So you can actually skip the database thing if something, somehow, fails.
if(!$search)
{
//.. return some warning error.
}
else
{
// Do what follows.
}
Now you should construct a query that can be used as a prepared query, that is, it accepts prepared statements so that you prepare the query and then you execute an array of variables that are to be put executed into the query, and will avoid sql injection in the meantime:
$query = "SELECT * FROM Product WHERE ProductID LIKE :search;"; // Construct the query, making it accept a prepared variable search.
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(':search' => $search)); // Here you insert the variable, by executing it 'into' the prepared query.
$statement->setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode.
while ($row = $statement->fetch())
{
$productId = $row['ProductID'];
echo "<li class='name><strong>$productId</strong></li>";
}
Oh yes, don't use the b tag, it's outdated. Use strong instead (It's even smarter to apply font-weight: bold; to .name in a separate css file.
Feel free to ask questions if anything is unclear.
remove the {} before and after $search.
should be:
$query = "SELECT * FROM Product WHERE ProductID LIKE '%$search%'";
You can use:
$result = mysql_query($query) or die($query."<br/><br/>".mysql_error());
To confirm that the data is returning.

Mysql Query, comparing values and assigning to PHP variables

I have done a fair bit of research into what i want to do, although i haven't found anything. I am not too sure if i am looking for the right thing :( I am also a little bit new to PHP and MySQL syntax, so please be kind.
I wish to perform the following in this order:
Connect to a database (DONE)
Query for a specific string (I think im done)
From here is gets a bit fuzzy :(
If a match is found for the variable, copy the whole row (I need other variables).
Assign the values from the SQL query to a PHP variables.
From there i will be right to carry on.
I have established the connection to the database with the following:
function connect() {
$dbname = 'database';
$dbuser = 'username';
$dbpass = 'password';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
}
And then calling the function connect();
I then wish to query the database for a particular value, for the sake of this argument i will use a static value. This is what i have:
mysql_select_db(DATABASENAME) or die( "Unable to select database");
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'";
$result=mysql_query($query);
From here i am not too sure how to compare the query result to see if it is a match (something along the lines of mysql rows?).
If there is a match, then i would like to obtain the entire row, and assign each value to a php variable.
I am not asking for you to do it for me, simply i kick in the right direction should be fine!
Hope it explains it enough :)
Thanks for your kind guidance
Ok. You will want to keep the connection to the mysql database somewhere. A common use is $conn.
So you would have
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
Then, either from the URL or Post, or just some variables you have sitting in your php file, you can query the database by putting the variables in the query itself. Also, here you can use $conn so that you have one place to connect to the database, in an include for example, and you won't have to make all of the connection string in each place you need to connect to the DB.
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%" . $varToCompare . "%'";
$result=mysql_query($query,$conn);
Above you are using a like. You may want to just look at doing .. Where column=$var.
Then you can use php to spin through the results into an array (for queries where would get multiple rows).
Where the hell you learned how to use MySQL in PHP ? The mysql_* functions are more then 10 years old and not maintained anymore. Community has already begun to work on deprecating them.
You should be using PDO or MySQLi for that.
// connection to database
$db = new PDO('mysql:host=localhost;dbname=datadump_pwmgr;charset=UTF-8',
'datadump_pwmgr',
'kzddim05xrgl');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// setting up prepared statement for the query
$statement = $db->prepare('SELECT * FROM table WHERE column LIKE :value');
$statement->bindParam(':value', $some_variable, PDO::PARAM_STR, 127);
// executing query and fetching first result
if ( $statement->execute())
{
$data = $statement->fetch(PDO::FETCH_OBJ);
var_dump( $data );
}
This should give you something like what you needed. Though, I would recommend to try this tutorial. And learning more about prepared statements could be useful too.
Also , if you are working with objects, then it is possible to create a single DB connection object , and pass it to multiple other classes to use it:
$pdo = new PDO('sqlite::memory:');
$a = new Foo( $pdo );
$b = new Bar( $pdo, 'something');
This way you pass both objects the same database connection, and you do not need to reinitialize it.
I think you're looking for something like this:
$count = mysql_num_rows($result);
//if there is more then 1 record retrieved from the database
if($count > 0)
{
//Do what ever you want to do here, which I think you want to be
while ($row = mysql_fetch_assoc($result))
{
echo $row["Columnname1"];
echo $row["Columnname2"];
echo $row["Columnname3"];
}
}
else
{
echo "There are no matches for this specific value";
}
You can get the queried data by rows as an associated array using mysql_fetch_array():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_array($data)) !== false)
{
echo "row = $row, name1 = " . $result["name1"] . ", name2 = " . $result["name2"];
$row ++;
}
... or as an objects using mysql_fetch_object():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_object($data)) !== false)
{
echo "row = $row, name1 = $result->name1, name2 = $result->name2";
$row ++;
}
I'm not too sure of what you want, but I can see one probable bug here: you're using LIKE in a way which means =: in order to have LIKE to behave like a like, you need some joker chars :
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'" // This will return all rows where column='VAUL'
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'" // This will return all rows where column='%VAUL%' // This will return any row containing 'VAUL' in column
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE'" // This will return all rows where column='%VAUL' // this will return all rows ending by VAUL. I guess you get it now :)
An to retrieve the actual results:
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'";
$result=mysql_query($query);
while (false !== ($row = mysql_fetch_assoc($result))) {
//here $row is an array containing all the data from your mysql row
}
Try to write the database connection in another page no need to use function and include that page in where ever you need.
ex: require_once 'dbConnect.php';
dbConnect.php consists:
<?php
$dbname = 'datadump_pwmgr';
$dbuser = 'datadump_pwmgr';
$dbpass = 'kzddim05xrgl';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
?>

Display MySQL Database as an array

I have a MySQL database full of user information, like their username, password, email, etc.
I want a PHP script that allows me to pull JUST their username and display it like so:
"username1","username2","username3"
Literally exactly like that, the quotes and all.
EDIT: Sorry for not supplying enough information.
The table is named "users" the field I want to pull off it is "username" I can get it to pull and display all the information, my only problem is imploding it.
OK dude, read the comments
<?php // open a php tag
$dbc = mysql_connect("host", "username", "password"); // connect to database
mysql_select_db("db_name", $dbc) // select the database
$sql = "SELECT `username` FROM `users_table`"; // select only the username field from the table "users_table"
$result = mysql_query($sql); // process the query
$username_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$username_array[] = "\"".$row['username']."\""; // get the username field and add to the array above with surrounding quotes
}
$username_string = implode(",", $username_array); // implode the array to "stick together" all the usernames with a comma inbetween each
echo $username_string; // output the string to the display
?>
I've seen all the other answers, however have you considered using PDO instead of mysql_query functions? It's a much nicer way to work with the database.
Here's what you want to achieve in a few lines of code (using lamba functions):
$dbh = new PDO("mysql:host=localhost;dbname=test", "yourusername", "yourpassword");
$results = $dbh->prepare("SELECT u.username FROM users u");
$results->execute();
$results = $results->fetchAll();
echo implode(", ", array_map(function(&$r) { return $r['username']; }, $results));
Output: Jamie, Bob, Chris
Nice and clean. Also, you should check if you have any results that have been returned and if the query was successful.
Just another approach.
EDIT: I've just realised you're a beginner so my answer may be a bit too advanced. However, i'll leave it for others to see as a solution, and perhaps you might look into using PDO an lamba functions when you learn a bit more. Best of luck.
Let's assume that you have a 'mydb' database and 'users' table in it.
SQL needed:
USE mydb;
SELECT username from users;
Short version:
Wrap it in PHP calls to mysql PHP library
Get result as an array then implode it with comma symbol.
Long version:
First we need to connect to database:
$db = mysql_connect('DATABASE_HOST', 'USER', 'PASSWORD');
if (!$db) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('mydb', $db);
if (!$db_selected) {
die ('Can\'t use mydb: ' . mysql_error());
}
Remember to always check the return values of functions.
Then we query the database:
$result = mysql_query('select username from users', $db);
...and fetch results in flat array (we need only usernames):
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC))
{
$data[] = $row['login'];
}
Then we format the returned data according to your specs:
$string_result = '"'. implode('", "', $data) . '"';
You can do with $string_result anything you want, just close the database connection immediately after use:
mysql_close($db);
Good luck with learning PHP, BTW. ;)
You could using PHP's implode, but it's probably easier just do it in SQL assuming that the list won't be too long:
SELECT GROUP_CONCAT(CONCAT('"', username, '"')) AS usernames
FROM your_table

Categories