PHP Functions and MySQL Connectivity - php

I have a database.php file which stores the database connection info like this:
<?php
// Database connectivity stuff
$host = "localhost"; // Hostname for the database. Usually localhost
$username = "root"; // Username used to connect to the database
$password = "root"; // Password for the username used to connect to the database
$database = "blog"; // The database used
// Connect to the database using mysqli_connect
$connection = mysqli_connect($host, $username, $password, $database);
// Check the connection for errors
if (mysqli_connect_errno($connection)) {
// Stop the whole page from loading if errors occur
die("<br />Could not connect to the database. Please check the settings and try again.") . mysqli_connect_error() . mysqli_connect_errno();
}
?>
And also a functions.php file that has the following:
<?php
// Functions file for the system
function show_posts($user_id) {
$posts = array();
$sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
$result = mysqli_query($connection, $sql);
}
function show_users() {
$users = array();
$sql = "SELECT id, username FROM users WHERE status = 'active' ORDER BY username";
$result = mysqli_query($connection, $sql);
while ($data = mysqli_fetch_array($result)) {
$users[$data->id] = $data->username;
}
return $users;
}
function following($user_id) {
$users = array();
$sql = "SELECT DISTINCT user_id FROM following WHERE follower_id = $user_id";
$result = mysqli_query($connection, $sql);
while ($data = mysqli_fetch_assoc($result)) {
array_push($users, $data->user_id);
}
return $users;
}
?>
Both files are inside an /includes folder. I now have a users.php files in which I want to display a list of users. Here's my code that tries to do that:
<?php
$users = show_users();
foreach ($users as $key => $value) {
echo $key . " " . $value;
}
?>
The problem I have is this:
Notice: Undefined variable: connection in
/Applications/MAMP/htdocs/blog/includes/functions.php on line 13
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in /Applications/MAMP/htdocs/blog/includes/functions.php on line 13
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
null given in /Applications/MAMP/htdocs/blog/includes/functions.php on
line 15
The users.php file has require('includes/functions.php') and require('includes/database.php'). But somehow the values are not passed?. What am I doing wrong? Please help me out. I hope this makes sense. The problem with the undefined variable occurs for each function of the 3.

Either pass the $connection variable to your functions or make it global.
E.g:
function show_posts($connection, $user_id) {
$posts = array();
$sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
$result = mysqli_query($connection, $sql);
}
OR
function show_posts($user_id) {
global $connection;
$posts = array();
$sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
$result = mysqli_query($connection, $sql);
}

Try $GLOBALS['connection'] instead of $connection in your function. See more here

Related

while ($data = mysql_fetch_array() ) doesnot working

I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>

Use data from one SQL-query to another

