Having issues retrieving data from database - php

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.

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

Echo verabllees from database in php

Im trying to echo out some variable in my database.
I have a table called channel and within that table there is a row called cookie_script. How do I echo out the verbal in the cookie_script row variables that are stored in the db.
PDO is the recommended way of communicating with your database in PHP.
First you need to setup the connection:
$host = '127.0.0.1';
$db = 'example';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$pdo = new PDO($dsn, $user, $pass);
Now you can run queries on your database:
$stmt = $pdo->query('SELECT * FROM cookie_script');
while ($row = $stmt->fetch())
{
print_r($row) . "\n";
}

query error when access clearDB database using php on Heroku

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);
}

PHP getting no response body

Username and password values are being passed into my login php file and returning as a jsonResponse string. However the jsonResponse string that is being returning is empty?
<?php
# this file will return true or false depending if passed in username and password matcha user on the system.
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$dbhost = "localhost";
$dbname = "example";
$dbuser = "example";
$dbpass = "example";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$data = array( $_POST["username"],$_POST["password"] );
$stmt = $conn->prepare("Select * FROM example where username=?, password=?");
if(mysql_num_rows($stmt)>0)
{
$row = mysql_fetch_array($stmt);
if($_POST["password"] == $row["password"])
{
echo "loggedIn";
}
else
{
echo "passwordNotValid"; alert
}
}
else
{
echo "usernameNotValid";
}
if(!$stmt)
{
print_r($dbh->errorInfo());
}
}
?>
You have a lot of issues...
Remove the alert from that line
echo "passwordNotValid"; alert
Close the quotes like shown
echo "usernameNotValid";
Remove a } brace from the last line..
Apart from these issues... The (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead,the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
you are mixing mysql_* with PDO. Here is a complete example of PDO. you should use PDO like this.
$dbhost = "localhost";
$dbname = "example";
$dbuser = "example";
$dbpass = "example";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("Select * FROM example where username=?, password=?");
use your username and password varaibles in bind params
$stmt ->bindParam(':username', $username, PDO::PARAM_STR);
$stmt ->bindParam(':password', $password, PDO::PARAM_STR);
$stmt ->execute();
$result = $stmt ->fetch(PDO::FETCH_ASSOC);
and use $result in your page
Syntax error in line
echo "usernameNotValid;
your code is most likely never executed.

Categories