rewrite queries from deprecated mysql_connect to PDO in PHP - php

i am rewriting code mysql_connect deprecated below to work in PDO but cannot get it to work properly. no error is showed. i have tried everything I could. can someone help me
deprecated mysql_connect
<?php include('config.php'); ?>
<?php
if(isset($_POST['page'])):
$paged=$_POST['page'];
$sql="SELECT * FROM `users` where qualify='Po' ORDER BY `uid` desc ";
if($paged>0){
$page_limit=$resultsPerPage*($paged-1);
$pagination_sql=" LIMIT $page_limit, $resultsPerPage";
}
else{
$pagination_sql=" LIMIT 0 , $resultsPerPage";
}
$result=mysql_query($sql.$pagination_sql);
$num_rows = mysql_num_rows($result);
if($num_rows>0){
while($data=mysql_fetch_array($result)){
$userid=$data['uid'];
$fullname=$data['fullname'];
echo "<li><h3>$userid</h3><p>$fullname<p></li>";
}
}
if($num_rows == $resultsPerPage){?>
<li class="loadbutton"><button class="loadmore" data-page="<?php echo $paged+1 ;?>">Load More</button></li>
<?php
}else{
echo "<li class='loadbutton'><h3>No More Data</h3></li>";
}
endif;
?>
convert to PDO
<?php
$resultsPerPage=1;
$db = new PDO (
'mysql:host=localhost;dbname=chat;charset=utf8',
'root', // username
'' // password
);
?>
<?php include('pdo.php'); ?>
<?php
if(isset($_POST['page'])):
$paged=$_POST['page'];
$prefix = "";
//Loadmore configuarion
$resultsPerPage=1;
$sql = $db->prepare("SELECT * FROM users where qualify=:qualify ORDER BY uid desc");
$sql->execute(array(':qualify'=>'po'));
if($paged>0){
$page_limit=$resultsPerPage*($paged-1);
$pagination_sql=" LIMIT $page_limit, $resultsPerPage";
}
else{
$pagination_sql=" LIMIT 0 , $resultsPerPage";
}
$result = $db->prepare($sql.$pagination_sql);
$num_rows = $result->rowCount();
if($num_rows>0){
while ($row = $result->fetch()) {
$userid=htmlentities($row['uid'], ENT_QUOTES, "UTF-8");
$fullname=htmlentities($row['fullname'], ENT_QUOTES, "UTF-8");
echo "<li><h3>$userid</h3><p>$fullname<p></li>";
}
}
if($num_rows == $resultsPerPage){?>
<li class="loadbutton"><button class="loadmore" data-page="<?php echo $paged+1 ;?>">Load More</button></li>
<?php
}else{
echo "<li class='loadbutton'><h3>No More Data</h3></li>";
}
endif;
?>
Thank you so much

Your solution here is to look at http://php.net/manual/en/pdo.setattribute.php and put the following code after your PDO construct:
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
This won't fix your code but it should show you why the error is occuring and you can debug it fully from there.

Related

Hiding links with 0 query value results by php

I have a menu block that contains some links like: Some_link1: 5pcs, Some_link2: 13pcs, Some_link3: 0pcs, Some_link4: 0pcs.
I want to hide link "Some_link" with 0pcs value. I write a code with MySQL query, but it's not working! "Some_link" with 0pcs not hiding but still show 0pcs value.
What i'm doing wrong or what my mistake? I can't understand. Thank you for help.
<?
$resultonline = mysql_query("SELECT count(customers_id) from tbl_customers WHERE active='Y' and saled='N'");
$resultonshafasaled = mysql_query("SELECT count(customers_id) from tbl_customers WHERE shafa='Y' and saled='Y'");
$resultonlinenonactive = mysql_query("SELECT count(customers_id) from tbl_customers WHERE active='N' and saled='N'");
$topmenuNotOnShafa = mysql_result($resultonshafasaled, 0);
$topmenuonline = mysql_result($resultonline, 0);
$topmenuoffline = mysql_result($resultonlinenonactive, 0);
$topmenuonlineText = "Some text : ";
$topmenuOnShafaText = "Some text 2 : ";
?>
<?php if ($topmenuonline!=0): ?><?=$topmenuonlineText;?><?php endif; ?>
<?php if ($topmenuonline!=0): ?><?=$topmenuonline;?>
<?php endif; ?>
<?php if ($topmenuoffline!=0): ?> / <?=$topmenuoffline;?>
<br /><?php endif; ?>
<?php if ($topmenuNotOnShafa!=0): ?>
<span class="saled-warning"><a href="some_link" target="_self" ><?=$topmenuNotOnShafa;?></a></span>
<?php endif; ?>
You can check if the value of the item is 0 or not and print it only if it is not 0:
Example:
<?php
$items='0';
if(isset($items)){
if($items != 0){
echo "<a href='non_zero_item.php'>Item from menu (".$items.")";
} else {
echo "Oh sorry, there are no items!";
}
} else {
echo "items variable is not declared!";
}
?>
In this example you will get the else condition, if you change the variable $items to 1 you will get printed the html code. This is a small test, the variable can be the mysql query result, a manual input like this, etc.
If you dont want to print anything if the value is 0 or not declared, like I understand you want you can do only this:
<?php
$items='1';
if(isset($items)){
if($items != 0){
echo "<a href='non_zero_item.php'>Item from menu (".$items.")";
}
}
?>
For debuging I recommend you to use allways the else condition.
use
mysql_num_rows
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>
http://php.net/manual/en/function.mysql-num-rows.php

