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;
}
}
Related
I cannot get my Mysqli queries to both work. If I comment out one function in my html, the other function is properly executed and vice versa.
function all_posts() {
require_once 'database.inc.php';
$mysqli = mysqli_connect($host, $username, $password, $database);
$query = mysqli_query($mysqli, "SELECT variable_name, post_name, post_date, post_display FROM blog_posts ORDER BY id DESC LIMIT 5");
if (!$query)
echo mysqli_error();
while ($results = mysqli_fetch_assoc($query)) {
$post_name = $results['post_name'];
$post_date = $results['post_date'];
$post_display = $results['post_display'];
$variable_name = $results['variable_name'];
echo "<a href='posts.php?post={$variable_name}'>";
echo "<div class='entry'>";
echo "<div class='entry_header'>";
echo "<h2>{$post_name}</h2>";
echo "<h3>{$post_date}</h3>";
echo "</div>";
echo "<p>{$post_display}</p>";
echo "</div>";
echo "</a>";
}
mysqli_free_result();
}
function all_sidebar_posts() {
require_once 'database.inc.php';
$mysqli = mysqli_connect($host, $username, $password, $database);
$query = mysqli_query($mysqli, "SELECT variable_name, post_name FROM blog_posts ORDER BY id DESC LIMIT 5");
while ($results = mysqli_fetch_assoc($query)) {
$post_name = $results['post_name'];
$variable_name = $results['variable_name'];
echo "<li><a href='posts.php?post=$variable_name'>$post_name</a></li>";
}
mysqli_free_result();
}
Here is the html that I am outputting to.
<ul>
<?php all_sidebar_posts(); ?>
</ul>
</div>
<div class="content_container">
<?php all_posts(); ?>
</div>
I have tried using mysqli_data_seek(); but haven't had luck. Perhaps I am not using it right? I have browsed many questions and found similar ones but I have tried them all to no avail. I am new to programming so I may be overlooking something basic. Thank you all for the help!
You are doing it wrong way.
Never mix your data manipulation code with presentation code.
First, get the posts into array:
require_once 'database.inc.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect($host, $username, $password, $database);
$sql = "SELECT variable_name, post_name, post_date, post_display
FROM blog_posts ORDER BY id DESC LIMIT 5"
$result = mysqli_query($mysqli, $sql);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
and then use this $data array to display posts any times you need, simply using foreach()
http://www.php.net/manual/en/mysqli-result.data-seek.php
Consult the manual for the usage of data_seek();
Take this example:
$Query = "SELECT * FROM Users WHERE ID='1'";
$TheQuery -> $MySQLi->query($Query);
$Results = $TheQuery->fetch_array(MYSQLI_ASSOC);
$TheQuery->data_seek(0); // Lets you re-use the query
$Count = $TheQuery->num_rows; // Gets the count
so in your case:
You should perform the procedure method:
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($result = mysqli_query($link, $query)) {
/* fetch row */
$row = mysqli_fetch_row($result);
printf ("City: %s Countrycode: %s\n", $row[0], $row[1]);
mysqli_data_seek($result, 0);
$row_cnt = mysqli_num_rows($result);
/* free result set*/
mysqli_free_result($result);
}
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.
So I got a nifty little bit of code set to run along and find me information when I give it a certain KittenID but its not working at all, I am sad. And oh so tired, Can anyone tell me where I have gone wrong? and yes I do have:
<?php
date_default_timezone_set('America/New_York');
//If statements:
//find:
date_default_timezone_set('America/New_York');
if(isset($_POST['Find']))
{
$connection = mysql_connect("ocelot.aul.fiu.edu","userName","password");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{
//select a database
$dbName="spr15_xgotz001";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)
while($row = mysql_fetch_array($result))
{
$Name = $row['Name'];
$KittenID = $row['KittenID'];
$KittenAge = $row['KittenAge'];
$Email = $row['Email'];
$Comments = $row['Comments'];
$Gender = $row['Gender'];
$Personality = $row['Personality'];
$Activity = $row['Activity'];
echo $row['Comments'];
}
}
}
mysql_close($connection);
}
?>
Use
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = " .$_POST['KittenID']);
instead of
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)
Note: Please use mysqli_ for your future projects
You need to privide more context. How are you setting the $_GET['id'].. is it in fact being stored as $_GET['KittenID'] (e.g. https://yoursite.com?view&KittenID=1). If so...
You can set a variable and declare the 'KittenID'
$kittenid = $_POST['KittenID'];
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = $kittenid");
I suggest providing more context. What error are you getting? What do your parameters look like?
Use
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = " .$_SERVER['KittenID']);
instead of
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)
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();
}
I have been trying to convert a php page to mysqli, and have encoutnered some problems. Given the code below, and the way which I have ordered things to work, I would like to know what the better way is using mysqli methods.
Is there an mysqli alternative to mysql_num_rows or is a different method of calculating the number of rows required?
How would I do the following using mysqli?:
$data = mysql_query($countQuery) or die(mysql_error());
$rowcount = mysql_num_rows($data);
What is an alternative for mysql_fetch_assoc? I feel that I should not be using the current rows method I am using, even if there is a replacement function, so what would be the correct approach?
I apologize for these questions, but I have not been able to determine the answers myself so far.
<?php
$con = mysqli_connect("localhost", "user", "", "ebay");
if (!$con) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
}
$con->query("SET NAMES 'utf8'");
$cmd = "word";
//normally retrieved from GET
if($cmd=="deleterec") {
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
}
}
$table = 'AUCTIONS';
$brand = "test";
$countQuery = "SELECT ARTICLE_NO FROM ? WHERE upper(ARTICLE_NAME) LIKE '% ? %'";
if ($numRecords = $con->prepare($countQuery)) {
$numRecords->bind_param("ss", $table, $brand);
$numRecords->execute();
$data = $con->query($countQuery) or die(print_r($con->error));
$rowcount = mysql_num_rows($data);
$rows = getRowsByArticleSearch($query, $table, $max);
$last = ceil($rowcount/$page_rows);
}
$self = htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'utf-8');
foreach ($rows as $row) // print table rows {
echo '<tr>' . "\n";
echo '<td>'.$row['USERNAME'].'</td>' . "\n";
// repeated for each column
}
function getRowsByArticleSearch($searchString, $table, $max) {
global $con;
$recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM ? WHERE upper(ARTICLE_NAME) LIKE '%?%' ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max;
if ($getRecords = $con->prepare($recordsQuery)) {
$getRecords->bind_param("ss", $searchString, $table);
$getRecords->execute();
$getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate);
while ($getRecords->fetch()) {
$result = $con->query($recordsQuery);
$rows = array();
while($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
}
}
I usually use this directly after my execute:
$query->execute();
// store the result first
$query->store_result();
$rows = $query->num_rows;
Actually, to answer the first question:
$data = mysql_query($countQuery) or die(mysql_error());
$rowcount = mysql_num_rows($data);
If you want to do this using mysqli, mysqli_num_rows works just fine. The only difference is, remember to put the connection parameter in the query.
$data = mysqli_query($dbc,$countQuery) or die(mysql_error());
I've rewritten your code sample with the correct property / function calls to fix the two issues that you mention in the question:
<?php
$con = mysqli::connect("localhost", "user", "", "ebay");
if (!$con) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
}
$con->query("SET NAMES 'utf8'");
$cmd = "word";
//normally retrieved from GET
if($cmd=="deleterec") {
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
}
}
$table = 'AUCTIONS';
$brand = "test";
$countQuery = "SELECT ARTICLE_NO FROM ? WHERE upper(ARTICLE_NAME) LIKE '% ? %'";
if ($numRecords = $con->prepare($countQuery)) {
$numRecords->bind_param("ss", $table, $brand);
$numRecords->execute();
$data = $con->query($countQuery) or die(print_r($con->error));
// Here is the property that you can reference to determine the affected rows from the previous query. -- gabriel
$rowcount = $data->num_rows;
$rows = getRowsByArticleSearch($query, $table, $max);
$last = ceil($rowcount/$page_rows);
}
$self = htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'utf-8');
foreach ($rows as $row) // print table rows {
echo '<tr>' . "\n";
echo '<td>'.$row['USERNAME'].'</td>' . "\n";
// repeated for each column
}
function getRowsByArticleSearch($searchString, $table, $max) {
//global $con; Globals are BAD!! Please don't use.
$con = mysqli::connet("localhost", "user", "", "ebay");
$recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM ? WHERE upper(ARTICLE_NAME) LIKE '%?%' ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max;
if ($getRecords = $con->prepare($recordsQuery)) {
$getRecords->bind_param("ss", $searchString, $table);
$getRecords->execute();
$getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate);
while ($getRecords->fetch()) {
$result = $con->query($recordsQuery);
$rows = array();
// Notice the adjusted function call to retrieve the associate array for each record within the result set. -- gabriel
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
}
}
However, I would like to add that dusoft was correct in the assessment that MySQLi is buggy and is known to create issues. It is for this reason that we had to switch from MySQLi to PDO (which is native to PHP as of at least 5.1) and we haven't had any problems since. I would strongly recommend that you look at PDO or perhaps one of the Pear libraries to actually provide your database connection interface.
You can use:
$data->num_rows();
$data->fetch_assoc();
You can check out the docs for more info num_rows and fetch_assoc.