session variable in select query - php

<?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/

Related

rewrite queries from deprecated mysql_connect to PDO in 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.

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.

Connect to mysql db but no data from table is echo to screen

The script below connects to the db (I get the connected successfully echo) but none of the data from the query is shown onscreen.
I assume the data must be somewhere as I do not get the error message.
Question: Where is the error in the script?
<?php
//connectdb();
$con = mysqli_connect("localhost","UN","PW");
if ( $con == "" ) { echo " DB Connection error...\r\n"; exit(); }
echo 'Connected successfully';
$result = mysqli_query($con, "SELECT graduation_year FROM wp_gfsept2013");
while($row = mysql_fetch_array($result))
if ($result === "") {echo "An error occurred.";}
{
echo $row['graduation_year'];
echo "<br>";
}
?>
Appreciate any help that can be sent my way, I'm a real newbie at this stuff.
Roger
Try adding an opening brace after while($row = mysql_fetch_array($result)) and a closing brace before the end of the script.
Is this not a syntax issue?? Why is there an IF clause after a WHILE clause but before the opening bracket for the WHILE loop block?
Additionally, you are trying to use mysql_fetch_array() instead of mysqli_fetch_array().
<?php
//connectdb();
$con = mysqli_connect("localhost","UN","PW");
if ( $con == "" ) { echo " DB Connection error...\r\n"; exit(); }
echo 'Connected successfully';
$result = mysqli_query($con, "SELECT graduation_year FROM wp_gfsept2013");
if ($result !== FALSE && mysqli_num_rows($result) > 0) { // Proper way to test for results
while($row = mysqli_fetch_assoc($result))
{
echo $row['graduation_year'];
echo "<br/>";
}
}
else {
die("Query Returned 0 rows...");
}
?>
Documentation: mysqli_result::$num_rows

MySQL - mysql_fetch_assoc() doesn't give one column

My column type is SMALLINT and name is user_level.
Here is the code I am using:
<?php
mysql_connect("localhost", "root", "*********");
mysql_select_db("3591_other");
$result = mysql_query("SELECT * FROM rivase_f_users WHERE user_name = '$email' AND user_pass=sha1('$passwd')");
if (!$result) {
echo mysql_error();
}
//snip
else if (mysql_fetch_assoc($result)) {
$row=mysql_fetch_assoc($result);
$_SESSION['username']=$email;
if ($row['user_level']==1) {$_SESSION['usertype']='leader';}
header("Location: index.php");
die();
}
?>
$row['user_level'] looks like to be null, but phpmyadmin says it is 1. I tried echoing it with commenting the header-location row, it did not say anything. What am I doing wrong?
try this,
else if ($row = mysql_fetch_assoc($result)) {
$_SESSION['username']=$email;
if ($row['user_level']==1) {$_SESSION['usertype']='leader';}
header("Location: index.php");
die();
}
What you're trying to accomplish is unclear to me but you are discarding the first result:
else if (mysql_fetch_assoc($result)) {
// ^^^^^^^^^^^^^^^^^ Read and discard
$row=mysql_fetch_assoc($result);
// ^^^^^^^^^^^^^^^^^ Read next row
You are experiencing a logical if-else bug.
You are reading the value of next mysql_fetch_assoc() after testing the output result of the first call in the else condition, but you wanted to read the value from first returned result.
Based on your code try this
<?php
mysql_connect("localhost", "root", "*********");
mysql_select_db("3591_other");
$result = mysql_query("SELECT * FROM rivase_f_users WHERE user_name = '$email' AND user_pass=sha1('$passwd')");
if (!$result) {
echo mysql_error();
}
//snip
else if ($row=mysql_fetch_assoc($result)) {
$_SESSION['username']=$email;
if ($row['user_level']==1) {$_SESSION['usertype']='leader';}
header("Location: index.php");
die();
}
?>
I've changed the else if check to save the row when doing the comparison.

PHP MYQSLi Returning a different value if field is empty

This should be simple.... but it's taking a while... Here's the code that's not working (it either shows nothing or the blank state message each time). $show image is the query and I know it's running fine.
// BLANK STATE TOGGLE
$result = mysqli_fetch_array($showimage, MYSQLI_ASSOC);
if($result == ''){
echo '<p>Sorry- no image.</p>';
}
else {
echo '<p>There is an image!</p>';
}
}
If you only want to check for the existence of rows in the result from your query, why don't you simplify it like this
// $db is your MySQLi connection object
$query = 'SELECT COUNT(1) FROM `table` WHERE `something` = ?';
$stmt = $db->prepare($query);
$stmt->bind_param('s', $something);
$stmt->execute();
$stmt->bind_result($rowCount);
$stmt->fetch();
$stmt->close();
if ($rowCount > 0) : ?>
<p>There is an image!</p>
<?php else : ?>
<p>Sorry- no image.</p>
<?php endif ?>
mysqli_fetch_array returns null if there is no match in the database. So you need to check for null.
You may need to try this:
if $showimage is your query ..
//This should run fine
//$link is ur connection
$new_result = mysqli_query($link,$showimage);
$result = mysqli_fetch_array($new_result, MYSQLI_ASSOC);
if($result == null){
echo '<p>Sorry- no image.</p>';
}
else {
echo '<p>There is an image!</p>';
}
}

Categories