query error when access clearDB database using php on Heroku - php

I can access clearDB database well by using Mysql Workbench.
But when I query database by using php on Heroku, it always fail.
This is my code:
$url=parse_url(getenv("CLEARDB_DATABASE_URL"));
$dbhost = $url["host"];
$dbuser = $url["user"];
$dbpass = $url["pass"];
$dbname = substr($url["path"],1);
mysqli_connect($dbhost, $dbuser, $dbpass);
mysqli_select_db($dbname);
$sql = "SELECT * FROM `user_info` WHERE `user_account`='".$user_account."'";
$result = mysqli_query($sql) or die('MySQL query error');
user_account is a table in the database, $user_account is a input variable from client user
help me
thanks

You're not passing the link to mysqli_query(). You need to either do that, or use the object oriented style and call query() on the connection.
You also have a possible SQL injection there, because $user_account could contain "foo' OR 1 OR '", returning all rows (and that's just a simple, not very evil case), so you should escape that using mysqli_real_escape_string(), or even better, use prepared statements.
Finally, instead of or die(), how about extracting error information properly, or even configuring mysqli to throw exceptions?
<?php
$url = parse_url(getenv("CLEARDB_DATABASE_URL"));
$server = $url["host"];
$username = $url["user"];
$password = $url["pass"];
$db = substr($url["path"], 1);
$conn = new mysqli($server, $username, $password, $db);
$sql = "SELECT * FROM `user_info` WHERE `user_account`='".$conn->real_escape_string($user_account)."'";
if($result = $conn->query($sql)) {
foreach($result as $row) {
// ...
}
} else {
throw new Exception($conn->error);
}

Related

Getting error when calling connect as function in prepare statement

EDIT. My error ONLY occurs when calling database connection as a function, if I call my database connection normally, the error do not occur.
I'm trying to execute a prepare statement with database connection as a function so that it can be reused inside other functions. Executing normal SQL codes work when using database connection function but I'm getting errors when I try to use in a prepare statement.
This is my code.
function connect(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
if (connect()->connect_error) {
die("Connection failed: " . connect()->connect_error);
} else {
echo "GOOD";
}
$val = "1";
$stmt = connect()->prepare("SELECT * FROM countries WHERE id = ?");
$stmt->bind_param("s",$val);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['name'];
}
$stmt->close();
When connecting database as a normal variable such as this works.
$stmt = $conn->prepare("SELECT * FROM countries WHERE id = ?");
However, I get "Call to a member function fetch_assoc() on bool" whenever I tried to call my connection as a function.
What am I doing wrong with this code?
After searching for a while and based on this answer, I was able fix my problem by declaring a variable for connection. However, this doesn't explain why directly calling connect doesn't work. Can somebody explain to me why the first way doesn't work?
$db = connect();
$stmt = $db->prepare("SELECT * FROM countries WHERE id = ?");

unable to update SQL table with php program

I have installed XAMPP and ensured that all the servers are running. I'm completely new to PHP and SQL
I configured a local database called test and a table called sensor.
I have added a user called arduino with a password.
pls ignore the comments
<?php
// Prepare variables for database connection
$dbusername = "arduino";
$dbpassword = "xxx";
$server = "localhost";
// Connect to your database
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
// Prepare the SQL statement
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
// mysql_query($sql);
?>
I want to use this set up to fetch data from arduino. Before connecting this set up to arduino, I wanted to ensure that this would be able to fetch data by passing http://localhost/write_data.php?value=100 to the browser. I was expecting that this would update the table with id, timestamp and value (of 100). It did not.
I had trouble with $dbconnect = mysql_pconnect($server, $dbusername, $dbpassword); and hence replaced that with $db = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
I also had trouble with mysql_query($sql);. So I have commented it out for now.
How can I get this to work? Where can I find easy to follow documentation for MySql replacements?
Updated Code based on answers
<?php
$dbusername = "arduino";
$dbpassword = "test";
$server = "localhost";
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
$stmt = $dbconnect->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
print "procedure returned $return_value\n";
?>
Brother checkout this example.. you have to bind get parameter in your query
Example:-
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM `$table` WHERE `$fieldname`=:id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
You are not executing the SQL statement in your code. Try executing the below implementation :
$db = new PDO('mysql:host=localhost;dbname=rfid_db;charset=utf8mb4', 'username', 'password');
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //optional
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //optional
$stmt = $db->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
Also for detailed study on PDO try referencing the documentation here http://php.net/manual/en/pdo.prepared-statements.php

Having issues retrieving data from database

I am trying to figure out how to connect and fetch data from a database using PDO, I have been using mysqli but figure PDO is the way to go now a days.
Here is my code, looks like I can connect but I am not able to grab any data.
<?php
$host = "localhost";
$user = "";
$pw = "";
$dbName = "test";
$numberID = 1;
$pdo = new PDO("mysql:host=$host", $user, $pw);
if ($pdo){
echo "Connected";
$smt=$pdo->prepare("SELECT from sample WHERE id=:ID");
$smt->bindParam(":ID", $numberID);
if($smt->execute()){
$rows=$smt->fetchAll();
print_r($rows);
}
}
There is syntax error in your query. You are missing * or specific column names which you want to select
$smt=$pdo->prepare("SELECT * from sample WHERE id=:ID");
and you have not used database name in your connection. Try to use this
$dbo = new PDO('mysql:host='.$host.';dbname='.$dbName, $user, $pw);
You must specify the column names or * after the SELECT and use the database while creating the PDO object. The working code is provided
<?php
$host = "localhost";
$user = "";
$pw = "";
$dbName = "test";
$numberID = 1;
$pdo = new PDO('mysql:host='.$host.';dbname='.$dbName, $user, $pw);
if ($pdo){
echo "Connected";
$smt=$pdo->prepare("SELECT * FROM sample WHERE id=:ID");
$smt->bindParam(":ID", $numberID);
if($smt->execute()){
$rows=$smt->fetchAll();
print_r($rows);
}
}
?>
This is really silly, but have you confirmed PDO is installed? Check the error logs to see if it's barking about a missing pdo driver.

mysqli does not execute Select statement

I have the code bellow. When I use this code without the WHERE clause, all the users from the table are displayed, as expected. But when the WHERE clause is used, nothing is displayed.
What could be the cause and how can I fix it?
Thank you!
function requestUser($user) {
$DBHost = "localhost";
$DBUser = "dbUser";
$DBPass = "dbPass";
$DBName = "dbName";
$db = new mysqli($DBHost, $DBUser, $DBPass, $DBName);
if ($db -> connect_errno > 0) {
$lbOK = false;
}
else {
$lbOK = $db -> set_charset('utf8');
}
if ($lbOK) {
$id = NULL;
$user_name = NULL;
$user = htmlentities($user, ENT_QUOTES);
$lcSQL = "SELECT `user_name` FROM `users` WHERE user_name=?";
$stmt = $db -> prepare($lcSQL);
$ok = $stmt -> bind_param('s', $user);
$ok = $stmt -> execute();
$ok = $stmt -> bind_result($user_name);
while ($row = $stmt -> fetch()){
echo $user_name;
}
$stmt->close();
}
}
There are many major faults with your code, some of them can be responsible for the problem, and some not. But nevertheless, they all have to be corrected
Never connect co database inside of an application function. Connect somewhere in the bootstrap file, once, and use that single connection throughout all the application.
Do not use htmlentities with whatever database interactions. It may easily spoil the data
Always check for the the errors
Do not use mysqli, it is unusable. Use PDO instead.
$dsn = "mysql:host=DBHost;dbname=DBName;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,$DBUser, $DBPass, $opt);
function requestUser($user) {
global $db;
$sql = "SELECT `user_name` FROM `users` WHERE user_name=?";
$stmt = $db->prepare($sql);
$stmt->execute(array($user));
return $stmt->fetchColumn();
}
echo requestUser($user);
if it still doesn't work, verify it this way
$sql = "SELECT `user_name` FROM `users` WHERE user_name='$user'";
var_dump($sql);
and then try to run in console/phpmyadmin to find out what's wrong with your data/value

Error calling member function "FETCH_ASSOC" - what is wrong with my code?

I am trying to connect to a PHP PDO and run a simple query on the data but I run into an error about the object not being created? I'm trying to make this as simple as possible and have been advised not to make a singleton database class and instead define the Database PDO whenever I need it, which is for this initial (simple) query.
Here is the error I am getting. What do I need to do to fix the code?
Fatal error: Call to a member function fetch() on a non-object in/home/...index.php on line 11
<?php
$dbhost = "localhost";
$dbname = "x";
$dbuser = "y";
$dbpass = "z";
$db = new PDO("mysql:host=$dbhost;db_name=$dbname", $dbuser, $dbpass);
$query = $db->query("SELECT * FROM tablename");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
echo $row['field_name'],'<br>';
}
?>
And please let me know if you have a better way to select data from a mysql table using php. Trying to learn PDO and not mysqli. Thanks
You have to choose between ->query or ->fetch. You can't mix both method.
->query():
$sql = 'SELECT * FROM tablename';
foreach ($db->query($sql) as $row) {
echo $row['field_name'],'<br>';
}
->fetch():
$sth = $db->prepare("SELECT * FROM tablename");
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row['field_name'],'<br>';
}
Probably there is a problem with the query, like a typo or the table does not exist.
Then $query is not a PDOStatement but false and you can't call false->fetch().
There's your typo:
$db = new PDO("mysql:host=$dbhost;db_name=$dbname", $dbuser, $dbpass);
Should be:
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
After fixing the typo this code works perfectly:
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$query = $db->query("SELECT * FROM wp_blogs");
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
var_dump($row).'<br>';
}

Categories