PHP MySQL query returning random values - php

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!!

Related

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

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.

MySQL PHP Column Update Query

i would really appreciate if anyone can help me out with this mysql php problem of which i have no idea how to do it.
I Have a column named = 'x'
The text of that column 'x' is = "yz,zz,zy"
I want to edit the value of the column 'x' to = "yz,zyz,zy".
Now how do i add that 'y' in the middle term between yz and zy using CONCAT.
Regards.
You haven't provided any code or an attempt for us to go off of something so I'll give you a brief way of doing it. Look up PDO here This is a really easy to follow and secure way to manipulate data in your database using php. Again as you haven't given me much to go off i'm unsure if you want to just set something at specific count of characters along OR if you want to just update the entire thing, SO i'll help you with the latter as it will help give you some base understanding.
Please read into PDO further as this is just an example further down the line and will not run if you just blindly copy and paste it in.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE table SET x='yz,zyz,zy' WHERE id= 1"; // No clue if you've even given anything IDs
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
As you haven't really provided any Schema of the table you are updating this is the best I could provide based off of what you have given me.. try to include as much information as possible as I'm unsure if this is what you even want

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

Issues with php connection to mySQL database

Hy everyone, I can't wrap my head around this. I'm trying to get some data from a table using PDO. this is my code:
//in db.php I have the connection:
$host = 'localhost';
$db = 'APL';
$dbuser = '';
$pass = ' ';
try{
$conn = new PDO("mysql:host=$host;dbname=$db", $dbuser, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//in my file I have this:
$id = $_GET['id'];
$sel_sql = "SELECT * FROM users WHERE id =:id";
$stmt = $conn ->prepare($sel_sql);
$stmt -> bindParam(':id', $id);
$stmt -> execute();
$result = $stmt -> fetchAll(PDO::FETCH_ASSOC);
The problem is that print_r($result) returns '1' (just the value 1, therefore I can't access any data stored in the table) as long as $_SESSION['user'] is set.
The whole data-retrieving worked just fine if the $_SESSION['user'] is not set.
Can someone please explain why this is happening? (I'm fairly new to all this and I'm really trying to understand why some issues occur).
Thank you!
The fetchAll function should be returning either an array, or a boolean FALSE.
You report that print_r($result) is displaying an integer value of 1.
I don't see how that's possible, unless you are assigning a different value to $result. Try relocating print_r($result) to immediately follow the assignment from fetchAll.
(My suspicion is that $result is being assigned a value of 1 elsewhere in your code, before you do the print_r. If there were "Issues with php connection to MySQL database", we'd be expecting to see a PDO error of some sort.)
NOTE: I don't think PDO::FETCH_ASSOC is a defined fetch style for the fetchAll function. (fetchAll has different fetch styles than fetch.)
Just in case someone else stumbles upon this, between the $result variable and the print_r($result) I had an include_once(); statement (which was wrongly put there in the first place).
Thank you everyone for your answers.

How to fetch single row with PDO from href link, receives fatal error: Call to a member function prepare() on a non-object?

I am starting to learn php PDO because I've read that it is more efficient and secure.
I could do the following with simple mysqli but am having trouble making it work with PDO.
PID stands for an id number.
fname stands for: first name.
lname stands for: last name.
age stands for ... age.
Basically I have an index.php that contains links from a test table called "persons" inside of the database drinks. When I click on the link which shows the fname of every row, it goes to insertcarbonated.php which is then supposed to $_GET['fname']; of the link and search up that specific row. However, my code in insertcarbonated.php is not working and I am not familiar enough with PDO to know exactly why, I would like some enlightenment on this because I literally begun learning PDO yesterday. :(
Here is my insertcarbonated.php:
<html>
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'theusername';
/*** mysql ***/
$password = 'thepass';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=drinks", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
/*** The SQL SELECT statement ***/
$fname = $_GET['fname'];
//is _GET even working with PDO?
$STH = $dbh-> prepare( "SELECT * FROM persons WHERE fname LIKE '$fname'" );
/***as Joachim suggested, I had actually two different variables here, however, it
did not solve the issue **EDITED** from ($DBH to $dbh)****/
$STH -> execute();
$result = $STH -> fetch(0);
//$result should print out the first column correct? which is the person's ID.
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<head>
</head>
<body>
<p><?php print $result; ?></p>
//me trying to print out person's ID number here.
</body>
</html>
As previously mentioned, I'm not sure where my error is, I get fatal error:
Call to a member function prepare() on a non-object?
and If I try to not use that function, my page is simply blank and nothing prints out.
Basically I would just like to print out different bits of information from that row (that is from it's relevant link in index.php). I would like to know how to solve this using PDO.
Here is the previous question I asked, and it was solved but not with PDO.
Previous question
You could do something like this...
try {
$dbh = new PDO("mysql:host=$hostname;dbname=drinks", $username, $password);
$fname = $_GET['fname'];
$sth = $dbh->prepare("SELECT * FROM persons WHERE fname LIKE ?");
$sth->execute( array($fname) );
$result = $sth->fetch(PDO::FETCH_OBJ); // or try PDO::FETCH_ASSOC for an associative array
}
catch(PDOException $e)
{
die( $e->getMessage() );
}
In the HTML part you can do print_r($result) and you will see the exact structure of your results.
Comments: one of the best reasons to use PDO is the automatic escaping of the dynamic user inputs, like $fname here, so you should use it. Also, with $sth->fetch($param) the $param is not the column number but the type of the fetch method PDO will use (see PHP manual). Depending the method, you can get the PID of the result by $result->PID in case of PDO::FETCH_OBJ or by $result['PID'] when using PDO::FETCH_ASSOC. I hope this helps.

Categories