PHP Function Calling MySQL - php

I have made a function in PHP to grab info from a MySQL database but am not sure about something.
Currently the function looks like this:
function profile_info($option, $size = NULL){
// MySQL Connection Info
$mysql_hostname = "";
$mysql_username = "";
$mysql_password = "";
$mysql_database = "";
$mysql_table = "";
// MySQL Connect
$con = mysqli_connect($mysql_hostname,$mysql_username,$mysql_password,$mysql_database);
// Check the Database Connection
if (mysqli_connect_errno()){
echo (mysqli_connect_error());
}
// Define UID
$uid = $_SESSION['login'];
// Deploy Query
$result = $con->query("SELECT * FROM $mysql_table WHERE uid='$uid'");
// Define Row For All Data
$row = $result->fetch_assoc();
if($option == "firstname"){
echo $row['first_name'];
}
if($option == "lastname"){
echo $row['last_name'];
}
if($option == "nickname"){
echo $row['nick_name'];
}
if($option == "email"){
echo $row['email'];
}
if($option == "dob"){
echo $row['date_of_birth'];
}
if($option == "status"){
echo $row['status'];
}
if($option == "gravitar"){
echo ("http://www.gravatar.com/avatar/" . md5( strtolower( trim( $row['email'] ) ) ) . "?d=mm&s=" . $size);
}
$result->close();
$con->close();
}
I've tested it and it works perfectly.
Now my question is, does it make a new connection to the database everytime I call profile_info?
If so, how do I fix it so that it only calls the database once for all the information.
Regards,
Tim

Yes, it always connect for information.
You can use $_SESSION.
You can get user datas and save it to $_SESSION and get them from session. If session is not created before you can get them from database and save it to $_Session.
session_start();
function profile_info($option, $size = NULL){
if(!$_SESSION['user']){
// MySQL Connection Info
$mysql_hostname = "";
$mysql_username = "";
$mysql_password = "";
$mysql_database = "";
$mysql_table = "";
// MySQL Connect
$con = mysqli_connect($mysql_hostname,$mysql_username,$mysql_password,$mysql_database);
// Check the Database Connection
if (mysqli_connect_errno()){
echo (mysqli_connect_error());
}
// Define UID
$uid = $_SESSION['login'];
// Deploy Query
$result = $con->query("SELECT * FROM $mysql_table WHERE uid='$uid'");
// Define Row For All Data
$row = $result->fetch_assoc();
$_SESSION['user'] = $row;
echo $_SESSION['user'][$option]
$result->close();
$con->close();
}else{
echo $_SESSION['user'][$option]
}
}
I am not coding PHP for years so there can be a syntax or logic mistake.

How about storing a global variable with the row, and only loading the data once. Then, if it's been loaded once already, just use the data stored in $data.
$called = false;
$data = null;
function profile_info($option, $size = NULL){
$row;
if ($called) {
$row = $data;
} else {
// it's been called
$called = true;
// get the info from database (removed for space)
}
// Define Row For All Data
$row = $result->fetch_assoc();
// define global var for row data
$data = $row;
// use the info (removed for space)
}

Q: does it make a new connection to the database everytime I call profile_info?
A: yes.
Q: how do I fix it so that it only calls the database once for all the information.
If you are calling this function more than once (or other functions also need a connectioN), then move the $con - mysqli_connect() and $con->close(); operations outside of the function, to a higher scope. Usually either at the start of the entire script, if you will almost always need a connection, or at the point in the script, at the point it's determined that a database connection will actually be needed.
Then pass the connection object $con as an argument to the function, e.g.
function profile_info($con, $option, ...
This will avoid the overhead of "churning" connections.
While you're at it, you might want to consider closing up some SQL Injection vulnerabilities. Including "unsafe" variables in SQL text can be an issue.
$sql = "SELECT * FROM $mysql_table WHERE uid='"
. mysqli_real_escape_string($con, $uid)
. "'");
$result = $con->query($sql);

use PDO prepared statements. its secure and easy to use. here's something you could do to store it as a session. instead replace session variables with normal variables and you could call to this each time without using session variables.either way its possible, but session method would not call database each and every time after its initialized this way.
//in case if you want to store all in session
session_start();
$con=new PDO('mysql:host='.$host.';dbname='.$dB.'', $dbUser, $dbPass);
$q=$con->prepare("SELECT * FROM $mysql_table WHERE uid=:uid");
$q->bindParam(":uid",$uid);
if ($q->execute())
{
while ($row = $q->fetch())
{
$_SESSION['fname']=$row['first_name'];
$_SESSION['lname']= $row['last_name'];
$_SESSION['nick']=$row['nick_name'];
$_SESSION['email']=$row['email'];
$_SESSION['dob']=$row['date_of_birth'];
$_SESSION['status']=$row['status'];
}
}
else
{
echo '<pre>';
print_r($q->errorInfo());
echo '</pre>';
}
$con=null;