Comparing stored data in a column to an existing value

I have a column called favid. I am trying to pull and compare the data in that column to an existing value:
<?php $query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid=$favid");
while ($row = mysql_fetch_assoc($query)) {
echo $row['favid']; };?>
I also have an existing value:
$x
But when I do something like this it doesn't work:
<?php if($row['favid'] == $x){?>
Do this...
<?php } else { ?>
Do nothing...
<?php}?>
I realize the data in the column somehow isn't pulled out. What should be done for this to work?
Try this, I assume you already connected to DB.
<?php
$x = 1;
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid='$favid'") or die(mysql_error());
if (mysql_num_rows($query) > 0)
{
while ($row = mysql_fetch_assoc($query))
{
if ($row["existing_column_name"] == $x)
{
echo "Yes";
} else
{
echo "No";
}
}
} else
{
echo "Nothing was found";
}
?>
<?php
$x = 100500; // integer for example
$CID = mysql_connect("host","user","pass") or die(mysql_error());
mysql_select_db("db_name");
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid='{$favid}'", $CID);
while ($row = mysql_fetch_assoc($query)) {
if (intval($row["some_existing_column_name"])==$x){
print "Is equals!";
} else {
print "Is different!";
}
}
?>
Please be informed that mysql_connect and other functions with the prefix of mysql_ is deprecated and can be removed in the next versions of PHP.

Check if row in table is 'equal' to other row

I have the following code to check if a row exists in MySQL:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT 1 FROM files WHERE id='$code' LIMIT 1");
if (mysql_fetch_row($result)) {
echo 'Exists';
} else {
echo 'Does not exist';
}
}
?>
This works fine. But I need to change it a bit. I have the following fields:
id, title, url, type. When someone uses the code above ^ to check if a row exists, I need a variable to get the url from the same row, so I can redirect the user to there.
Do you have any idea how I can do that?
Thanks in advance! :)
Try this:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT * FROM files WHERE id=" . $code . " LIMIT 1");
if (mysql_num_rows($result) > 0) {
while($rows = mysql_fetch_array($result)) {
echo 'Exists';
$url = $rows['url'];
}
} else {
echo 'Does not exist';
}
}
?>
It is quite simple. I think you don't show any effort to find the solution by yourself.
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT url FROM files WHERE id='$code' LIMIT 1");
if ($result) {
$url = mysql_fetch_row($resultado);
} else {
echo 'Does not exist';
}
}
<?php
$sql_query = "SELECT * FROM test WHERE userid ='$userid'";
$result1 =mysql_query($sql_query);
if(mysql_num_rows($result1)>0){
while($post = mysql_fetch_array($result1))
{
$url = $post['url'];
}
}
?>
If mysql_num_rows($result1)>0 it means row is existed fir the given user id

$mysqli variable works on Server but not on localhost

