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.
Related
The database doesn't get updated for some strange reason, I can get the correct data (I checked it), but the database does not get updated when I click submit. Can you anyone check if there is anything missing?
NB: the "----" are just for security reasons!
<?php
$host = "sql308.-----.com";
$dbUsername = "----_3041----";
$dbPassword = "-----------";
$dbName = "----_3041----_phpmysqli";
$conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($conn-> connect_error) {
die("Connection échouée!".$conn-> connect_error);
}
$rn = $_GET['rn'];
$dt = $_GET['dt'];
$to = $_GET['to'];
$rk = $_GET['rk'];
if(isset($_POST['edit'])) {
$rn = $_POST['rn'];
$dt = $_POST['date'];
$to = $_POST["total"];
$rk = $_POST['remarques'];
$sql = "UPDATE `datab1` SET
`date` = '$dt',
`total` = '$to',
`remarques` = '$rk'
WHERE `datab1`.`id` = '$rn'";
$result = mysqli_query($conn, $sql);
if($result == 1) {
header('location:table.php');
}
else {
die(mysqli_error($conn));
}
}
?>
Most probably the update is executed without finding a match for the where condition.
Just before
if(isset($_POST['edit'])) {
add the following code at line 18
echo "<p>GET: "; var_dump($_GET); echo "<p>POST: "; var_dump($_POST); echo "<p>";
and inspect the values.
Also before
$result = mysqli_query($conn, $sql);
at line 30, please add
echo "<br>$sql<br>"; exit();
And if you could not solve after reviewing both the outputs, please post the same here.
Thank you #Natarajan N Napoleon for the helpful trick, the outputs are correct in both GET and POST as it's shown here:
GET: array(9) { ["rn"]=> string(2) "21" ["dt"]=> string(10) "07-12-2021" ["rk"]=> string(5) "walou" ["to"]=> string(4) "1250" }
POST: array(9) { ["date"]=> string(10) "07-12-2021" ["total"]=> string(4) "1800" ["remarques"]=> string(5) "done" ["edit"]=> string(8) "Modifier" }
the SQL Query is the one making troubles, this is what I get:
UPDATE `datab1` SET `date` = '07-12-2021', `total` = '1800', `remarques` = 'done' WHERE id = ''
I was assigning a null to my "rn" which caused this error, I had to pass the value of "rn" directly to my query without no modification.
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;
}
}
}
I am making an application in which I pull data from an SQL database. My php code echos json data but its not well formed. My current output does not have a name of the array of results, and I would like it to - I have provided a link to a picture of how I would like the output to look.
Any help would be greatly appreciated.
<?php
// database settings
$db_username = "****";
$db_password = "****";
$db_name = "****";
$db_host = "****";
//open connection to mysql db
$connection = mysqli_connect("$db_host","$db_username","$db_password","$db_name") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from markers";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
$data = array($emparray);
echo json_encode($data);
//close the db connection
mysqli_close($connection);
?>
Final JSON
Current Output
What if you replace line
$data = array($emparray);
with
$data = array('markers' => $emparray);
?
It should output something like
JSON : {"markers":[{"id":1,"lorem":"ipsum"},{"id":2,"lorem":"dolor"}]}
php > var_dump($test);
array(1) {
["markers"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
int(1)
["lorem"]=>
string(5) "ipsum"
}
[1]=>
array(2) {
["id"]=>
int(2)
["lorem"]=>
string(5) "dolor"
}
}
}
I have an error in php and I have no idea how to fix this. By the way this is my school lesson example so I don't really know what's happening there. This is supporsed to be master/detail navigation.
<?php
$mysqli = new mysqli("localhost", "root", "", "base");
$stmt = $mysqli->prepare('SELECT * FROM aeromiting WHERE id = ":id"');
echo $mysqli->error;
$stmt->bind_param(':id', $_GET['id']);
var_dump($stmt);
$data = $stmt->execute();
?>
Warning: mysqli_stmt::bind_param(): Number of elements in type
definition string doesn't match number of bind variables in
C:\xampp\htdocs\test1\detail.php on line 20 object(mysqli_stmt)#2 (10)
{ ["affected_rows"]=> int(0) ["insert_id"]=> int(0) ["num_rows"]=>
int(0) ["param_count"]=> int(0) ["field_count"]=> int(4) ["errno"]=>
int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { }
["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
If you want to do it in PDO, try this...
<?php
$host = 'localhost'; $db = 'base'; $user = 'root'; $pw = '';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$id = $_GET['id'];
$sql = "SELECT * FROM aeromiting WHERE id=:id";
$query = $conn->prepare($sql);
$query->bindValue(':id', $id, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
?>
Have a look at pdo_mysql for more information.
You're mixing APIs here. MySQLi can't accept strings or the likes as parameters.
$stmt = $mysqli->prepare('SELECT * FROM aeromiting WHERE id = ":id"');
$stmt->bind_param(':id', $_GET['id']);
Should be
$stmt = $mysqli->prepare('SELECT * FROM aeromiting WHERE id = ?');
$stmt->bind_param('i', $_GET['id']);
This is of course assumed that $_GET['id'] is an integer (hence the 'i' in the bind_param. If it's a string, replace the i with s.
You should probably get a bind_result as well, so you actually bind the results from the database to some variables. Take a look at the MySQLi documentation.
I want to make a the following thing happen in PHP PDO OOP
$conn = mysqli_connect("localhost", "root", "blogger.g", "test");
$query = mysqli_query($conn, "SELECT * FROM users WHERE username='sandeep'");
$row = mysqli_fetch_assoc($query);
echo $row['password'];
The code which I use in the OOP way is as follows
class getResults{
public $results;
public function start(){
try {
$DTH = new PDO("mysql:host=127.0.0.1;dbname=test", "root", "blogger.g");
$STH = $DTH->query("SELECT * FROM users WHERE username='sandeep'");
$results = $STH->fetchAll(PDO::FETCH_OBJ);
return $results;
} catch (PDOException $e){
return $e->getMessage();
}
}
}
var_dump(getResults::start());
I got the following output
array(1) { [0]=> object(stdClass)#3 (3) { ["id"]=> string(1) "1" ["username"]=> string(7) "sandeep" ["password"]=> string(8) "password" } }
And How Should I access each of the properties ??
You can access each row if you loop through the object with a while()-loop, for example.
while($row = getResults::start()) {
echo $row->id;
}
One last tip: If you're already using PDO, use Prepared Statements. For your safety.
Since your query yields a single row, don't use fetchAll:
$results = $STH->fetch(PDO::FETCH_OBJ);
would suffice. Now, store the returned value inside a variable:
$x = getResults::start();
Since, $x is a class object, you can access its members by -> operator:
echo $x->username . "\n" . $x->password;
Alternatively, you can use PDO::FETCH_ASSOC:
$results = $STH->fetch(PDO::FETCH_ASSOC);
$x = getResults::start();
echo $x['username'] . "\n" . $x['password'];