Related

I'm unable to insert into MySQL using PHP (no errors are being displayed)

<?php
$q= $_REQUEST["q"];
$r = $_REQUEST["r"];
$s = $_SESSION['empid'];
$max = 0;
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'employeesurvey';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$sql1 = "SELECT QuestionID FROM question";
if(!mysqli_query($conn,$sql1)){
echo 'error2 php';
}
while($rw1 = mysqli_fetch_array($sql1)){
$Q = $rw1['QuestionID'] ;
if ($max<$Q){
$max = $Q;
}
}
$Q = $Q+1;
$sql = "INSERT INTO question VALUES (".$Q.",'".$r."',".$s.",CURRENT_DATE(),".$q.",0)";
if(!mysqli_query($conn,$sql)){
echo "Error";
}
?>
The db, table names are all correct. I'm using xmlHttpRequest.open() to pass the values to this page
the call statement is:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "gethint1.php?q=" + cid + "&r=" + question, true);
Im not getting any errors, nor the values are being inserted
Replace this line:
if(!mysqli_query($conn,$sql1)){
with these
$resultSet = mysqli_query($conn,$sql1);
if(!$resultSet){
And now replace this line:
while($rw1 = mysqli_fetch_array($sql1)){
With this one
while($rw1 = mysqli_fetch_array($resultSet)){
Reason is that you haven't executed query and stored the result set while at fetching record from result set, you are using direct query variable which is logically wrong.
why are you making a simple thing this complicated by obtaining Question id from table just use autoincrement field in your mysql table or use insert_id
and the problem is mysqli_fetch_array() function works on mysqli_query() function's output i.e. a object you are providing a string to a function which expects an object

Php webservice looping

I am about to lose my mind.I dont have any php experince and I am struggling about php web service.
Here is my code;
<?php
private $username2 = "";
private $password2 = "";
private $DB_CONNECTION;
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "dptest";
function __construct()
{
$this->DB_CONNECTION = mysqli_connect($this->servername, $this->username,
$this->password, $this->dbname);
}
function getUserType(){
$sql = "SELECT usertype FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
//$value = mysqli_fetch_array($result);
while(!is_null($value = mysqli_fetch_array($result))){
return $value['usertype'];
}
}
}
This is my function code.The other is my login code;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepare($_POST);
$userStatus = $auth->isUserValidToLogIn();
if ($userStatus) {
// user existed
// So log him to main page
$json['success'] = 1;
$json['message'] = 'access granted';
$json['usertype'] = $auth->getUserType();
echo json_encode($json);
} else {
$json['success'] = 0;
$json['message'] = 'error!';
echo json_encode($json);
}
I am trying to get the user's type but when try to get the data form phpmyadmin local database it only gives the first column's usertype.When I try to get 2nd,3rd,4th so on.. user's usertype it doesnt return anything and blank page shows up on postman app.
Also my database looks like this;
usertype username password
admin despro 1234
client test 1234
client despro2 1234
client despro3 1234
The reason you are only getting one column back is because you only request the one column. In order to get the columns you want you need to explicitly request them in your query or use '*' in order to get all columns back. So your query should look like this in order to get all columns from the data table:
$sql = "SELECT * FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
In general, I highly recommend that you stop using MySQLi extension and start using PHP Data Objects (PDO). It makes it easy to use prepared statements. Which also makes your code safer.
Then your query could look something like this (this is NOT the complete code):
// connecting to db
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT *
FROM login_test
WHERE userName = :username
AND pass = :password;';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username2, PDO::PARAM_STR);
$stmt->bindParam(':password', $password2, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
$response["userdata"] = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
}
Note that the code above is for returning multiple rows of data. If you just want the one row then use something like this:
if ($res) {
$response["userdata"] = array();
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
removing the 'while' statement.
You might want to take a look at this answer I gave, recently. It is a comprehensive example of using a webservice from an Android app.
How to insert all the SQL table data into an array in java [android studio]

Why do i get more results from my mysql query in php then what i ask for?

I am getting return values that do not exist in my current database. Even if i change my query the return array stays the same but missing values. How can this be what did i do wrong?
My MYSQL server version is 10.0.22 and this server gives me the correct result.
So the issue must be in PHP.
My code:
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Result:
array(1) {
[1]=> array(9) {
["UID"]=> string(1) "1"
["CreationTimestamp"]=> NULL
["UpdateTimestamp"]=> NULL
["ProcessState"]=> NULL
}
}
Solution:
I have found this code somewhere in my program. The program used the same name ass mine. This function turns the MYSQL result into a array. This happens between the result view and my script. This was done to make the result readable.
parent::processUpdatedAfter($date);
Function:
public function processUpdatedAfter($date)
{
$result = parent::processUpdatedAfter($date);
$array = Array();
if($result != false)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$array[$row["UID"]]["UID"] = $row["UID"];
$array[$row["UID"]]["CreationTimestamp"] = $row["CreationTimestamp"];
$array[$row["UID"]]["UpdateTimestamp"] = $row["UpdateTimestamp"];
$array[$row["UID"]]["ProcessState"] = $row["ProcessState"];
}
return $array;
}
return false;
}
I edited this and my script works fine now thanks for all the help.
Note that, var_dump($result); will only return the resource not data.
You need to mysql_fetch_* for getting records.
Example with MYSQLi Object Oriented:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['UID'];
}
}
else
{
echo "No record found";
}
$conn->close();
?>
Side Note: i suggest you to use mysqli_* or PDO because mysql_* is deprecated and closed in PHP 7.
You are var_dumping a database resource handle and not the data you queried
You must use some sort of fetching process to actually retrieve that data generated by your query.
$ts = '2016-09-20 08:56:43';
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > '$ts'";
$result = mysql_query($select_query, $link_identifier);
// did the query work or is there an error in it
if ( !$result ) {
// query failed, better look at the error message
echo mysql_error($link_identifier);
exit;
}
// test we have some results
echo 'Query Produced ' . mysql_num_rows($result) . '<br>';
// in a while loop if more than one row might be returned
while( $row = mysql_fetch_assoc($result) ) {
echo $row['UID'] . '<br>';
}
However I have to mention Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
$select_query = "SELECT `UID` FROM `process_state ` WHERE `UpdateTimestamp` > \"[given time]\" ORDER BY UID DESC ";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Try this hope it will works