I need to store the values of the column 'following' in an array. However, I can't figure out what's wrong with this code.
session_start();
$connect = mysqli_connect("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$result = mysql_query("SELECT * FROM Followers WHERE user='$user'");
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row['following'];
}
It's easier to use a jointure, which will be far more efficient :
Select * from message left join followers on followers.following=Messages.user where Follower.user=...
HTH
Regards
Your solution will encounter problems if you forget to escape caracters like " ' " or " " " or even " \ ".
If I was you, I'd merge into a subquery this way:
$sql = "SELECT * FROM Messages WHERE user IN
(SELECT * FROM Followers WHERE user='$user')"
$result = mysqli_query($connect, $sql );
cheers!
Replace the below
mysql_fetch_array($result) with mysqli_fetch_array($result)
Hope it works!
try this
session_start();
$connect = new mysqli("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$result = mysqli_query($connect,"SELECT * FROM Followers WHERE user='$user'");
$data = array();
while ($row = mysqli_fetch_array($result)) {
$data[] = $row['following'];
}
As was pointed out you ought to use a prepared statement to avoid nasty sql injection. As the only field that is being used is follower limit the columns returned ( makes it easier using below notation - notably bind_result )
session_start();
$data = array();
$db = new mysqli("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$sql='select `following` from `followers` where user=?';
$stmt=$db->prepare($sql);
if( $stmt ){
$stmt->bind_param('s',$user);
$res=$stmt->execute();
if( $res ){
$stmt->bind_result($follower);
while( $stmt->fetch() ){
$data[]=$follower;
}
$stmt->free_result();
$stmt->close();
}
}
$db->close();
You have 3 errors in code:
1.mysql_query() is deprecated and may give error so use mysqli_query() which expects 2 paramter connection and query.
2.Your query is not receiving user variable value since its a string.
3.Your row is not an associative array for which you can get following value so use mysqli_fetch_assoc() instead.
You can use the following code:
$connect = mysqli_connect("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$result = mysqli_query($connect,"SELECT * FROM followers WHERE user='".$user."'");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[]=$row['following'];
}

Adding parameters to an already working webservice

I have the following already working great, but would like to add a parameter as this returns the whole data set.
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "00000";
$mysql_db_password = "00000";
$mysql_db_database = "000000";
$con = #mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,
$mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$var = array();
$sql = "SELECT * FROM mns";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"mns":'.json_encode($var).'}';
?>
For clarification, I was hoping to add a parameter in the url that is passed through to the php so that I get specific records. For example, if there is a field called [Customer], I would like to pass a customer id to it.

Errors when adding data to a database with PHP

I have to make a web app that gets information from my database, that gets its info from an API). Then I have to show items under certain conditions.
But when I try to add the data from the API, I got a strange message:
Notice: Trying to get property of non-object in c:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Here is my PHP code:
<?php
require_once 'settings.php';
$mysqli = mysqli_connect($db_host, $db_user, $db_password, $db_database);
if (mysqli_connect_error()) {
echo mysqli_connect_error($mysqli) . "We are not able to connect to the online database";
}
jsondecode($mysqli);
if (isset($_GET['club']) && !empty($_GET['club'])) {
jsondecode($mysqli);
} else if (isset($_GET['thuisPoint']) && !empty($_GET['thuisPoint']) && ($_GET['uitPoint']) && ($_GET['uitPoint'])) {
updatePoints($mysqli);
} else {
getWedstrijd($mysqli);
}
function jsondecode($mysqli) {
$apiLink = 'http://docent.cmi.hr.nl/moora/imp03/api/wedstrijden?club=';
// $club = $_GET['club'];
$data = json_decode(file_get_contents($apiLink . "Ajax"));
foreach ($data->data as $info) {
$thuisClub = $info->homeClub;
$uitClub = $info->awayClub;
addWestrijden($mysqli, $thuisClub, $uitClub);
}
}
//querys
function addWestrijden($mysqli, $thuisClub, $uitClub) {
$query = "INSERT INTO wedstrijd VALUES(null, '$thuisClub', '$uitClub')";
$resultAddWedstrijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
function getWedstrijd($mysqli) {
$query = "SELECT * FROM wedstrijd ORDER BY thuisClub DESC";
$resultGetWedstijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
while ($result = mysqli_fetch_assoc($resultGetWedstijd)) {
$rows [] = $result;
}
header("Content-Type: application/json");
echo json_encode($rows);
exit;
}
function updatePoints($mysqli) {
$id = $_GET['id'];
$thuisPoints = $_GET['thuisPoint'];
$uitPoints = $_GET['uitPoint'];
$query = "UPDATE wedstrijd "
. "SET thuisPunt = '$thuisPoints', uitPunt = '$uitPoints') "
. "WHERE id = '$id'";
mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
I did modify it a bit so it would add data from the API. I really would appreciate it if someone could help me.
Change your foreach to:
foreach ($data as $data => $info)

Error when I passed on values on function

Sorry about the last post I had. Here's my revision, please help me.
<?php
//connect database
$sql = "SELECT * FROM user where user_id = 8320 AND password = 'admin' ";
$query = pg_query($sql);
var_dump($row = pg_fetch_array($query)); //dumps correctly.
?>
BUT THE PROBLEM IS THIS..when I try to make it as a function LIKE:
function check($user_id, $password)
{
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($sql);
$row = pg_fetch_array($query);
return $row;
}
AND CALL IT HERE:
var_dump($data = check(8320, 'admin')); DUMPS NULL;
How come it ended up like this?
Its returning NULL because there is an error with your SQL query, and no results are being returned. You should do some error checking in your function, try this version:
function check($user_id, $password)
{
$dbconn = pg_connect("host=localhost dbname=test");
$sql = "SELECT * FROM user where user_id = $1 AND password = $2 ";
$result = pg_query_params($dbconn, $sql, array($user_id,$password));
$row = pg_fetch_array($result);
if (!$row) {
echo pg_last_error($dbconn);
} else {
return $row;
}
}
Try the code below. It should work fine for you.
$data = check(8320, 'admin');
var_dump($data);
Seems like your PostgreSQL resource is missing inside the function. You have two options.
Declare the connection resource inside the function using global.
Establish the connection inside the function.
This is the first option:
$conn = pg_connect('host','user','pass','db');
function check($user_id, $password)
{
global $conn;
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
And this is the second option:
function check($user_id, $password)
{
$conn = pg_connect('host','user','pass','db');
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
According to the PHP manual, You may omit connection resource, but it is not recommended, since it can be the cause of hard to find bugs in scripts.

Categories