Help with mysqli and multiple queries - php

I've never had to use mysqli until today and cannot seem to get this right. What I want is a simple function that will accept a mysql procedure call and have it return those results.
When I started using these procedures, I noticed that the old way of querying the database, using mysql_query, would no longer get me the expected results; one procedure would successfully return and the other would not. After reading the manual and several other examples out there, I found that the reason for this odd behavior was because the results need to be buffered then cleared. I have tried several ways of doing this and have been unsuccessful.
What I have so far works if I create another instance of the mysqli object and will get me both results however, I don't think it's right that I should have to instantiate 20 different objects to get back 20 different queries.
Again, what I want here, is to have a single function that I can feed a procedure to and have the results returned back.
$mysqli = new mysqli('host','user','password','test');
$rs = $mysqli->query('CALL titles()');
while($row = $rs->fetch_object())
{
print_r($row);
}
$mysqli2 = new mysqli('host','user','password','test');
$rs2 = $mysqli2->query('CALL colours()');
while($row2 = $rs2->fetch_object())
{
print_r($row2);
}

you can make a class for this:
db.php // A db class. Call this you perform a query.
<?php
class MyConnection{
var $db_host = 'Localhost';
var $db_user = 'mYUserName';
var $db_password = 'myPassword';
var $db_name = 'mYDB';
var $connection;
function Connect(){
$this->connection = #mysqli_connect($this->db_host, $this->db_user, $this->db_password)
or
die("Error: ".mysqli_connect_error());
mysqli_select_db($this->connection, $this->db_name);
mysqli_query($this->connection, "SET NAMES 'utf8'");
}
function Disconnect(){
mysqli_close($this->connection);
}
function ExecSQL($query){
$result = mysqli_query($this->connection, $query)
or
die('Error: '.mysqli_error($this->connection));
return $result;
}
}
?>
Implementation:
include "db.php";
$conn = new MyConnection;
$conn->Connect();
$rs = $conn->ExecSQL('CALL titles()');
while($row = $rs->fetch_object())
{
print_r($row);
}
$rs2 = $conn->ExecSQL('CALL colours()');
while($row2 = $rs2->fetch_object())
{
print_r($row2);
}
$conn->Disconnect();

Related

"Function name must be a string" on INSERT - mysqli PHP

I have puzzled over this for some time. It is puzzling because a very similar query just a few lines above works fine. I am very new to mysqli, so there may be something very fundamental I am missing.
The connection is set up like this:
Class dbObj{
/* Database connection start */
var $servername = "myserver";
var $username = "myusername";
var $password = "mypassword";
var $dbname = "mydb";
var $conn;
function getConnstring() {
$con = mysqli_connect($this->servername, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$this->conn = $con;
}
return $this->conn;
}
}
Then, in an Ajax processing file:
include_once({the connection file above});
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$NeedsCls = new Needs($connString);
Then, inside a class called "Needs":
protected $conn;
protected $data = array();
function __construct($connString)
{
$this->conn = $connString;
}
function insertNeeds($params)
{
$ExpDate = $params[Expire];
$sql = "INSERT INTO `pNeeds` (PubCode, Title, Description, Keywords, Expire) VALUES('".$_SESSION["PubCode"]."','".$params["Title"]."','".$params["Description"]."','".$params[NeedsTags]."','".$ExpDate."'); ";
echo $result = mysqli_query($this->conn, $sql) or die("Error - Failed inserting Needs data");
$Record = $db->insert_id;
$KW = explode(';',$params[NeedsTags]);
$KWCount = count($KW);
for($x=0;$x<$KWCount;$x++)
{
$Keyword = $KW[$x];
$sql = "INSERT INTO `Keywords` (Keyword, PubCode, Table, Record, Expire) VALUES ('".$Keyword."','".$_SESSION["PubCode"]."','pNeeds','".$Record."','".$ExpDate."'); ";
echo $result = mysqli_query($this->conn,$sql) or die("Error - Keywords not saved<br />".$mysqli_error());
}
}
The first query works fine. The second fails with the error "Function name must be a string". I've verified the data going into the Ajax code is correct. It doesn't appear that I am missing something stupid. (famous last words) The error message makes no sense to me. Similar posts here on StackOverflow and elsewhere do not seem to pertain in this instance.
It looks like you're just grabbing $params wrong:
$ExpDate = $params[Expire];
$params[NeedsTags];
Should be:
$ExpDate = $params['Expire'];
$params['NeedsTags'];
Edit
You're actual error is from:
$mysqli_error()
Remove the $
Edit
RationalRabbit: To avoid confusing anyone, I should mention that the whole syntax was wrong. Using object oriented mysqli, the error syntax should have been
db->error
OR
mysqli($this->conn)

call data from database without mentioning specific rows

