No connection could be made because the target machine actively refused it.
Here is my code.
//$db = 'htdocs\as4.mdb';
//$conn = new COM('ADODB.Connection');
mysql_connect('htdocs\as4.mdb');
mysql_select_db('vendor');
$search = $_POST['search'];
$sql = "SELECT * FROM vendor WHERE vendorName like '%search%' OR
address like '%search%' or
city like '%search%' or
provState like '%search%' or
country like '%search%'";
$result = mysql_query($sql, $conn) or die (mysql_error());
$number = mysql_num_rows($result);
// <h3>$number of results found search for "$search"</h3>
while($row = mysql_fetch_array($result))
{
$vendorName = $row['vendorName'];
$address = $row['address'];
$city = $row['city'];
$provState = $row['provState'];
$country = $row['country'];
}
?>
I'm trying to connect to the database and through a search textbox find a certain keyword and display results with anything that has to do with the key word, for example if I type in Canada I would like to see the results of all the people in Canada. I tried to do it through new COM('ADODB.Connection') as you can see it commented out, but couldn't figure out exactly how.
What if I wanted to use something like this to search the database?
$db = 'htdocs\database\database.mdb';
$sql = "SELECT * FROM Vendor";
//to make this work, you need to add
//extension=php_com_dotnet.dll
//to your php.ini file. Put it with the other
//extension=
//values towards the bottom of the file (around line number 1050)
$conn = new COM('ADODB.Connection');
if(!$conn)
{
echo "Database unreachable";
exit();
}
else
{
echo "Success!<hr />";
try
{
$conn -> Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=$db");
$rs = $conn->Execute($sql);
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "<br />";
exit();
}
while(!$rs->EOF)
{
For($i = 0; $i < ($rs->Fields->Count); $i++)
{
echo $rs->Fields[$i]->Value;
echo " ";
}
echo "<br />";
$rs->MoveNext();
}
Related
I'm trying to make something which will only display the name of the row which has ID 1 but I can't seem to get it to work. I can make it display all the names but I only want it to display the name of user ID 1. This is my current code but it doesn't work.
<a style="font-size: 17px; color: #ff0000;"><?php
$q = "SELECT * FROM `Team` WHERE id =1";
$result=mysqli_query($q);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row != FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo $name;
} else{echo "it's false :(";};
?></a>
It returns:
it's false :(
you may need the while() check on there.
Try something like:
Your database connection:
$servername = "YOUR_HOST";
$username = "YOUR_USER";
$password = "YOUR_PASSWORD";
$dbname = "YOUR_DATABASE";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
echo "There was a slight problem, please contact your webmaster before continuing.";
exit();
}
Then your main file with displaying the row you want:
// create query
$q = "SELECT * FROM Team WHERE id = 1";
// get the records from the database
if ($result = $mysqli->query($q))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// fetch the results
while ($row = $result->fetch_object())
{
$name = $row->name;
echo $name;
}
}
else
{
echo "No results to display!<br><hr><br>";
}
}
else
{ // show an error if there is an issue with the database query
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
mysqli_query requires first parameter should be connection string and second is the query
mysqli_query($link, "your query");
Ref: http://php.net/manual/en/mysqli.query.php
You need to add the Connection-Parameter!
$result=mysqli_query($db, $q);
instead of
$result=mysqli_query($q);
i am trying to get this output from a database of countries. i had use the mysqli_fetch_object() function but it does not work with me
"countries":[{"countryname":"India","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/india.png","language":"Hindi","capital":"New Delhi","currency":{"code":"INR","currencyname":"Rupee"}},{"countryname":"Pakistan","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/pakistan.png","language":"Urdu","capital":"Islamabad","currency":{"code":"PKR","currencyname":"Pakistani Rupee"}}]}
and i am use this php script
<?php
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
{
die ("Erro in connection" . mysqli_connect_error);
}
else{ $encode = array();
$sql="select * from country ";
$res=mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
//$temp_array[]=$row;
$encode=$row;
}
//echo json_encode($temp_array);
echo json_encode($encode);
}
else
{
echo " 0 Rows";
}
}
?>
if anybody can help me ?
Your code should be something like below;
<?PHP
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
die ("Error in connection" . mysqli_connect_error);
else{
$encode = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
$encode[]=$row;
}
}
echo json_encode($encode);
}
?>
You do not need to write down 0 rows because you are returning a json object which has an array so when you check result.length it tells you the row count.
As an advice you may use something like below;
<?php
require 'config.php';
$con = mysqli_connect($servername,$username,$password,$db);
$resultArray = array();
$resultArray["error"] = true; //That will tell your javascript client if any error exits.
$resultArray["errorMessage"] = ""; //We will set this value if any error exits;
if(!$con)
{
$resultArray["error"] = true;
$resultArray["errorMessage"] = "Error in connection" . mysqli_connect_error();
}
else{
$resultArray["error"] = false;
$itemCollection = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
while($row = mysqli_fetch_object($res))
$itemCollection[]=$row;
$resultArray["itemCollection"] = $itemCollection;
}
echo json_encode($resultArray);
?>
In my sample you are going to get a json result something like below;
{"error":true,"errorMessage":"ErrorMessageIfExists","itemCollection":[yourObject,yourObject]}
Hope this helps you.
I'm new to php n I'm trying to make a phone to timezone converter.
I'm getting the error undefined variable '$result' on line 49
How do I resolve it.
Also if you can find out any other mistakes I've made
Please chck for errors I'm making
Phone number:
<button type="submit" name="submit" action="submit">
Submit
</button>
</form>
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$ccode=$_POST["phone"];
// Create connection
$db = new mysqli($servername, $username, $password);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$pattern = '/^\(?[\d]{1,4}\)?( |-)?/';
if(preg_match($pattern, $ccode, $matches))
{
$code = $matches[0];
} else $code = substr($ccode, 0, 4);
$q = "SELECT nicename FROM country.country WHERE phonecode=$code";
if($query = $db->query($q))
{
$record = $query->fetch_assoc();
} else echo "<br/>NO RECORD";
echo '<pre>';print_r($record);
if (empty($_POST["phone"]))
{
echo "<p>Please write a Phone Number!</p>";
}
$abb = "SELECT zone_id FROM zone INNER JOIN country on country.country_code = zone.country_code
WHERE country.country_name = " . $record['nicename'];
if($query = $db->query($abb))
{
$result = $query->fetch_assoc();
} else echo "<br/>NO RECORD";
echo '<pre>';print_r($result);
?>
</body>
Thanks for the help!
I believe this way it will works. I'm not sure about $code, if he contains the right information, you can check that by echo'ing the $code.
if(preg_match($pattern, $ccode, $matches))
{
$code = $matches[0];
} else { $code = substr($ccode, 0, 4); }
$q = "SELECT nicename FROM country WHERE phonecode=$code";
if($query = $db->query($q))
{
$record = $query->fetch_assoc();
echo '<pre>';
print_r($record);
} else { echo "<br/>NO RECORD"; }
$abb = "SELECT zone_id FROM zone INNER JOIN country on country.country_code = zone.country_code
WHERE country.country_name = '" . $record['nicename'] . "'";
if($query = $db->query($abb))
{
$result = $query->fetch_assoc();
echo '<pre>';
print_r($result);
//Here $result will exist!
} else { echo "<br/>NO RECORD"; }
// You had your $result here, and here, the result may not exist,
// depending if the query succeeded or not.
// Same counts for the query above.
There were 2 problems as far as I can tell.
1 was that you tried to print $record, while $record may not have existed, and the same counts for $result.
2 was the zone-query, if you check if a column/field equals a certain string, then make sure the string has quotes around itself. So country_name='something'. You didn't have these quotes around $record['nicename'], so whatever came out of $record['nicename'], he thought it was a column/field, but not a value to check upon.
i'm still new to PDO stuff
i'm writing a pdo pagination but my problem is, its not outputting the data
it just output blank white page
PHP CODE
include "config.php";
if(isset($_POST['checkin'])){
$country = $_POST['country'];
$city = $_POST['city'];
$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];
$sql = $dbo->prepare("SELECT COUNT(id) FROM hotels");
if(!$sql->execute()){
echo "No Count";
}else {
$fetchrows = $sql->fetch();
$rows = $fetchrows[0];
$page_rows = 5;
$last = ceil($rows/$page_rows);
if($last < 1){
$last = 1;
}
$page_num = 1;
if(isset($_GET['pn'])){
$page_num = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
$limit = ($page_num - 1) * $page_rows;
$sql = $dbo->prepare("SELECT * FROM hotels DESC WHERE h_country='$country' LIMIT $limit");
echo "<h3>Total hotels found: $rows</h3>";
echo "Page <b>$page_num</b> of <b>$last</b>";
$hotels = $sql->fetchAll(PDO::FETCH_OBJ);
foreach($hotels as $hotel){
echo $hotel->h_title;
}
}
}
i normally do while statement for pagination in a normal query, so i tried doing the same thing but in PDO, but it didn't work.
i dunno what's the problem. It would be great if you can point out my mistake.
Thanks
Here's my PDO Connection & Mysql, i copied the PDO connection code from a website.
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "test";
$dbserver = mysql_connect($dbhost,$dbuser,$dbpass);
if(!$dbserver) die ("Failed to Connect:" . mysql_error());
mysql_select_db($dbname) or die ("Unable to select the database");
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
I'm not sure how the errors work
You are missing execute() in your second query.
$sql = $dbo->prepare("SELECT * FROM hotels DESC WHERE h_country='$country' LIMI$limit");
// add this
$sql->execute();
echo "<h3>Total hotels found: $rows</h3>";
echo "Page <b>$page_num</b> of <b>$last</b>";
$hotels = $sql->fetchAll(PDO::FETCH_OBJ);
i still dunno what's the problem.
i went to write a code that outputs all data,literally all NO LIMITS.
and it work so i copied the code and paste it to the code above to see if it works and it did
WORKING CODE:
$stmt = $dbo->prepare("SELECT * FROM hotels WHERE h_country='Malaysia' LIMIT 5");
$stmt->bindParam(':country', $country);
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
if(!$stmt->execute()){
echo "\nPDO::errorInfo():\n";
print_r($dbo->errorInfo());
}else {
echo "<h3>Total hotels found: $rows</h3>";
echo "Page <b>$page_num</b> of <b>$last</b>";
$hotels = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach($hotels as $hotel){
echo "<h3>$hotel->h_title</h3>";
}
}
i think maybe (just maybe) its the fault the (DESC)
and i finally i know how to use while statements in PDO(was really easy but i didn't know :P)
Thanks for the tips
ORIGINAL CODE:
$sql = $dbo->prepare("SELECT * FROM hotels DESC WHERE h_country='$country' LIMIT $limit");
echo "<h3>Total hotels found: $rows</h3>";
echo "Page <b>$page_num</b> of <b>$last</b>";
$hotels = $sql->fetchAll(PDO::FETCH_OBJ);
foreach($hotels as $hotel){
echo $hotel->h_title;
}
}
This is my code to pull information from my sql database and then I want to delete the .txt files in each directory, but I can't seem to figure out why it won't delete the files.
<?php
session_start();
$user = $_SESSION['SESS_USERNAME'];
$id = array();
$id = $_POST['selected'];
//Include database connection details
require_once('config_order.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if (!$db) {
die("Unable to select database");
}
//Create query
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'");
// display query results
while ($row = mysql_fetch_array($query)) {
$c_name = $row['clientname'];
$sitestreet = $row['sitestreet'];
$inspector = $row['inspector'];
}
mysql_close($link);
$client_name = str_replace(" ", "_", $c_name);
$site_street = str_replace(" ", "_", $sitestreet);
$client_name = "{$client_name}.txt";
$site_street = "{$site_street}.txt";
$client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
$inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";
if (unlink($client_path . "/" . $client_name)) {
echo 'File Deleted';
} else {
echo 'File could not be deleted';
}
?>
I think this is because your while loop is overwriting the $c_name, $sitestreet and $inspector variables. This means you will only ever delete the last file.
Is this what you were trying to do? (Edited Again...)
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` IN (".mysql_real_escape_string(implode(',',$id)).")");
while ($row = mysql_fetch_array($query)) {
$inspector = $row['inspector'];
$client_name = str_replace(" ", "_", $row['clientname']).'.txt';
$site_street = str_replace(" ", "_", $row['sitestreet']).'.txt';
$client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
$inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";
if (!file_exists($client_path.'/'.$client_name)) {
echo "File $client_path/$client_name does not exist!\n";
} else echo (unlink($client_path.'/'.$client_name)) ? "File $client_path/$client_name was deleted\n" : "File $client_path/$client_name could not be deleted\n";
}
mysql_close($link);
Try some extra debugging:
$realpath = $client_path . '/' . $client_name;
if (file_exists($realpath)) {
if (is_writable($realpath)) {
if (unlink($realpath)) {
echo "$realpath deleted";
} else {
echo "Unable to delete $realpath";
}
} else {
echo "$realpath is not writable";
}
} else {
echo "$realpath does not exist";
}
On first glance, this is a problem, if $_POST['selected'] is not an array:
$id = array();
$id = $_POST['selected'];
...
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'");
You are instantiating $id as an empty array, then overwriting it with $_POST['selected'], so $id[0] is the first character of the string $id.
For example, if $_POST['selected'] is 12345:
"SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'"
is equivalent to:
"SELECT * FROM `PropertyInfo` WHERE `order_number` = '1'"
Either don't try to access it with an index or do $id[] = $_POST['selected']; to add the element onto the $id array instead.
Whether that is an array or not, you do need to either sanitize that input before you insert it into the query or use prepared statements, though!