SQL How to make a select query with a var php condition - php

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.

Related

How to SELECT column value FROM table?

Here's my code:
<?php
//recently added
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if ($result == 1){
?>
<script>
jQuery(document).ready(function(){
jQuery(".eltdf-psc-slide").addClass("no-background");
});
</script>
<?php
}
//=============
?>
Basically what I'm trying to do is checking and see if the value stored in the $shadowless_background_table "DB" is == 1 and I only want that column (background). I have browse the web, but what I see are examples with while loops which I was wondering if I could do something like this instead.
If you want to fetch a single record based on a condition you can do this -
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if (mysql_num_rows($result)>0){
$fetchedColum = mysql_result($result, 0, 'COLUMN_NAME');
}
There are couple of issues with your code.The first thing that i have noticed is that you are using mysql API instead of PDO.I don't blame you since the internet is full of old tutorials and you probably didn't have a chance to get some guidance.
MySql is getting old It doesn't support modern SQL database concepts such as prepared statements, stored procs, transactions etc... and it's method for escaping parameters with mysql_real_escape_string and concatenating into SQL strings is error prone and old fashioned.
Organize your project better.
As i have seen from this example you probably have a poor project organization.You should consider reading about PSR Standards
And to go back to your question ,and to update it a bit.
Instead of doing
mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
I would do it this way:
<?php
$host = "localhost";
$username = "user name of db";
$password = "password of db";
$dbname = "database name ";
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//your data
$id = 1; // id
$stmt = $conn->prepare("SELECT background FROM database_name WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row) {
echo $row["row_name"];
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
Go read more about PHP in general ,it will help you out a lot.The biggest problem is that there are so much wrong tutorials and references or they are just old.And people learn from wrong sources.
I had the same problem ,but thanks to right people on this site i have managed to learn more.
My suggestion is that you read about PSR,PDO and PHP in general!!!
Also a thing you should consider reading about is security in php.
Good luck mate :D

PHP MySQL query returning random values

I'm very noob in php and SQL and I want to solve this weird problem I'm facing :S
Here I show you the code:
<?php
require 'dbdata.php';
$gp = $_POST["GP"];
$DBH1 = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$RQ1 = $DBH1->prepare("SELECT GgID,ID FROM Usuarios WHERE GgID='$gp'");
$RQ1 -> execute();
$row1 = $RQ1->fetch(PDO::FETCH_BOTH);
if(($RQ1 -> rowCount()) >0){
echo $row1[1] . "////##";
echo "Login";// Username is taken
$DBH = null;
}
else{
echo "0" . "////##";
echo "Register";
$DBH = null;
}
?>
Now I want to explain you what should it do and what randomly do. The script is a simple one, I make a post with a string, that string has to be on the database and the script return me the content of the ID column, BUT, a 10% times it returns me a random value that has no relation with the post i do but 90% times returns the correct value... what's wrong here?
PS: I have a similar script that runs simultaneously but with other post, is this related with the error?
Thank you in advance!!

Issues with PHP while statement

I'm attempting to run a while statement that will set a column in a mysql database, based on a uniqueID.
I've done this many times, and I'm not sure what I am doing wrong this time.
Basically, it works properly until I actually tell it to save the table. Here is my code
$alertAdmin = mysqli_query($con, "SELECT * FROM tickets WHERE notified='0'");
$tcheckNotifs = mysqli_num_rows($alertAdmin);
if($tcheckNotifs > 0) {
echo "test<br><br>";
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
$sql = "UPDATE tickets SET `notified`='1' WHERE `UniqueID`='$Unique'";
//mysqli_query($con, $sql);
}
}
And this works for echoing the UniqueID, and it echos the correct one. The problem comes in when I uncomment the mysqli_query($con, $sql);
in which case, nothing inside the loop is echo'd, but it DOES save the database.
For example:
Lets say this while statement loops through and finds 3 iterations of rows that have notified equal to 0 (UniqueID's 29, 26, 25), while the mysqli_query is commented, it will display these numbers on the page just fine. But as soon as I uncomment it, the database will save but it does not display any of the rest of the while loop on the page.
I need this desperately, because I plan to send a desktop notification at the same time the loop is played.
FOLLOW UP:
It also does not display the echo "test<br><br>"; on the page when the query is uncommented either.
Another follow up:
The query is saving all the data like its meant to. The problem is nothing else inside the tcheckNotifs IF statement are showing (echo's and such), like they aren't being executed. Almost like the end of the while statement is executing before anything else, including the "test" echo before the while statement.
Could anyone help me figure out why this isn't working as expected?
Here is all of my current code, with some suggestions from you guys added in, but still not working properly.
The while statement will save the query, but no other output is shown on the page.
$configs = include("config.php");
$con = mysqli_connect($configs['SQL-Host'], $configs['SQL-User'], $configs['SQL-Pass'], $configs['SQL-Database']) or die("Error " . mysqli_error($con));
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$alertAdmin = mysqli_query($con, "SELECT * FROM tickets WHERE notified='0'");
$tcheckNotifs = mysqli_num_rows($alertAdmin);
if($tcheckNotifs > 0) {
echo "test<br><br>";
flush(); ob_flush();
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
updateTickets($con, $Unique);
}
echo "test<br><br>";
}
function updateTickets($con, $id){
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$id";
mysqli_query($con, $sql);
}
FINAL UPDATE
With the help of Alex Andrei as well, we moved to PDO
$dsn = 'mysql:dbname=domains;host=localhost';
$user = 'root';
$password = '';
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$st = $db->prepare('SELECT UniqueID FROM tickets WHERE notified=0');
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $d){
echo $d['UniqueID'] . "<br/>";
$id = $d['UniqueID'];
$st = $db->prepare("UPDATE tickets SET notified=1 WHERE UniqueID=$id");
$st->execute();
}
SECOND UPDATE
Try putting your query in a variable and run the loop like this...
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$Unique";
$update = mysqli_query($con, $sql);
}
UPDATE
There is a chance the query runs first like you said. Maybe you can create an independent function to run the query and call the function from inside the while loop.
function updateTickets($con, $id){
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$id";
mysqli_query($con, $sql);
}
And your loop would look like this...
while($row = mysqli_fetch_array($alertAdmin))
{
$Unique = $row['UniqueID'];
echo $Unique.' ';
updateTickets($con, $Unique);
}
ORIGINAL ANSWER
I would modify your query like this...
$sql = "UPDATE tickets SET notified=1 WHERE UniqueID=$Unique";
You do not need all the back ticks nor single quotes here. Might be causing an issue.
Also, I assume 1 is an integer so no need to quote that.
The Fix: PDO OF COURSE!
$configs = include("config.php");
$dsn = 'mysql:dbname='.$configs['SQL-Database'].';host='.$configs['SQL-Host'].'';
$user = $configs['SQL-User'];
$password = $configs['SQL-Pass'];
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$st = $db->prepare('SELECT UniqueID FROM tickets WHERE notified=0');
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $d){
echo $d['UniqueID'] . "<br/>";
$id = $d['UniqueID'];
$st = $db->prepare("UPDATE tickets SET notified=1 WHERE UniqueID=$id");
$st->execute();
}
$sql = "UPDATE tickets SET notified='1' WHERE UniqueID='$Unique'";
The error I think it's here. You can't use $Unique between single quotes (although you already are between double quotes).
Try to fixing this replacing the line with:
$sql = "UPDATE tickets SET `notified`='1' WHERE `UniqueID`=$Unique";
Firstly in your query you are passing a string in: ...WHERE "UniqueID"="$Unique" because of the quotes around your php variable. So your query looks like this: WHERE UniqueID = "10". Not a big deal but generally if your looking up a number your should drop the quotes.
And i suspect something is causing your query in the loop to fail, so add something to check for errors:
if(!$queryResult){
echo $con->error;
}
Run the loop and see if something is causing errors in your query. But really you should get rid of most of the backticks you have in your queries.

