How to SELECT column value FROM table? - php

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

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

Attempting to insert new row into database using PDO

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>

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

Retrieving row from MySQL Database via PHP

Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);

Categories