unable to update SQL table with php program - php

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

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 = ?");

Inserting ID from primary col to another table

I want to insert 2 tables columns ids to another table
I got the query but there is the annoying error.
I tried to solve this problem for hours none worked :(
This code:
$query = "INSERT INTO
groups(
group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count
)
VALUES(
$group_shcool_id,
$group_teacher_id,
'$group_name',
'$group_note',
'$group_system',
'$group_students_count'
)";
this old:
<?php
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
mysqli_query($con, "SET NAMES 'utf8'");
}
?>
this new:
<?php
// if you are using php just don't forget to add php tags though
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
//using try catch statements
try{
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}
?>
its connects successfully but all my code use the old one, how to change to convert it? I dont know what pdo I like to learn it, it seems more pro type, but is there solution for this site only using mysqli?
sorry for the long post this is my 1st one, dont know how to explain enough
Thanks
give this error :
QUERY FAILED .You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , 'test', '', 'test' at line 11
I thought it will work fine like this but I think the problem with the query syntax.
Just an advice try to use PDO prepared statements example below:
$query = "INSERT INTO groups(group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count)
VALUES (:gsid,:gtid,:gname,:gnote,:gsystem,:gstudcount)";
//assuming $conn is your object variable name for database connection
$stmnt = $conn->prepare($query);
$stmnt->execute(array(':gsid'=>$group_school_id,
':gtid'=>$group_teacher_id,
':gname'=>$group_name,
':gnote'=>$group_note,
':gsystem'=>$group_system,
':gstudcount'=>$group_students_count));
//to check if you have inserted data into your table
$rows = $stmnt->rowCount();
echo "Inserted ".$rows." row";
the :gsid are placeholders for your variables, also make sure that each variable passed are inline with column datatypes in your database
//if you are using php just don't forget to add php tags though
$dbhost = "localhost";
$dbname = "whatevername";
$dbuser = "root";
$dbpass = "";
//using try catch statements
try{
$conn = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}

I am trying to retrieve data from my database using PDO Fetch object

I am trying to retrieve data from my database using PDO Fetch object and it says
Fatal error: Uncaught Error: Call to undefined method mysqli_result::execute()
what I'm doing wrong
This is what I have tried
<?php
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "messages_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$getquery = $conn->query('select col_name from db where id = 2');
$getquery->execute();
$result = $getquery->fetch(PDO::FETCH_OBJ);
?>
<div><?= $result->col_name; ?></div>
Firstly, don't mix PDO and mysqli. Stick to one. Here's a PDO example. You first need to create a new PDO object. and connect to DB at the start
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "dbname";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername,
$dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
$rtrv = "select col_name from db where id = 2"
$stmt = $pdo->prepare($rtrv);
//Execute.
$stmt->execute();
//Fetch.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// Do whatever you want after this

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

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.

Categories