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.
Related
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.
Hey guys so i really have a problem in php and i have been working on it for like an hour and i can get it to work. So in my database i have two tables:
usuarios and menus
So each user have a menu assigned like this:
usuarios
id email ....... menus
1 email ...... 1,2,3,4
where 1,2,3,4 is text that i will explode and convert it into an array so latter i can get the menus checking the menu id's.
menus
id url .....
1 profile ..........
2 messages ..........
3 log out ..........
4 support ..........
I dont know why it is not working, please help.
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));}
// Checks the user id from his session (session has been already started in headers)
if($stmt->rowCount() > 0){
$row = $stmt->fetch();
$menus = $row['menus'];
//Gets the menus
$menus = explode(",", $menus);
//Converts the text into an array.
$i = 0;
$menusize = sizeof($menus);
//Checks how big is $menus array
$menusize = $menusize -1;
//This is because $i=0 and not 1
while ($i == $menusize) {
try{
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
$stmt->execute(array(':menus'=>$menus[$i]));
$row = $stmt->fetch();
if ($section==$row['url']) {
echo '<li class="liselected"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}else{
echo '<li class="menuelement"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
$i++;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Here is the problem, in this while
} else {
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}else{
header("Location:index.php");
}
?>
I have checked and what happends is that $i doesnt seems to be incrementing, i have been working on it but nothing seems to do it.
Thank you all for your support!
You should do it a little bit differently altogether, like storing the menu's in different rows but for now:
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
# When you set the $_SESSION['id'] and you're sure it's sanitized you don't have to prepare a query. Instead execute it directly.
# Preparing is useful for user submitted data or running the same query more then once with different values (seen below)
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
// This part of the code does not match your description of your database.
$row = $stmt->fetch();
$menu = explode(",", $row['menus']);
// end
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
try{
foreach($menu as $value){
$stmt->execute(array(':menus'=>$value));
$row = $stmt->fetch();
$css_class = ($section == $row['url']) ? 'liselected' : 'menuelement';
echo '<li class="'.$css_class.'"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
} else {
header("Location:index.php");
}
?>
Please note that I only prepared the query once, this is the proper way to do it. Preparing takes server performance, but once prepared you can rebind the values.
Also, I changed the loop to a foreach loop, easier to maintain.
There where also some bracket issues in the code, my advice always code in the same way so these issues are easy to spot.
I keep getting an error, even though I am 100% sure I followed the example that is found in the PHP manual.
The simplified version of the code can be found below.
note: connection to the database is ok.
EDIT: I keep getting an "Catchable fatal error: Object of class mysqli_stmt could not be converted to string" error.
EDIT: Now I keep getting "Mission Failed" even though I am sure that the row count should be 1.
Here's the coode used:
# $db = new mysqli('localhost', 'USER', 'PASSWORD', 'DATABSE');
$email = $db->prepare("select * from members where email = ?");
$email->bind_param('s', $email);
$email->execute;
$email->store_result;
$email->num_rows;
if ($email > 0) {
echo "<p>This e-mail is already in use, please try again with another e-mail.</p>";
exit;
} else {
echo "mission failed";
}
exit;
EDIT:
# $db = new mysqli('localhost', 'USER', 'PASSWORD', 'DB');
if ($db->connect_errno) {
echo "<p id=\"signup_confirmed\">Error: could not connect to database. Please try again later.</p>";
exit;
}
$checkRow = $db->prepare("select * from members where email = ?");
$checkRow->bind_param('s', $email);
$checkRow->execute;
$checkRow->store_result;
if ($checkRow->num_rows > 0) {
echo "<p id=\"signup_confirmed\">This e-mail is already in use, please try again with another e-mail.</p>";
exit;
} else {
echo "<p id=\"signup_confirmed\">Row checking has failed</p>";
}
change
$email->num_rows();
to
$email->num_rows;
in your code
New edit
$count = $email->num_rows;
if ($count > 0) {
echo "<p>This e-mail is already in use, please try again with another e-mail.</p>";
exit;
} else {
echo "mission failed";
}
More edit
change this to
$email = $db->prepare("select * from members where email = ?");
$email->bind_param('s', $email);
this
// you are over riding your $email value with the query thats the reason its not working
$query= $db->prepare("select * from members where email = ?");
$query->bind_param('s', $email);
# $db = new mysqli('localhost', 'USER', 'PASSWORD?', 'DATABSE');
$query_email = "select * from members where email = ?";
$email = $db->prepare($query_email);
$email->bind_param('s', $email);
$email->execute();
$email->store_result();
if ( $email->num_rows > 0) {
echo "<p id=\"signup_confirmed\">This e-mail is already in use, please try again with another e-mail.</p>";
exit;
}
$email is a result set, an object.
It will hold data returned from SQL operation.
You need to get the num_rows() in a variable.
Corrected code:
$cnt = $email->num_rows;
if ($cnt > 0) {
OR
if ($email->num_rows > 0) {
instead of
if ($email > 0) use if ($email->num_rows() > 0)
I highly appreciate that you try to help me.
My problem is this script:
<?php include("inc/incfiles/header.inc.php"); ?>
<?php
$list_user_info = $_GET['q'];
if ($list_user_info != "") {
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
$user_list = $get_user_list['username'];
$user_profile = "profile.php?user=".$user_list;
$profilepic_info = $get_user_list['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/avatar.png";
}
else {
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
if ($user_list != "") {
?>
<br>
<h2>Search</h2>
<hr color="#FF8000"></hr>
<div class="SearchList">
<br><br>
<div style="float: left;">
<img src="<?php echo $profilepic_info; ?>" height="50" width="50">
</div>
<?php echo "<h1>".$user_list."</h1>"; ?>
</div>
<?php
}
else {
echo "<br><h3>User was not found</h3>";
}
}
else {
echo "<br><h3>You must specify a search query</h3>";
}
?>
I am creating a search script that takes the mysql databse information and shows the result associated to the search query. My script is the above, but keep in mind the sql connection is established in an extern scipt.
The problem is that i want the script to first check if the user is found with the search query in the username row, and then get the entre information from that user and display it. If the user is not found with the username query, it should try and compare the search query with the name row, and then with the last name row. If no result is displayed it should then return an else statement with an error, e.g. "No user wsas found"
Yours sincerely,
Victor Achton
Do the query as Muhammet Arslan ... but just counting the rows would be faster ...
if(mysql_num_rows($get_user_info)){
//not found
}
you should add a "Limit 1" at the end if you are just interested in one result (or none).
But read about prepared statements
pdo.prepared-statements.php
This is how it should be done in 2013!
Something like this but you don't need 3 queries for this. you can always use OR in mysql statements
$handle1 = mysql_query("SELECT * FROM users WHERE username = $username"); // Username
if (($row = mysql_fetch_assoc($handle1) !== false) {
// username is found
} else {
$handle2 = mysql_query("SELECT * FROM users WHERE name = $name"); // name
if (($row = mysql_fetch_assoc($handle2) !== false) {
// name is found
} else {
$handle3 = mysql_query("SELECT * FROM users WHERE lastname = $lastname"); // Last name
if (($row = mysql_fetch_assoc($handle3) !== false) {
// last name is found
} else {
// nothing found
}
}
}
Already you did ,but you can improve it by using "AND" or "OR" on ur sql statement.
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info' or name = '$list_user_info' or last_name = '$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
if(empty($get_user_list))
{
echo "No User was found";
}
and you should control $list_user_info or u can hacked.
Here some adapted copy pasting from php.net
Connect
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
fetch data
$stmt = $dbh->prepare("SELECT * FROM users where name LIKE '%?%'");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
the rest is your programing ...
And do some reading it's very dangerous to use copied code without understanding !
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>';
}
}