Can't access to SQLite3 database from php

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.

Parsing variables through PHP with Flash

I'm making chat in flash as3 with php and mysql database.
However I don't know php at all, and got problem with updating messages.
for now my php file looks like this:
$caster = $_POST['caster'];
$msgText = $_POST['msgText'];
$sendTime = $_POST['sendTime'];
$query = "INSERT INTO chat VALUES ('','$sendTime','$caster','$msgText')"
mysql_query($query);
$query="SELECT * FROM chat";
$result=mysql_query($query);
$cast=mysql_result($result,1,"caster");
mysql_close();
$returnVars = array();
$returnVars['success'] = $success;
$returnVars['caster'] = $cast;
$returnString = http_build_query($returnVars);
echo $returnString;
And my question is how to loop for all already sent chat messages to send them to flash.
I can only do it with one, but I need whole bunch of them to be loaded.
Thanks
What you are looking for is "fetchAll". Note that your code is open to SQL injection, it is very easy to drop your database by passing evil values to the PHP script. I have changed the code therefore from the deprecated Mysql extension to PDO. PDO will to the escaping of the values for you.
Read more on PDO in the PHP manual (Lots of examples over there).
Also note that you have to adapt the following code snipped as I could not guess how the field names of the chat table in your database are named. So you have to adapt the insert statement below.
// database config parameters
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "";
try {
// try to set up a db connection
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
// insert the data using PDO's prepared statements
// you have to adapt this line to the field names of your chat table!!
$sql = "INSERT INTO chat (sendtime,caster,msg) VALUES (:sendtime,:caster,:msg)";
$sth = $db->prepare($sql);
$sth->execute(array(
':caster' => $_POST['caster'],
':sendtime' => $_POST['sendTime'],
':msg' => $_POST['msgText']
));
// Get everything
$sth = $db->prepare("SELECT * FROM chat");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
// your code to format and return the data goes here
print json_encode($result);
}
catch (PDOException $e) {
// if anything related to the database goes wrong, catch the exceptions
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$db = null;
The Actionscript will receive a JSON object looking similar to this:
[
{
"sendtime":"2013-04-14",
"caster":"person1",
"msg":"Message 1"
},
{
"sendtime":"2013-04-15",
"caster":"person2",
"msg":"Message 2"
}
]
As you can see the JSON has no specific variable name like in the version with GET used in the question (the method used in the question does not work for large result lists).
So how do you work with the JSON document in Actionscript? I am not an actionscript programmer, but this Stackoverflow post looks like a reasonable answer to this problem:
Get and parse JSON in Actionscript

Categories