Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm creating simple web application using php. And there is basic constant settings in (config.php) like:
define('SITE_NAME', 'Site A');
define('SITE_URL', 'https://example.com');
define('SITE_EMAIL', 'test#example.com');
define('SENDGRID_API', 'G.6786jka9769fhgg45479989hjvh');
And calling this file almost every page. Is it possible to store this value in mysql and it's editable via web interface for admin? If yes, how to do it? So that i don't need to connect to db for everytime using this constant. If i'm not mistaken, some settings from wordpress is using something like this.
For your solution create a table like:
DROP TABLE IF EXISTS `settings`;
CREATE TABLE IF NOT EXISTS `settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`site_option` varchar(200) NOT NULL,
`site_value` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
COMMIT;
Needs 4 files: index.php, db.php, create.php, update.php
db.php
function connect()
{
$dsn = 'mysql:host=localhost;port=3306;dbname=update;';
try{
return new PDO($dsn, 'root', '');
}catch( \Exception $e ){
return $e->getMessage();
}
}
index.php
<?php
session_start();
?>
<htmL>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<title>Test UPDATING records in PHP</title>
</head>
<div>
<?php
if(isset($_SESSION['success'])){
echo $_SESSION['success'];
}elseif(isset($_SESSION['error'])){
echo $_SESSION['error'];
}
//clearing all session values
session_unset();
?>
<h2>Create New Site Option / Setting</h2>
<form action="create.php" method="POST">
Site Option: <input type='text' name='site_option' size='12' value=''>
Site Value: <input type='text' name='site_value' size='12' value=''>
<input type="submit" value="Submit">
</form>
</div>
<?php
require_once('db.php');
$pdo = connect();
if( $pdo instanceof \PDO ){
$sql = "SELECT * FROM settings";
$dbh = $pdo->prepare($sql);
var_dump($dbh);
$dbh->execute();
foreach($dbh as $row){
echo "<div style='padding-bottom:1em;' class='datarow'>";
echo "<input type='text' name='site_option' size='12' value='{$row['site_option']}'>";
echo "<input type='text' name='site_value' size='3' value='{$row['site_value']}'>";
echo "<input type='hidden' name='id' size='3' value='{$row['id']}'>";
echo "<button onClick='updateValues(this);'>Update Option</button>";
echo "</div>";
//define the constant
if (!defined($row['site_option'])) {
define( strtoupper($row['site_option']),$row['site_value']);
}
}
// To see all constants , uncomment if you need to see them for testing
// print_r(get_defined_constants(true));
}else{
//echo $pdo->getMessage();
}
?>
<script type="text/javascript">
function updateValues(obj){
let datarow = $(obj).closest('.datarow');
//("input[name='quantity']").val()
console.log($('input[name="author"]', datarow).val());
$.post( "update.php", { site_option: $('input[name="site_option"]', datarow).val(),
site_value: $('input[name="site_value"]', datarow).val(),
id: $('input[name="id"]', datarow).val()
//id: $(obj).data('parentid')
}
).done(function( data ) {
if( ! $.isEmptyObject( data.error ) ) {
alert( 'error' + data.error);
}else{
//success
alert( 'Success: ' + data.success );
location.reload();
}
});
}
</script>
</htmL>
create.php
session_start();
require_once('db.php');
if(isset($_POST['site_option']) && isset($_POST['site_value'])){
//Todo: do some sort of validation / sanity checking (dont trust user input)
$site_option = $_POST['site_option'];
$site_value = $_POST['site_value'];
$sql = "INSERT INTO settings ( id, site_option, site_value ) VALUES ( NULL, :site_option, :site_value )";
$pdo = connect();
$dbh = $pdo->prepare($sql);
try{
$dbh->execute( [
':site_option' => $site_option,
':site_value' => $site_value
] );
$_SESSION['success'] = 'Successful creation of new record';
header("Location: index.php");
}catch( \Exception $e ){
$_SESSION['error'] = 'Error creating new entry';
//echo json_encode( [ 'error' => $e->getMessage() ] );
}
}
update.php
require_once('db.php');
header('Content-Type: application/json');
if(isset($_POST['id'])){
//Todo: do some sort of validation / sanity checking (dont trust user input)
$sql = "UPDATE settings SET site_option=:site_option, site_value=:site_value WHERE id=:id";
$pdo = connect();
$dbh = $pdo->prepare($sql);
try{
$dbh->execute( [
':site_option' => $_POST['site_option'],
':site_value' => $_POST['site_value'],
':id' => $_POST['id']
] );
echo json_encode( [ 'success' => 'Record updated.' . $_POST['site_option'] ] );
}catch( \Exception $e ){
echo json_encode( ['error' => 'Error updating the record' ]);
//echo json_encode( [ 'error' => $e->getMessage() ] );
}
}
Related
I'm working on a basic database app which uses a sql database to store and retrieve information from as part of the crud operations the creation and reading of data works perfectly fine. However I'm facing issues with updating and deleting the data stored and it never happened before.Is there something I'm doing wrong?
I'm assuming the something that I've done wrong in update may be similar to my issue in delete.
Here's the code for the update part : [Note this is just for a basic demo and so security features aren't important]
<?php
require "config.php";
require "common.php";
if (isset($_POST['submit'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$user =[
"char_id" => $_POST['char_id'],
"char_name" => $_POST['char_name'],
"currency" => $_POST['currency'],
"server_id" => $_POST['server_id'],
"account_id" => $_POST['account_id']
];
$sql = "UPDATE characters
SET
char_name = :char_name,
currency = :currency,
server_id = :server_id,
account_id = :account_id
WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->execute($user);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
if (isset($_GET['char_id'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$char_id = $_GET['char_id'];
$sql = "SELECT * FROM characters WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->bindValue(':char_id', $char_id);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
} else {
echo "Something went wrong!"; //this happens
exit;
}
?>
<?php require "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['char_name']); ?> successfully
updated.</blockquote>
<?php endif; ?>
<h2>Edit a character</h2>
<form method="post">
<?php foreach ($user as $key => $value) : ?>
<label for="<?php echo $key; ?>"><?php echo ucfirst($key); ?>
</label>
<input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'id' ? 'readonly' : null); ?>>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php require "templates/footer.php"; ?>
The problem seems to be that your loop of inputs expects an array variable called $user. The $user comes from a DB query, using inputs from your form, but the actual input values comes from the $user variable which isn't set until the DB query is run!
First I would try keeping the $_GET in your code. Your SELECT query expects $_GET['char_id'] to be set in order to execute. Do that by adding ?char_id=SOME NUMBER HERE to your url and go. The number should be a char_id present in your Database.
Now the DB query gets the $_GET['char_id'] that it needs (since the $_GET method fetches parameters from the URL), and you should get some working inputs from your loop, and be able to update entries in your Database.
I am looking for answers on Stack Overflow and Google, have read about 50 same questions, every time its different, my head is already boiling. I have a simple PHP CRUD application with OOP.
It has a connection to the database (it works, my data is fetched from the database and I could see it at my index.php in Opera/Safari), has 'add' action (it doesn't work - white page), 'edit' action (it doesn't work - white page), 'delete' action (it works).
UPDATE2:
I have changed cli interpreter to 5.6. Now I see some errors (if I add this line to .ini file 'always_populate_raw_post_data' to '-1' errors are disappear, but I see a white page again):
Deprecated: Automatically populating $HTTP_RAW_POST_DATA is .
deprecated and will be removed in a future version. To avoid this
warning set 'always_populate_raw_post_data' to '-1' in php.ini and
use the php://input stream instead. in Unknown on line 0
Warning: Cannot modify header information - headers already sent in
Unknown on line 0
Array ( [type] => 2 [message] => Cannot modify header information -
headers already sent [file] => Unknown [line] => 0 ) Array ( [type]
=> 2 [message] => Cannot modify header information - headers already
sent [file] => Unknown [line] => 0 )
I am using in my project:
PHPSTORM
PHP CLI interpreter 7.2
PHP version 5.6
add.php code:
<html>
<head>
<title>Add Data</title>
</head>
<body>
<?php
include_once("classes/Crud.php");
include_once("classes/Validation.php");
$crud = new Crud();
$validation = new Validation();
if(isset($_POST['Submit'])) {
$name = $crud->escape_string($_POST['name']);
$age = $crud->escape_string($_POST['age']);
$email = $crud->escape_string($_POST['email']);
$msg = $validation->check_empty($_POST, array('name', 'age', 'email'));
$check_age = $validation->is_age_valid($_POST['age']);
$check_email = $validation->is_email_valid($_POST['email']);
if($msg != null) {
echo $msg;
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} elseif (!$check_age) {
echo 'Please provide proper age.';
} elseif (!$check_email) {
echo 'Please provide proper email.';
}
else {
$result = $crud->execute("INSERT INTO users(name,age,email) VALUES('$name','$age','$email')");
echo "<p style='color=green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}?>
</body>
</html>
edit.php
<?php
include_once("classes/Crud.php");
$crud = new Crud();
$id = $crud->escape_string($_GET['id']);
$result = $crud->getData("SELECT * FROM users WHERE id=$id");
foreach ($result as $res) {
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="editaction.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo
$name;?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo
$age;?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo
$email;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo
$_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update">
</td>
</tr>
</table>
</form>
</body>
</html>
editaction.php
<?php
include_once("classes/Crud.php");
include_once("classes/Validation.php");
$crud = new Crud();
$validation = new Validation();
if(isset($_POST['update']))
{
$id = $crud->escape_string($_POST['id']);
$name = $crud->escape_string($_POST['name']);
$age = $crud->escape_string($_POST['age']);
$email = $crud->escape_string($_POST['email']);
$msg = $validation->check_empty($_POST, array('name', 'age', 'email'));
$check_age = $validation->is_age_valid($_POST['age']);
$check_email = $validation->is_email_valid($_POST['email']);
if($msg) {
echo $msg;
echo "<br/><a href='javascript:self.history.back();'>Go
Back</a>";
} elseif (!$check_age) {
echo 'Please provide proper age.';
} elseif (!$check_email) {
echo 'Please provide proper email.';
} else {
$result = $crud->execute("UPDATE users SET
name='$name',age='$age',email='$email' WHERE id=$id");
header("Location: index.php");
}
}
?>
DB SCHEME:
create database test;
use test;
CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(100) NOT NULL,
`age` int(3) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
Crud.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
include_once 'DbConfig.php';
class Crud extends DbConfig
{
public function __construct()
{
parent::__construct();
}
public function getData($query)
{
$result = $this->connection->query($query);
if ($result == false) {
return false;
}
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function execute($query)
{
$result = $this->connection->query($query);
if ($result == false) {
echo 'Error: cannot execute the command';
return false;
} else {
return true;
}
}
public function delete($id, $table)
{
$query = "DELETE FROM $table WHERE id = $id";
$result = $this->connection->query($query);
if ($result == false) {
echo 'Error: cannot delete id ' . $id . ' from table ' . $table;
return false;
} else {
return true;
}
}
public function escape_string($value)
{
return $this->connection->real_escape_string($value);
}
}
?>
The problem was with phpStorm. My app won't work with PHP interpreter running inside phpStorm.
I run my app in Apache2 HTTP server and it works well.
Here i am writing a script which will send three different values to a database using a simple html form.But whenever i submit the form no values are inserted and i get the following error :
what might be the reason for this error.How can i fix this problem.
$server='localhost';
$user='root';
$password='';
$dbname='fruits';
if(isset($_POST['name']) &&isset($_POST['colour']) && isset($_POST['calories'])){
if(!empty($_POST['name']) && !empty($_POST['colour']) && !empty($_POST['calories'])){
$name=$_POST['name'];
$colour=$_POST['colour'];
$calories=$_POST['calories'];
try{
$conn=new PDO('mysql:host=$server,dbname=$dbname,$user,$password');
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt=$conn->prepare("INSERT INTO favfruit(name,colour,calories)
VALUES(:name,:colour,:calories)");
$stmt->execute(array(':name'=>$name,':colour'=>$colour,':calories'=>$calories));
echo 'it was successfully entered to database';
}catch(PDOException $e){
echo 'error : '.$e->getMessage();
}
}
}
HTML form :
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
fruit name :<input type='text' placeholder='fruit name' name='name'></br>
colur :<input type='text' placeholder='fruit colour' name='colour'></br>
calories :<input type='text' placeholder='calories' name='calories'></br>
<input type='submit' value='SUBMIT FORM'>
</form>
Your problem is just a typo. Replace
$conn=new PDO('mysql:host=$server,dbname=$dbname,$user,$password');
by
$conn=new PDO("mysql:host=$server;dbname=$dbname",$user,$password);
require_once($_SERVER['DOCUMENT_ROOT'].'/settings.php');
class db extends pdo{
//variables
public $db = '';
public $config;
public $settings = array(
'host' => SERVER,
'database' => DB,
'username' => USER,
'password' => PASS,
);
public function __construct(){
$this->db = new PDO(
"mysql:host={$this->settings['host']};" .
"dbname={$this->settings['database']};" .
"charset=utf8",
"{$this->settings['username']}",
"{$this->settings['password']}"
);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
Within the settings.php file define the constants for your db connection
then create a new function.
public function InsertFruit() {
if(isset($_POST['name']) &&isset($_POST['colour']) && isset($_POST['calories'])){
if(!empty($_POST['name']) && !empty($_POST['colour']) && !empty($_POST['calories'])){
$name=$_POST['name'];
$colour=$_POST['colour'];
$calories=$_POST['calories'];
try{
$query = <<<SQL
INSERT INTO favfruit(name,colour,calories)
VALUES(:name,:colour,:calories)
SQL;
$resource = $this->db->prepare($query);
$resource->execute(array(
'name' => $_POST['name'],
'colour' => $_POST['colour'],
'calories' => $_POST['calories'],
));
echo $_POST['name'].' entered into database';
$stmt=$conn->prepare("INSERT INTO favfruit(name,colour,calories)
VALUES(:name,:colour,:calories)");
}catch(PDOException $e){
echo 'error : '.$e->getMessage();
}
}
}
}
I know for sure as long as your webserver is up and running that this will work for your connection and that it will ease any other connections you need to use later on. As for your actual form just use a case process to determine what function is ran.
Here is my web service call.
Right now, it's hard coded, but I will stick it behind a User Form.
It's returning an object. How do I use that object with a SQL query? I need to do various Select queries with Products, Manufacturers, in the WHERE criteria I need the contract vehicle ID.
<html>
<head>
<title>Call to Navigator Web Service</title>
</head>
<body>
<?php
$param = array('commodity' => 'LAPTOP', 'placeOfPerformance' => array('location' => 'LSA' , 'lsaStates' => 'NY', 'VA', 'TX', 'oconusStates' => 'ALASKA', 'EMEA'), 'equipmentType' => 'ANY', 'socioEconomicObjective' => 'NONE', 'agencyCode' => '007',);
$client = new SoapClient('https://sso-test.fas.gsa.gov/mpdev/navigator/wsdl');
$results = $client->__soapCall('retrieveContractVehicles', array('parameters' => $param));
print_r($results);
echo ("<br />");
echo ("End of line");
?>
</body>
</html>
class test_object
{
public $contractVehicle = array(
0=>'ITSchedule70',
1=>'ITCommodityProgram'
);
function get_contract()
{
return $this->contractVehicle;
}
}
$var = new test_object(); //let us say this is the part you are getting the result from web service
echo $var->contractVehicle[0]; //this is how you will get ITSchedule70
result:
ITSchedule70
what do you mean by How to insert a query? Do you mean how to save it? I am not sure about the question, but this is how I will insert a query(save to the database)
<?php
define('DB_IP',''); //this is your server's IP/name
define('DB_USERNAME',''); //database username
define('DB_PASSWORD',''); //database password
define('DB_DATABASE',''); //default database to use
class test_object //I do not have the webservice object so I just add this
{
public $contractVehicle = array(
0=>'ITSchedule70',
1=>'ITCommodityProgram'
);
function get_contract()
{
return $this->contractVehicle;
}
}
$var = new test_object(); //lets say this is the variable you will save the result when you invoke the webservice
try
{
//check for connection
$connection = mysqli_connect(DB_IP,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(!$connection)
{
$db_conn_err = "Unable to Connect to Database ERROR: ". mysqli_connect_error($connection);
throw new Exception($db_conn_err);
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
$qry_trans = "INSERT INTO `Product`
(
`id`,
`other_column`,
`ContractVehicle`
)
VALUES
(
1, //use your own value depending on your table requirements
'use your own values',
$var->contractVehicle[0] //ITSchedule70
);";
try
{
$result = mysqli_query($connection, $qry_trans ); //execute the query
if( $result )
{
echo 'Successfully saved!';
}
else
{
$err = 'Unable to insert into table err:'.mysqli_error($connection).'<br>';
throw new Exception($err);
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
UPDATE BASED ON YOUR COMMENT
If the data changes, you might want to know which index in the webservice you want to find,
echo $var->contractVehicle[2]; //will return OtherContractVehicle
you might want to clarify your question or atleast post your sample data so that I can analyse it more.
This question already has answers here:
Get number of rows in SQL-Server with PHP
(2 answers)
Closed 9 years ago.
I know there have been lots of questions about this but I need some specific help, I'm new to sql and php, so sorry for bad coding and poor indenting. What I am trying to do is count the number of rows to a specific column then when I find out how many have this id from this column then I would like it to send this number back to the php page. ATM I am using a like query I don't want this effected.
My layout is 3 pages the index the part choices and the part location, the user inputs a part number into the index page which is then searched against the database which then displays the parts that match or are like the users input on the part choices page. then you click on the part you want and then it takes you to the locations page and showing the closest locations for this part.
What I am trying to do is when the user puts in the part number a query runs and searches the database counting the number of rows that have or are like the input, then outputs the parts like it usually does, but what i want to happen is if there is only one row with that part number i want it to say row = 1 so i can then run an if statement using this value. i have looked into different code and cant quiet find what I'm looking for these are the examples I have found and have tryied to modify for what I need. but i have had no luck.
$query = "SELECT (column) FROM table WHERE column = value";
2.$results = mysql_query($query);
3.$rows = mysql_num_rows($results);
4.echo $rows ;
seperate code below
<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['LastName'].", ".$row['FirstName']."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
i would like the code or query to be within the php that i have, any ideas would be great or examples sorry about poor english many thanks
my code for my page is below:
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=false;">
<script type="text/javascript">
function submit()
{
document.getElementById("start").click(); // Simulates button click
document.submitForm.submit(); // Submits the form without the button
}
</script>
</head>
<body>
<?php
try {
$serverName = "188.64.188.89";
$connectionInfo = array( "Database"=>"tdStoreLocator", "UID"=>"odbcAdmin", "PWD"=>"Midnight1Midnight1");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false )
{
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT TOP 10 [company]
,[partnum]
,[description]
FROM [tdStoreLocator].[odbcadmin].[Part]
WHERE Part.partnum LIKE ? or Part.description LIKE ?";
/* Set parameter values. */
$params = array( "%" . str_replace(" ","%",$_POST["part"] ). "%", "%" . str_replace(" ","%",$_POST["part"] ) . "%");
$i = 0;
$x = true;
/*echo print_r($params, true);*/
$stmt = sqlsrv_query( $conn, $sql, $params );
if( $stmt === false)
{
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
if($x == true)
{
echo"<form id=\"submitForm\" action=\"locations.php\" method=\"post\">";
echo"<input type=\"hidden\" name=\"part\" id=\"3\" value=\"".$row['partnum']."\">";
echo"<input type=\"hidden\" name=\"lon1\" id=\"1\" value=\"".$_POST["lon1"]."\">";
echo"<input type=\"hidden\" name=\"lat1\" id=\"2\" value=\"".$_POST["lat1"]."\">";
echo"<button id=\"start\" type=\"submit\">";
echo "<div style=\"font-family:verdana;font-weight:bold;color:#3083FF;font-size:20px;width:100%;text-align:center;margin:0; padding:0;\">";
echo $row['partnum']."<br/>";
echo "</div>";
echo"<img style=\"width:50%;\"; src=\"productimages/".$row['partnum'].".jpg\" alt=\"Save icon\" onError=\"this.src='productimages/noimage.jpg'\"/>";
echo "<div style=\"font-family:verdana;color:#3083FF;font-size:20px;width:100%;text-align:center;margin:0; padding:0;\">";
echo $row['description'];
echo "</div>";
echo"</button>";
echo"</form>";
}
$i++;
}
sqlsrv_free_stmt( $stmt);
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if($i < 1)
{
echo "<div style=\"font-family:verdana;font-weight:bold;color:#3083FF;font-size:20px;width:100%;text-align:center;\">";
echo "No results found, Please check your spelling of the part number or description.";
echo "</div>";
}
if($i == 1 ) {
echo"<img onload=\"setTimeout(submit(),00001);\" src=\"index.jpg\" onError=\"this.src='productimages/noimage.jpg'\"/>";
}
?>
</body>
</html>
Instead you can use count in query.
$query = "SELECT count(column) FROM table WHERE column = value";
following step count search value in mysql table.
$query = "SELECT * FROM table WHERE fieldName = fieldvalue";
$results = mysql_query($query);
$rows = mysql_num_rows($results);
echo $rows ;