how to acess my database elements using the for loop?

I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
First of all, you should use database access drivers to connect to your database.
Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];

PHP5 Mysqli class is not outputting data

So i am trying to make a backup class and this is what I have so far. Issue is the $tbl_data is empty. What am I doing wrong.
The connection to the database is successful.
Without the 'echo $tbl_data', the '$current_table - current table' output is correct but if 'echo $tbl_data' is used, only the first table is shown ( trying to backup two tables to begin with ).
class mBackup{
private $_connection = ""; //db connection var
private $output = ""; //sql output
private $tbl_data = "";
private $tbl_row = "";
private $nfields = "";
private $create_table_query = "";
private $create_table_output = "";
public function __construct($dbhost,$dbname,$dbuser,$dbpassword){
$this->_connection = new mysqli($dbhost,$dbuser,$dbpassword,$dbname);
//possible connection error
if($this->_connection->connect_errno){
echo "Failed to connect to the DB";
}
else{
echo "Connected<br />";
}
}
public function backup_db(){
//get the table names from the DB and store in an array
$result = $this->_connection->query("SHOW TABLES");
//get the TABLE names
while($row = $result->fetch_row())
{
$table_names[] = $row[0];
}
//For each table
foreach($table_names as $current_table)
{
echo $current_table." - current table<br />"; //debug
$tbl_data = "";
$tbl_row = "";
$nfields = "";
$create_table_query = "";
$create_table_output = "";
//SELECT Everything from the table in use
$query = $this->_connection->prepare("SELECT * FROM ?");
$query->bind_param('s', $current_table);
$query->execute();
$query->bind_result($tbl_data);
$query->fetch();
echo $tbl_data."<br/>";
}
}
Try something like:
while ($query->fetch()) {
echo $tbl_data;
}
and see if that gets you anything. From the little that I know, bind_result binds columns in the result set to variables. If your table has 5 columns, you should have bind_result($var1, $var2, $var3, $var4, $var5) but since your number of columns are going to change depending on the table, I don't know if bind_result will give you what you need.
Try closing the prepared statement after every loop
$query->close();
or resetting.
$query->reset()
You can't use ? for the table name. See the second note in http://www.php.net/manual/en/mysqli.prepare.php for the allowed places for markers. So you'll have to construct the query by normal variable interpolateion:
$select = sprintf("SELECT * FROM `%s`", $current_table);
$result = $this->_connection->query($select);

Categories