On my server I include 'config.php' in each function and it works perfectly, however when I do the same on my LOCALHOST the variable $mysqli cannot be found, will the PHP version differ from server to localhost? The paths are both 100% correct.
The error is as follows;
Notice: Undefined variable: mysqli in
C:\Users\PC\Documents\XAMPP\htdocs\php\myfunctions.php on line 20
config.php
$mysqli = new mysqli('localhost', 'userone', 'password', 'iitb');
The connection obviously changes when I use server
myfunctions.php
<?php
class News
{
function getLatest()
{
include 'config.php'; // WHERE TO PUT THIS CANNOT FIND MYSQL
$time = date('Y-m-d G:i:s', strtotime("-1 week"));
$stmt = $mysqli->prepare("SELECT ForumId, ForumTitle, ForumPostText FROM `forum` WHERE `PostDate` > ? ORDER BY PostDate desc LIMIT 5 ");
$stmt->bind_param('s', $time);
$stmt->execute();
$stmt->bind_result($ForumId, $ForumTitle, $ForumPostText);
$stmt->store_result();
if ($stmt->num_rows() == 0) {
echo "<p>No latest article available</p>";
} else {
while ($row = $stmt->fetch()) {
echo '<p class="posttitle">' . $ForumTitle . ' </p>';
echo '<p class="posttext">' . substr($ForumPostText, 0, 93) . ' ...</p>';
}
$stmt->free_result();
}
}
function mostPopular()
{
include 'config.php'; // WHERE TO PUT THIS CANNOT FIND MYSQL
$stmt = $mysqli->prepare("SELECT ForumId, ForumTitle, ForumPostText FROM forum ORDER BY Views DESC LIMIT 5");
$stmt->execute();
$stmt->bind_result($ForumId, $ForumTitle, $ForumPostText);
$stmt->store_result();
if ($stmt->num_rows() == 0) {
echo "<p>No latest article available</p>";
} else {
while ($row = $stmt->fetch()) {
echo '<p class="posttitle">' . $ForumTitle . ' </p>';
echo '<p class="posttext">' . substr($ForumPostText, 0, 93) . ' ...</p>';
}
$stmt->free_result();
}
}
}
Rather than having include 'config.php'; // WHERE TO PUT THIS CANNOT FIND MYSQL in each of your functions, add the $database parameter Eg function mostPopular($database){... and change $mysqli-> to $database->
Then when you call the functions, pass the database through mostPopular($database)
On an unrelated note: You may also find it easier to have the functions return an array rather than echo HTML so that your functions just get the data format it and return values. (It also means you can get away from echoing full HTML.
Here is an example using your mostPopular function
Function:
function mostPopular($databaseName){
$stmt = $mysqli->prepare("SELECT ForumId, ForumTitle, ForumPostText FROM forum ORDER BY Views DESC LIMIT 5");
$stmt->execute();
$stmt->bind_result($ForumId,$ForumTitle,$ForumPostText);
$stmt->store_result();
$returnData = array();
if($stmt->num_rows() > 0){
$i = 0;
while($row = $stmt->fetch()){
$returnData[$i]['ForumId'] = $ForumId;
$returnData[$i]['ForumTitle'] = $ForumTitle;
$returnData[$i]['ForumPostText'] = substr($ForumPostText, 0,93) . ' ...';
++$i;
}
$stmt->free_result();
}
}
return $returnData;
}
Use:
<div id="mostPopular">
<?php
$mostPopular = mostPopular($mysqli);
if(count($mostPopular) === 0){
?>
<p>No latest article available</p>
<?php
} else {
foreach($mostPopular as $Popular){
?>
<p class="posttitle"><?php echo $Popular['ForumTitle'];?></p>
<p class="posttext"><?php echo $Popular['ForumPostText'];?></p>
<?php
}
}
?>
</div>
The problem is that the config.php script is not started with the PHP start tag of
<?php
The config file should be like this:
<?php
$mysqli = new mysqli('localhost', 'userone', 'password', 'iitb');
EDIT: Make sure also to check the php_short_tags. It could be that the config.php file starts with a short tag <? and the short_open_tag is disabled on your localhost server.

session variable in select query

<?php
{
session_start();
include "dbconnect.php";
echo "email=".$_SESSION['email'];
$result = mysql_query("SELECT uid FROM master WHERE emailid='{$_SESSION['email']}'");
while($uid = mysqli_fetch_array($result))
{
echo $row[uid];
}
it is giving result for 1st echo ie email but for 2nd the error is
email=asdas#g.com
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, resource given in C:\xampp\htdocs\mymainproject\upload1.php on line 9
please help
You're using mysql_query and mysqli_fetch_array functions which belong to different database drivers.
You should choose one. In this case - it's mysqli.
PS: the first curly brace { right after <?php looks weird
Here are a few examples:
// restricted/dbconnect.php
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// mysqli::fetch_object()
<?php
session_start();
if(isset($_SESSION['email'])){
include 'restricted/dbconnect.php'; $db = db();
$result = $db->query("SELECT uid FROM master WHERE emailid='{$_SESSION['email']}'");
if($result->num_rows > 0){
while($row = $result->fetch_object()){
echo "<div>column name:{$row->columnName}</div><div>other column name:{$row->otherColumnName}</div>";
}
}
else{
echo 'No results were found';
}
$result->free(); $db->close();
}
else{
header('LOCATION:otherpage.php'); die();
}
?>
// mysqli::fetch_assoc()
<?php
session_start();
if(isset($_SESSION['email'])){
include 'restricted/dbconnect.php'; $db = db();
$result = $db->query("SELECT uid FROM master WHERE emailid='{$_SESSION['email']}'");
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<div>column name:{$row['columnName']}</div><div>other column name:{$row['otherColumnName']}</div>";
}
}
else{
echo 'No results were found';
}
$result->free(); $db->close();
}
else{
header('LOCATION:otherpage.php'); die();
}
?>
// mysqli::fetch_row()
<?php
session_start();
if(isset($_SESSION['email'])){
include 'restricted/dbconnect.php'; $db = db();
$result = $db->query("SELECT uid FROM master WHERE emailid='{$_SESSION['email']}'");
if($result->num_rows > 0){
while($row = $result->fetch_row()){
echo "<div>column name:$row[0]</div><div>other column name:$row[1]</div>";
}
}
else{
echo 'No results were found';
}
$result->free(); $db->close();
}
else{
header('LOCATION:otherpage.php'); die();
}
?>
Using the Object Oriented approach will save you typing. Note that you can put single dimensional Numeric Arrays inside double quotes without curly braces.
just use mysqli_query instead. i recommend switching to pdo, its easier to pass variables.
http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/

Categories