Lately I've been struggling with a problem and I have no idea what I'm doing wrong.
I want to add information to a database in SQLite3 from a PHP script. To achieve that since I am new to this I created a database, put some info in there and with the following script I am able to read the data:
<?php
$db = new SQLite3('mydatabase.db');
$results = $db->query('SELECT * FROM temps');
while ($row = $results->fetchArray()) {
var_dump($row);
}
?>
Next step I tried to ADD info to the database from PHP with this script:
<?php
$db = new SQLite3('mydatabase.db');
$db->exec("INSERT INTO temps (zone,temperature) VALUES ('maia',66)");
echo "something";
}
?>
This script does NOT add anything to the database and the echo is displayed.
After reading a bit I changed the last script to something like this:
<?php
try
{
$db = new PDO('sqlite:mydatabase.db');
$db->exec("INSERT INTO temps (zone,temperature) VALUES ('maia',66)");
echo "Row Inserted\n";
}
catch(PDOException $e)
{
print $e->getMessage();
}
?>
There is no exception displayed, the echo "Row Inserted" is displayed and nothing is added to the database.
Can someone give me an hint about what am I missing please?
Pretty much appreciated.
Related
hello I want to be able to display only the data from my database where the cookie id is equal to that of the database
For now it does not work, the cookie is well stored because I can display it is the sql part which does not work, I have no error code in the console
I tried a first code which did not work then I went on google to seek examples of codes which would have similarities to mine, I did not find anything convincing, I searched on stack over flow I found a topic that partially referred to it, so I applied the code but it didn't work.
here is the site where it is hosted : comparateur.innovations-Ux.com/compare.php
here is my code :
echo $_COOKIE["user_id"];
$user = "innovatiesvictor";
$pass = ".................";
try {
$dbh = new PDO('mysql:host=.............;dbname=innovatiesvictor', $user, $pass);
foreach($dbh->query("SELECT * from QUESTIONNAIRE WHERE SID = '{$_COOKIE["user_id"]}' ") as $row)
{
echo 'hello world';
}
$dbh = null;
} catch (PDOException $e) {
print "Erreur !: " . $e->getMessage() . "<br/>";
die();
}
?>
try to add a variable instead:
$cookie = $_COOKIE["user_id"];
and then turn this:
foreach($dbh->query("SELECT * from QUESTIONNAIRE WHERE SID = '{$_COOKIE["user_id"]}' ") as $row)
into this:
foreach($dbh->query("SELECT * from QUESTIONNAIRE WHERE SID = '$cookie'") as $row)
Hope it helps you.
If I am correct you are trying to foreach wrong object.
After you query you set fetch mode, for ex.:
$q->setFetchMode(PDO::FETCH_ASSOC);
Then you loop over rows with
<?php while ($row = $q->fetch()): ?>
That is first example I find.
https://www.mysqltutorial.org/php-querying-data-from-mysql-table/
Hope it helps.
I am writing a application that will read values from an SQlite3 database and display them through webbrowser with PHP. This is new to me and I have tried several things but can't seem to get it to work! The values are listed as REAL in the database, which should be PARAM_STR.
<?php
$db = new SQLite3('/home/pi/ECE522/test.db');
if(!$db) {
echo $db->lastErrorMsg();
} else {
echo "Opened DATABASE!";
$query = $db->prepare('SELECT df1, df2 FROM PLCValues');
$query->bindParm('df1', $df1,PDO::PARAM_STR);
$query->bindParm('df2', $df2,PDO::PARAM_STR);
$query->execute();
var_dump($df1);
var_dump($df2);
echo $df1;
echo $df2;
}
?>
On the webpage I get "Opened DATABASE!" but nothing else?
Thanks for any ideas!
You don't define the $df1 and $df2 before executing the query, that you bind as param at
$query->bindParm('df1', $df1,PDO::PARAM_STR);
$query->bindParm('df2', $df2,PDO::PARAM_STR);
Do you realy need that?
If you just want to select all values in columns 'df1' and 'df2' from PLCValues table, I think you need something like this:
$res = $db->query("SELECT df1, df2 FROM PLCValues");
while (($row = $res->fetchArray(SQLITE3_ASSOC))) {
var_dump($row);
}
For more information see examples from http://php.net/manual/ru/sqlite3stmt.bindparam.php
If you want to select values with certain df1, I think you need something like this:
$stmt = $db->prepare("SELECT df1, df2 FROM PLCValues WHERE df1=:df1");
$stmt->bindParam(':df1', '[WHAT_YOU_WANT_TO_SELECT]', [YOUR_DATA_TYPE]);
$result = $stmt->execute();
var_dump($result->fetchArray());
I need some help with my PHP. I have a trouble with fetching the data from the database. I have hired a PHP developer who did not do his job properly that he have messed up the code which make it don't work so I need some help to fix the issue to get it working again.
When I try this:
//open the database File
$db = new SQLite3('myChannel.db');
if(!$db)
{
echo $db->lastErrorMsg();
}
else
{
$channel_name = $_GET['channels'];
$sql ="SELECT channel, title, start_date, stop_date, description FROM programs WHERE channel='$channel_name'";
$results = $db->query($sql);
while ($row = $results->fetchArray())
{
print_r($row);
}
What happen with the code is it will not fetching the matched data from the database as it will not do anything. I think there is something wrong with the $sql variable.
What I'm expecting to do is I want to look for data in the database where I use the variable called $channel_name, then I want to fetch the matched data to output them in my PHP.
Can you please help me how I can fetch the matched data in the database?
Try this code based on the SQLite PHP docs
class MyDB extends SQLite3 {
function __construct() {
$this->open('myChannel.db');
}
}
$db = new MyDB();
if (!$db) {
echo $db->lastErrorMsg();
} else {
$channel_name = $_GET['channels'];
$sql = "SELECT channel, title, start_date, stop_date, description FROM programs WHERE channel='{$channel_name}'";
$results = $db->query($sql);
while($row = $results->fetchArray(SQLITE3_ASSOC) ) {
print_r($row);
}
}
I changed a few things. I turned your database connection into a class, and I changed your while to include SQLITE3_ASSOC.
Warning: OP's code and as a result this answer has code that is
vulnerable to SQL Injection!
Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>
I want to get stings form a mysql server to use as text on my webpage.
That way I can edit the text without editing the html file.
Problem is that the code I have to get the string is quite long, and I don't want to paste it everywhere on the page.
I would also like a tip on how to get just one datafield from the server, and not the whole column like I do here.
So this is what I got. And what I think is to write a function I can call from all the places I want the webpage to get a string or field from the sqlserver. But I don't know how. Can anyone help me?
<?php
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else
{
echo "error";
}
$con->close();
?>
Problem is that the code I have to get the string is quite long, and i
dont want to paste it everywhere on the page.
Put the code into a function, call that function wherever you need to. Then it is just a single line you have to insert.
PHP:
<?php
function connect() {
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function renderContent($con) {
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0))
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else {
echo "error";
}
}
HTML:
<?php $con = connect(); ?>
[...]
<div>
<?php renderContent($con); ?>
</div>
[...]
I would also like a tip on how to get just one datafield from the
server, and not the whole coloumn like i do here.
Not the whole column would mean not all rows, but one or some selected ones. That means you are looking for sqls ''WHERE'' clause.
SELECT topic FROM web_content WHERE <where clause>;
Where <where clause> is some clause to narrow down the result set. For example you can narrow down to topics containing some string: ... WHERE topid LIKE '%word%'; or by the IDs are a date range of the entries in your table. You should take a look into the documentation of the query syntax for an explanation: http://dev.mysql.com/doc/refman/5.0/en/select.html
Obviously all of this is just a rough sketch of what you are looking for. Lots of things need improving. Using exceptions for error handling is one thing, just to give an example...