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.
Related
I've tried to debug this times without success. Here is what I've tried so far
<?php
$cid= (string)$_GET['cid'];//I passed this from another page using get method
echo $cid; //My code works up to this point
$record = mysql_query("select * from questions where QType = '$cid'");
$array = array();
while($row = mysql_fetch_assoc($record))
{
$array[] = $row;
}
for($var = 0; $var<count($array);$var++)
{
echo $array[$var]['Question'].'<br>';
}
?>
This code will work and is a bit safer
<?php
//Connection part
$servername = "server_adress"; //It can be localhost or 127.0.0.1 or some other IP
$username = "XXXXXX"; //Username for DB
$password = "YYYYYY"; //Password for that user
$database = "ZZZZZZ"; //DB name you are connecting to
//Create a new connection
$conn_to_db = new mysqli($servername, $username, $password,$database);
// Check connection
if ($conn_to_db -> connect_error) {
die("Connection failed: " . $conn_to_db ->connect_error);
}
//Finished connection part
$cid = mysqli_real_escape_string($conn_to_db, $_GET['cid']); //Escapes special characters in a string for use in an SQL statement
$array = array();
if($stmt = $conn_to_db -> ("SELECT * FROM questions WHERE QType = ?")) {
$stmt -> bind_param("s", $cid);
$stmt -> execute();
$stmt -> bind_result($question_from_db); //Here you can put all variables you are fetching from DB
while($stmt -> fetch()){
//Iterate over rows - put your code here to fetch everything you need from DB and put in array
$array[] = array('question' => $question_from_db);
}
$stmt -> close();
}
}
//you can iterate over rows like this
foreach($array as $key => $value) {
echo $value['question'];
}
?>
Couple of things to keep in mind:
it's a good practice to avoid * (selecting everything from DB) and
put only columns you need from DB
use prepared statement which is a safer way and protects you from SQL injection
MySQL is depreciated so try to avoid it (use mysqli or PDO)
The code above you need to adjust to your needs! It will not work as copy/paste. Put your DB connection and select columns from DB you need and add variables which you fetch from DB
Keep in mind there are more ways to do this, and someone will probably give another solution.
if you are not on a production server, it's good to have some error reporting to see the errors that are happening
<?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.
To begin with, I am a novice when it comes to PHP and MySQL.
I have a MySQL table called levels that contains two columns: level_id and mapData. Some time ago, I wrote a piece of code using mysql_connect that takes user inputted level_id and fetches the corresponding mapData from the table, and the code works as intended. See below:
<?php
$mysql_host = 'localhost';
$mysql_user = 'username';
$mysql_password = "password";
$mysql_database = 'database';
if (!mysql_connect($mysql_host,$mysql_user,$mysql_password)||!mysql_select_db($mysql_database)){
die('Connection failed');
}
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = mysql_query($query)){
if($query_result = mysql_result($query_run,0,$field)){
return $query_result;
}
}
}
$user_input = mysql_real_escape_string(base64_decode($_GET["level_id"]));
$sql = "SELECT level_id FROM levels WHERE level_id='$user_input'";
$result = mysql_query($sql);
if(mysql_num_rows($result) >0){
$mapData = get_map_data($user_input,'mapData');
print $mapData;
}else{
echo "0";
}
?>
In the case that the user inputs a level_id that does not exist in the database, instead of mapData, he will receive 0. Everything works! I, however, read that mysql_connect is deprecated as of PHP 5.5 and decided to switch from using it in my file to using mysqli:
$conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
After changing to mysqli, my get_map_data function has stopped working. I have made certain that the mysqli connection works, but I am simply hitting my head against the wall in making my function work using it. How do I fix my get_map_data function so that it functions again using mysqli?
You can't mix mysqli and mysql_ functions. Furthermore, your mysqli initialization is creating an object, not a resource. Lastly, there is no mysqli_result() function, so therefore we need to emulate what you're trying to do. You wanted the first row 0 and then wanted a specific $field. Below should be what you want.
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = $mysqli->query($query)){
//no mysqli->result() function, so we need to seek to the row.
$query_run->data_seek(0);
if($query_result = $query_run->fetch_assoc()){
return $query_result[$field];
}
}
}
your get_map_data function currently has query running using mysql_query you have to change that to mysqli_query in order to execute:
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = mysqli_query($conn,$query)){
if($query_result = mysqli_result($query_run,0,$field)){
return $query_result;
}
}
}
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.
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");
?>