first of all, I want to thank you to everyone who gives this post attention. I got a problem when migrating code from php5 to php7. I actually don't know what is going wrong in my code
class database {
public function __construct () {
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db($conn, 'crm');
}
public function view_chart(){
$data = mysqli_query($conn, "select * from t_chart");
while($d = mysqli_fetch_array($data)){
$hasil[] = $d;
}
return $hasil;
}
foreach($db->view_chart() as $x){
echo "<option value='$x[id_chart_cat]'>$x[chart_name]</option>";
}
the view_chart() not work but it's work in php4 as well. anyone here can tell me what is going wrong with this code? I really appreciate any answer which is related to this question. Thank you.
You have to declare $conn as class member variable so it's accessible from other class functions.
Do:
class database {
public $conn; // added
public function __construct () {
$this->conn = mysqli_connect("localhost", "root", ""); // modified
mysqli_select_db($this->conn, 'crm'); // modified
}
public function view_chart(){
$data = mysqli_query($this->conn, "select * from t_chart"); // modified
while($d = mysqli_fetch_array($data)){
$hasil[] = $d;
}
return $hasil;
}
foreach($db->view_chart() as $x){
echo "<option value='$x[id_chart_cat]'>$x[chart_name]</option>";
}
when I updated my PHP-scripts to PHP7 I had issues with
mysqli_fetch_array()
you should replace it with a function like
mysqli_fetch_assoc()
did you first check and make sure your connection was being made? and how i always did it in 7 was like this
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbName = "test";
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
then you can do
<?php
$query = "SELECT * FROM whatever";
$result = $conn->query($query);
$hasil = [];
?>
then you should be able to just do
while($row = $result->fetch_assoc()){
$hasil[] = $row;
}
return $hasil;
then go into your foreach...not sure if that's what your looking for but hope it helps
Related
I'm trying to echo the query made to my database. So far the code runs but nothing happens. I'm very new at coding so help or an explanation about what I'm doing wrong would be awesome! Thanks a lot!!!
<?php
$servername = "servername";
// REPLACE with your Database name
$dbname = "dbsname";
// REPLACE with Database user
$username = "username";
// REPLACE with Database user password
$password = "password";
$ID = 1;
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "Error de conexion.";
}
$sql = "SELECT * FROM registro WHERE ID = '1' ";
$result = $conn->query($sql);
while ($data = $result->fetch_assoc()){
$sensor_data[] = $data;
}
echo $data;
$conn->close();
Thanks everyone who replied, #AbraCadaver was right, I can't echo an array so I used print_r() instead and printed the variable $data. Now the php file prints the array with the query results. Thank you all!
$sql = "SELECT * FROM registro WHERE ID = $ID";
while ($data = $result->fetch_assoc()){
$sensor_data[] = $data;
print_r($data);
}
I have been looking at this code for a while and can't figure out where the problem is.
I am new to coding in general, but especially new to CRUD and SQL. I want to create a prepared statement here to use variables instead of exact values. I don't understand where the issue comes from
I have a Databasetools.php
<?php
class DatabaseTools
{
//private $user = $_SESSION['userId']; // these get called when the object gets created
//private $userEmail = $_SESSION['emailUser'];
public function __construct($Name)
{
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "supersecretpassword";
$dbPort = "3306";
$this->name = $Name;
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $this->name, $dbPort);
$stmt = mysqli_stmt_init($conn);
if(!$conn)
{
die("connection faild: ".mysqli_connect_error());
}
}
public function lookup($dBName, $Row, $Column)
{
//$sql = "SELECT ".$Column." FROM ".$dBName." WHERE ".$Row.";";
$sql = "SELECT ? FROM ? WHERE ?;";
if(!mysqli_stmt_prepare($stmt, $sql))
{
echo "False";
}
else
{
mysqli_stmt_bind_param($stmt, "sss", $column, $dBName, $Row);
mysqli_stmt_execute($stmt);
$result = mysli_stmt_get_result($stmt);
echo $result;
}
// try to connect to the database
}
public function setCell($Database, $Row, $Column)
{
}
public function disconnect($dBName)
{
}
public function echotest()
{
}
}
?>
And I am using a page to check if the code is working
<?php
require "Model/php/databaseTools.php";
$loginData = new databaseTools("loginsystem");
$loginData->lookup("loginsystem","*","*");
?>
Thanks so much if you could point me in the write direction.
Are you sure you have $stmt value in the lookup function?
Try to add it as one of the parameters, something like this:
public function lookup($dBName, $stmt, $Row, $Column)
and then call it also with $stmt parameter:
$loginData->lookup("loginsystem", <stmt> ,"*","*");
My programming level is fairly elementary so a 'coding for idiots' type of explanation would be great...
I have the following code:
<?php
$host = 'localhost';
$user = 'user';
$password = 'password';
$db_name = 'db_name';
$connect = mysqli_connect($host, $user, $password);
mysqli_select_db($connect, $db_name) or die ("Couldn't connect");
function roll_die() {
$throw = rand(1, 6);
return $throw;
}
function get_subtotal() {
$query = "SELECT * FROM throws";
$result = mysqli_query($connect, $query);
while ($row = $result->fetch_assoc()) {
echo $row['value']."<br>";
}
}
?>
I get an error because the '$connect' in the function subtotal() is apparently undefined. How can that be if it's defined at the top of the page? Wouldn't that make it a global function?
Please don't just give me the correct code to fix this. Could you explain what's going on and how PHP defines and stores variables?
Thanks!
Ok, I found the answer.
At the top of the page:
$connect = mysql_connect($host, $user, $password);
Then within the function:
global $connect;
Actually, I found the answer in another question which was essentially asking the same thing, so apologies for the repost.
What I want is to return MYSQL query in a array however my code returns a bool(true).
Here is the code from code.php
require('model.php');
$id = $_POST['id'];
$password = $_POST['password'];
$user = new user();
$row = $user->check_user($id, $password);
var_dump($row);
Here is the code from model.php
class config {
public $dbhost = "localhost";
public $dbuser = "root";
public $dbpass = "";
public $dbused = "dbname";
function dbconn() {
$conn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass,$this->dbused);
if(mysqli_connect_errno()) {
printf("Connection failed: " . mysqli_connect_error());
exit();
}
return $conn;
}
}
class user {
function check_user($id, $pass) {
$config = new config();
$conn = $config->dbconn();
$query = $conn->prepare("SELECT id, password, status FROM e_users WHERE id = ? AND password = ?");
$query->bind_param('is', $id, $pass);
try {
$query->execute();
return $query->fetch();
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I think the problem is in the $query->fetch(); because I tried return 'test'; and it works fine. Even return an array works fine.
Can anyone help me?
As The Blue Dog pointed out, fetch() returns a status flag, not the row itself. But fetch_assoc() will return a row.
Have a look here:
http://php.net/manual/en/mysqli-stmt.fetch.php
If you work with fetch, you need to bind the variables:
$stmt->bind_result($mySelectedValue_1, $mySelectedValue_2);
Here are examples with fetch_assoc():
http://php.net/manual/de/mysqli.quickstart.prepared-statements.php
So this should work fine:
$row = $res->fetch_assoc();
Im new to php so im sure this is an easy one. Im getting this error
Notice: Undefined variable: conn in C:\Dev\Webserver\Apache2.2\htdocs\EclipsePHP\thecock\php\db.php on line 23
for this code
<?php
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
$conn = new mysqli($host, $username, $password, $database);
if (! $conn) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo("all ok!");
}
function getContent($id) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) { # line 23
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
?>
How do I fix the notice?
Change your function to:
function getContent($id, $conn) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
You don't declare the "original" $conn in the scope of the function. Inside the function you only have access to variables declared inside the function or provided via parameters.
Another way would be to declare the variable as global in your function:
function getContent($id) {
global $conn;
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
But you should only do this, if there is no other way. Globals make it hard to debug and maintain the code.
See also Variable scope and why global variables are bad.
Edit:
Yes e.g. you can have a DB class:
class DB {
private static $conn = null;
public static function getConnection() {
if (is_null(DB::$conn)) {
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
DB::$conn = new mysqli($host, $username, $password, $database);
}
return DB::$conn;
}
}
Of course this is not the best implementation ;) But it should give you the right idea. Then you can get the the connection:
DB::getConnection()
conn is a global variable. To access it within a function:
function getContent($id) {
global $conn;
...
}
Otherwise the function can't see it.