hye, i'm having trouble in calling all the rows in one table. hope anyone could assist me solve the error:
<?php
require_once('database.php');
$result = mysql_query("SELECT * FROM events ");
while($row = mysql_fetch_array($result))
?>
I am not an expert on mysqli stuff (I use a Connection class I found somewhere which provides functions like selectMultipleRows($query) and so on) but I will try to give a good answer here.
assuming you already have created a connection $this->connID
$mysqli = $this->connID;
$result = $mysqli->query($query);
$data = $result->fetch_all(MYSQLI_ASSOC);
//stuff I do to make my life easier:
$return = array(); //for scoping reasons
if (isset($data[0]['id'])) {
foreach ($data as $value) {
$return[$value['id']] = $value;
}
} else {
$return = $data;
}
as far as I am concerned this should work.
edit
my class Connection basically works like this:
$this->connID = new mysqli($this->server, $this->user, $this->pass, $this->database);
if ($this->connID→connect_errno) { //debug stuff
var_dump($this->connID->connect_error);
}
$this->connID->set_charset("utf8");
I guess this is all you will need.

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

PHP and PDO - Migrated from MySQL - Not Showing Results or Errors

I'm migrating parts of my code from mySQL over to PDO and I can't seem to see what is wrong with my code.
I've got a try/catch statement and error reporting on, but i'm getting nothing at all.
Can anyone here see what is wrong?
The files that are relevant to this question are:
db_pdo.php
<?php
// Define connection
$db_host = "localhost";
$db_name = "winestore";
$db_user = "user";
$db_pass = "pass";
$db = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
search.php
<?php
require_once ("MiniTemplator.class.php");
function getSearch($tableName, $attributeName) {
try {
require ("db_pdo.php");
$query = "SELECT DISTINCT {$attributeName} FROM {$tableName} ORDER BY {$attributeName}";
return $db->query($query);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
}
function generatePage(){
$t = new MiniTemplator;
$t->readTemplateFromFile ("search_template.htm");
$rows = getSearch("region", "region_name");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('regionName', $row['region_name']);
$t->addBlock("regionName");
}
$rows = getSearch("grape_variety", "variety");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('variety', $row['variety']);
$t->addBlock("variety");
}
$rows = getSearch("wine", "year");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('minYear', $row['year']);
$t->addBlock("minYear");
}
$rows = getSearch("wine", "year");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('maxYear', $row['year']);
$t->addBlock("maxYear");
}
$t->generateOutput();
}
generatePage();
?>
You are storing in $rows, but you are using $result afterwards, which will be empty.
// $rows = getSearch("region", "region_name");
// should be this:
$result = getSearch("region", "region_name");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
Side note: You are creating a new database connection with every search. You should store your $db object and reuse it, instead of creating new instances of it. I'd recommend to wrap all these functions in a class where you store it, but since you stated that you are migrating existing code you could use global $db to pull the existing object into the variable scope of your function:
// include this file once at the beginning of your script
require_once("db_pdo.php");
function getSearch($tableName, $attributeName) {
global $db; // pull $db inside the variable scope
try {
// ...
Try it?
$rows = getSearch("region", "region_name");
but
$result->fetch(PDO::FETCH_$rows->fetch(PDO::FETCH_ASSOC)){ )){
to
$rows->fetch(PDO::FETCH_ASSOC)){

PHP MySQLi select function not execute

I'm trying to call my function, but she's wrong.
I believe it is in connection variable.
Connection:
$conn = mysqli_connect('','','', '');
if(mysqli_connect_errno()) {
header("Location: error.php");
exit();
}
Function:
function t_car($id) {
global $conn;
$s_t_car = "SELECT *
FROM t_car
WHERE session='$id'";
$s_t_car_return = mysqli_query($conn, $s_t_car) or die("Erro SQL.".mysqli_error());
return $s_t_car_return;
}
Call Function:
$s_t_car_return = t_car($conn, $_SESSION['session_client']);
if(mysqli_num_rows($s_t_car_return )!=0) {
while($r_t_car = mysqli_fetch_array($s_t_car_return )) {
}
}
Error:
Catchable fatal error: Object of class mysqli could not be converted to string
At first you need to enter your settings from your MySQL server (mysql db).
$connection = mysqli_connect("HOSTNAME","USERNAME", "PASSWORD","DATABASE");
You can then use an if statement to check if the connection to the server has been made, if so, continue execution of following code, otherwise die();
If you want to fetch the data see below here:
$res = $connection->query("SELECT finger FROM hand WHERE index = 3");
while($row = $res->fetch_array())
{
print_r($row);
}
mysqli_query() returns a result. You have to fetch the result to do something with it.
$res = mysqli_query($conn, $s_t_car) or die("...");
$s_t_car_return = mysqli_fetch_row($res);

Categories