I have a connection class and it connects to the desired db table successfully. I have performed an insert query and i want to get the last inserted id of the connection. But I get a Notice: Undefined property: connection::$insert_id error. I var_dump($con) on connection object and following is what i get. Hope someone can help me to get this solved. Your help is much appreciated.
object(connection)#2 (5) { ["db_name"]=> string(5) "dbproject" ["db_user"]=> string(4) "root" ["db_pass"]=> string(0) "" ["db_host"]=> string(9) "localhost" ["connection"]=> object(mysqli)#3 (19) { ["affected_rows"]=> int(1) ["client_info"]=> string(79) "mysqlnd 5.0.12-dev - 20150407 - $Id: 241ae00989d1995ffcbbf63d579943635faf9972 $" ["client_version"]=> int(50012) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["field_count"]=> int(0) ["host_info"]=> string(20) "localhost via TCP/IP" ["info"]=> NULL ["insert_id"]=> int(26) ["server_info"]=> string(21) "5.5.5-10.1.19-MariaDB" ["server_version"]=> int(50505) ["stat"]=> string(136) "Uptime: 302248 Threads: 1 Questions: 9631 Slow queries: 0 Opens: 65 Flush tables: 1 Open tables: 40 Queries per second avg: 0.031" ["sqlstate"]=> string(5) "00000" ["protocol_version"]=> int(10) ["thread_id"]=> int(522) ["warning_count"]=> int(0) } }
class connection {
public $db_name;
public $db_user;
public $db_pass;
public $db_host;
public $connection;
public function connection(){
$this->db_host = HOST;
$this->db_user = DB_USERNAME;
$this->db_pass = DB_PASSWORD;
$this->db_name = DB_NAME;
$this->connection = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
}
function connect($host, $user, $pass, $db_name) {
$this->connection = new mysqli($host, $user, $pass, $db_name);
if ( mysqli_connect_errno() ) {
printf("Connection failed: %s", mysqli_connect_error());
exit();
}
return $this->connection;
}
public function query($sql)
{
return $this->connection->query($sql);
}
}
//--------
require_once("connection.php");
class DB {
public $con;
function __construct()
{
$this->con = new connection();
}
function insertQuery($table, $data_array){
$fields = " (";
$values = " VALUES (";
$x = 0;
$y = 0;
foreach ($data_array as $key => $value) {
$fields.= $key;
$values.= "'".addslashes($value)."'";
if(sizeof($data_array)-1 != $x){
$fields.= ",";
$values.=",";
}
else{
$fields.= ")";
$values.=")";
}
$x++;
}
$sql = "insert into ".$table.$fields.$values;
if (!$this->con->query($sql) === TRUE) {
return "Error: " . $sql . "<br>" . $this->con->error;
}
else {
$last_id = $this->con->insert_id;
return $last_id;
}
}
}
In DB class constructor first you should have set credential properties (db_host, db_user, db_pass, db_name) and call connection method of connection class
class DB {
public $con;
function __construct()
{
$this->con = new connection();
$this->con->db_host = HOST; // replace HOST
$this->con->db_user = DB_USERNAME; // replace DB_USERNAME
$this->con->db_pass = DB_PASSWORD; // replace DB_PASSWORD
$this->con->db_name = DB_NAME; // replace DB_NAME
$this->con->connection();
}
function insertQuery($table, $data_array){
$fields = " (";
$values = " VALUES (";
$x = 0;
$y = 0;
foreach ($data_array as $key => $value) {
$fields.= $key;
$values.= "'".addslashes($value)."'";
if(sizeof($data_array)-1 != $x){
$fields.= ",";
$values.=",";
}
else{
$fields.= ")";
$values.=")";
}
$x++;
}
$sql = "insert into ".$table.$fields.$values;
if (!$this->con->query($sql) === TRUE) {
return "Error: " . $sql . "<br>" . $this->con->error;
}
else {
$last_id = $this->con->insert_id;
return $last_id;
}
}
}
Related
Why get_result return object in this example?
function db_connect() {
$db_host='localhost';
$db_name='contact_manager';
$db_user='root';
$db_pass='';
$connection = new mysqli($db_host, $db_user, $db_pass, $db_name);
return $connection;
}
$connection = db_connect();
$query = $connection->prepare("SELECT * FROM users");
$query->execute();
$op = $query->get_result();
var_dump($op);
this is the vardump:
object(mysqli_result)#3 (5) {
["current_field"]=> int(0)
["field_count"]=> int(4)
["lengths"]=> NULL
["num_rows"]=> int(24)
["type"]=> int(0) }
According to official documentation (here), get_result() returns a resultset for successful SELECT queries. Next you must extract data from the result set, using for example $result->fetch_assoc():
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo $row['user_id'];
}
Task:
Find the unique rows from table one. For example, given the following tables:
guests_1.csv
firstname,lastname
Alex,Anderson
Billy,Bobson
Casandra,Crowford
Dennis,Dixson
guests_2.csv
firstname,lastname
Alex,Anderson
Billy,Bobson
Cindy,Crowford
Dave,Dixson
I would want: Casandra,Crowford and Dennis,Dixson to be the result since they are unique to table one.
index.php
<?php
class DataComparison {
public function __construct() {
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "scotchbox";
$this->conn = new mysqli($servername, $username, $password, $dbname);
if ($this->conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
public function drop_tables( $tables ) {
foreach( $tables as $key => $table_name ) {
$sql = "DROP TABLE $table_name";
$this->conn->query($sql);
}
}
public function create_table( $table_name ) {
$sql = "CREATE TABLE $table_name (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL
)";
if ($this->conn->query($sql) === TRUE) {
echo "Table $table_name created successfully.\n";
} else {
echo "Error creating table: " . $this->conn->error . "\n";
}
}
public function load_data( $table_name ) {
$sql = "LOAD DATA LOCAL INFILE '/var/www/public/" . $table_name . ".csv'
INTO TABLE $table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(firstname, lastname);";
if ($this->conn->query($sql) === TRUE) {
echo "Imported CSV data into Table $table_name.\n";
} else {
echo "Error importing data: " . $this->conn->error . "\n";
}
}
public function compare_tables( $table_one, $table_two ) {
$sql = "SELECT *
FROM $table_one
LEFT OUTER JOIN $table_two ON ($table_one.id = $table_two.id)";
$res = $this->conn->query($sql);
echo '<pre>';
while ($row = $res->fetch_assoc()) {
var_dump($row);
}
}
}
$instance = new DataComparison();
$instance->drop_tables( [ "guests_1", "guests_2" ] );
$instance->create_table( "guests_1" );
$instance->load_data( "guests_1" );
$instance->create_table( "guests_2" );
$instance->load_data( "guests_2" );
$instance->compare_tables( "guests_1", "guests_2" );
?>
Steps to reproduce:
git clone https://github.com/scotch-io/scotch-box import-csv
cd import-csv
vagrant up
then visit: http://192.168.33.10 to check it's working
edit import-csv/public/index.php so it looks like the above code segment
create guests_1.csv and add the data from above
create guests_2.csv and add the data from above
then visit: http://192.168.33.10
But the output is just
array(3) {
["id"]=>
string(1) "1"
["firstname"]=>
string(4) "Alex"
["lastname"]=>
string(8) "Anderson"
}
array(3) {
["id"]=>
string(1) "2"
["firstname"]=>
string(5) "Billy"
["lastname"]=>
string(6) "Bobson"
}
array(3) {
["id"]=>
string(1) "3"
["firstname"]=>
string(5) "Cindy"
["lastname"]=>
string(8) "Crowford"
}
array(3) {
["id"]=>
string(1) "4"
["firstname"]=>
string(4) "Dave"
["lastname"]=>
string(6) "Dixson"
}
Which is just the output of table two.
A left join will return all the results from table 1 and any from table 2 which match your condition. The important part here is rows in table 2 which don't match your condition will return NULL
So the condition you check for is firstname and lastname both match, then you only return the results which are NULL as they didn't match.
SELECT a.firstname, a.lastname
FROM Table1 a
LEFT JOIN Table2 b ON a.lastname = b.lastname AND a.firstname = b.firstname
WHERE b.lastname IS NULL;
I'm using this to select data from mysql in php
<?php
error_reporting(E_ALL);
$servername = "localhost";
$username = "******";
$password = "******";
$database = "*******";
// Create connection
$conn2 = new mysqli($servername, $username, $password, $database);
$stmt = $conn2->prepare('SELECT id, title, views from `blog_main`');
$stmt->execute();
var_dump($stmt);
$result = $stmt->get_result();
while($r=$result->fetch_assoc())
{
echo "id: " . $r["id"]. " - Name: " . $r["title"]. " " . $r["views"]. "<br>";
}
$conn->close();
?>
However no result is shown, but if I run this query on phpmyadmin interface it returns rows.
This code worked fine on localhost but when I shifted it to godaddy's server, I'm facing this problem only in prepared statement.
When I'm using normal query method it displays rows, only prepared statements are not working.
This is the value of var dump:
object(mysqli_stmt)#2 (10) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(0) ["field_count"]=> int(3) ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
Is there any kind of extension I need to enable or what might be the problem?
here is my answer for your question,
create file db.php
$dbInfo = array(
'host' => "localhost",
'user' => "******",
'pass' => "******",
'dbname' => "******"
);
create dbcon.php
class database{
protected $databaseLink;
function __construct(){
include "db.php";
$this->database = $dbInfo['host'];
$this->mysql_user = $dbInfo['user'];
$this->mysql_pass = $dbInfo['pass'];
$this->databaseName = $dbInfo['dbname'];
$this->openConnection();
return $this->get_link();
}
function openConnection(){
$this->databaseLink = mysqli_connect($this->database, $this->mysql_user, $this->mysql_pass, $this->databaseName);
}
function get_link(){
return $this->databaseLink;
}
}
create func.php
include "dbcon.php";
function selectData(){
$db = new database();
$selectQuery = "SELECT id, title, views FROM blog_main";
$selectQuery = mysqli_query($db->get_link(), $selectQuery) or die(mysqli_error());
while($r = mysqli_fetch_assoc($selectQuery)) {
$rows[] = $r;
}
return $result = json_encode(($rows));
mysqli_close($db->get_link());
}
and in for example index.php you can get data from which SQL return
include "func.php";
$data = selectData();
$dataJson = json_decode($data, TRUE);
foreach ($dataJson as $key => $value) {
echo "id: " . $value['id']. " - Name: " . $value['title']. " " . $value['views']. "<br>";
}
good luck
Seems like it was the disable driver issue. I enabled the stmt_mysqli driver and it worked.
Here's my function:
<?php
function getResults($query) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$conn->set_charset("utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($query);
if ($result) {
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
} else {
return mysqli_error($conn);
}
}
?>
And I use it here:
if ($_POST["action"] == "getCitiesByState") {
$cities = getResults("SELECT * FROM tbl_cidades WHERE estado_id = ".$_POST["state_id"]);
echo json_encode($cities, JSON_UNESCAPED_UNICODE);
die();
}
It outputs:
{id: "8853", estado_id: "26", nome: "Adamantina", cep: "17800000", loc_no_abrev: "Adamantina"},…]
The id, estado_id, nome, etc, all unquoted, form invalid JSON data. How can I return them as strings so that they can be valid JSON?
Here's one example of the output of var_dump($cities)
array(1) { [0]=> array(5) { ["id"]=> string(4) "1778" ["estado_id"]=> string(1) "7" ["nome"]=> string(9) "Brasília" ["cep"]=> string(0) "" ["loc_no_abrev"]=> string(9) "Brasília" } }
Things may be getting hung up on the Unicode text; try modifying your database code as follows:
function getResults($query) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$conn->set_charset("utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($query);
if ($result) {
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = array_map("utf8_encode", $row);
}
return $rows;
} else {
return mysqli_error($conn);
}
}
(By the way, you're introducing a lot of overhead by reconnecting to the database with every query.)
You can simply get the keys by looping the fetched array
while($row = $result->fetch_assoc()) { //each row
foreach($row as $key => $value){ // each key in each row
echo $key;
}
}
Like this ?
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$rows [] = $row;
}
echo json_encode($rows);
I am running 2 queries, the first one goes through correctly and returns the desired value, but the second one returns false.
I have set $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); so I should be getting an exception over false, so I am guessing that my $stmt->execute(); is the culprit here.
As that's the only function that can return false now that I've set the error attribute.
I have also tried setting $stmt->closeCursor();, $stmt = null;, and unset($stmt); with no avail.
This executes two queries (both "darkrp" and "pointshop" in the fetch_wallet() function.
if($this->pdo) {
foreach($this->methods as $method => $bool) {
if($bool) { $array[$method] = $this->fetch_wallet($method); }
}
}
This is the fetch_wallet() function:
public function fetch_wallet($type) {
if($type == "darkrp") {
$query = "SELECT `wallet` FROM `darkrp_player` WHERE uid=:uid LIMIT 1";
}
elseif ($type == "pointshop") {
$query = "SELECT `points` FROM `pointshop_data` WHERE uniqueid=:uid LIMIT 1";
}
try {
$stmt = $this->pdo->prepare($query);
$stmt->execute(array(":uid" => $this->uniqueid));
$result = $stmt->fetchColumn();
return $result;
}
catch (PDOException $e) {
return $e->getMessage();
}
}
When I run var_dump($stmt->errorInfo()); I get this, which means that both queries runs fine, although the last one returns false when it should return 440. No exception is thrown.
array(3) {
[0]=> string(5) "00000"
[1]=> NULL
[2]=> NULL
}
array(3) {
[0]=> string(5) "00000"
[1]=> NULL
[2]=> NULL
}
Printed screen of the pointshop_data table in phpMyAdmin (I want the 440 value there):
Value returned from var_dump($this->uniqueid); is 3266928646
I have debugged everything, and I get no errors whatsoever, just a false.
PHP Version: 5.3.10
MySQL Version: 5.5.38
OS: Ubuntu 12.04 LTS
I think there must be some other error in your class that makes this code does not work.
I've imported your tables structure and created the following testing code:
<?php
class A
{
private $pdo;
private $uniqueid;
private $methods = ['darkrp' => true, 'pointshop' => true];
public function __construct($pdo, $uniqueid)
{
$this->pdo = $pdo;
$this->uniqueid = $uniqueid;
}
public function fetch_wallet($type)
{
if ($type == "darkrp") {
$query = "SELECT `wallet` FROM `darkrp_player` WHERE uid=:uid LIMIT 1";
} elseif ($type == "pointshop") {
$query = "SELECT `points` FROM `pointshop_data` WHERE uniqueid=:uid LIMIT 1";
}
try {
$stmt = $this->pdo->prepare($query);
$stmt->execute(array(":uid" => $this->uniqueid));
$result = $stmt->fetchColumn();
return $result;
} catch (PDOException $e) {
return $e->getMessage();
}
}
public function run()
{
if ($this->pdo) {
foreach ($this->methods as $method => $bool) {
if ($bool) {
$array[$method] = $this->fetch_wallet($method);
var_dump($array[$method]);
}
}
}
}
}
$pdo = new PDO('mysql:host=localhost;dbname=tests', 'root', '');
$a = new A($pdo, 3266928646);
$a->run();
The result I get for this is:
string(4) "2075" string(3) "440"
So it is working as it should.
Please try this code (that's the whole file - of course you need to change your db name, user and password) and check if it gets you the same results. If yes, probably you have other errors in your class.
Change
$stmt->execute(array(":uid" => $this->uniqueid));
to
$stmt->bindValue(':uid', $this->uniqueid);
$stmt->execute();