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);
Related
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
I know this has been asked before but I cant seem to fix my code.
What I need is to run some php code to query mysql using mysqli for a select statement to retrieve my bcrypt hashed pass so I can compare the user input with the user hashed password. NOTE: I have not yet added mysql_real_escape_string to my $POST variables.
I've changed this code a thousand times still cant get it.
Ive even copy and pasted to a new file a simple query script using num_row
and printf($row['pass']); used echo etc..... I've used fetch array ive tried almost everything I've been all via php mysql at php.net w3c.com etc etc is my system broke? Does mysqli have a bug ? and no i dont want to switch to PDO I wont stop til this is fixed and when there is no longer sql injection vulns
Heres my code:
<?php
$conn = new mysqli('localhost', 'root', '', 'social');
if (mysqli_connect_errno())
{
exit("connection failed" . mysqli_connect_error());
}
else
{
echo "connection established";
}
$db=mysqli_select_db( $conn,'social');
if ($_POST && isset($_POST['submit'], $_POST['password'], $_POST['email']))
{
$pass = ($_POST["password"]);
$email =($_POST["email"]);
$bcrypt = password_hash($pass, PASSWORD_BCRYPT, array('cost' => 12));
}
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$fetcher = mysqli_fetch_assoc($query);
echo $fetcher;
if ($conn->query($fetcher) === TRUE)
{
echo "query has gone through now we need to store the hash<br /> for comparison";
}
else
{
echo "error did not retrieve hash info";
}
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$fetcher = mysqli_fetch_assoc($query);
Before you can fetch records from the result of the query, you need to actually perform the query. Your code should be
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$result = $conn->query($query); // This is where the query is executed
$fetcher = $result->fetch_assoc();
Two more points.
First, you don't need to call mysqli_select_db; you've already selected the database in your constructor call, so you only need to call mysqli_select_db if you want to access a different database.
Second, instead of calling mysql_real_escape_string you should look into using prepared statements, which do the same thing and also correctly handle type-matching and quoting.
Try fetching the value from database after executing the query
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$executedQuery = $conn->query($query);
if($executedQuery) {
$fetcher = mysqli_fetch_assoc($executedQuery);
echo "query has gone through ---------";
} else {
echo "error did not retrieve hash info";
}
$query = "SELECT pass FROM social WHERE id = 11"; // took the (``) out of the query and added this im assuming the value is stored in the $row variable and I may be able to use $row with the user input to verify hash via bcrypt!!!
$result = $conn->query($query);
while($row = mysqli_fetch_array($result))
{
echo $row['pass'];
echo "<br />";
}
I'm using PHP to try and select a single row from a table in my MySQL database. I've run the query manually inside phpMyAdmin4 and it returned the expected results. However, when I run the EXACT same query in PHP, it's returning nothing.
$query = "SELECT * FROM characters WHERE username=".$username." and charactername=".$characterName."";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
And when I test this in browser I get the "No results..." echoed back. Am I doing something wrong?
This isn't a duplicate question because I'm not asking when to use certain quotes and backticks. I'm asking for help on why my query isn't working. Quotes just happened to be incorrect, but even when corrected the problem isn't solved. Below is the edited code as well as the rest of it. I have removed my server information for obvious reasons.
<?PHP
$username = $_GET['username'];
$characterName = $_GET['characterName'];
$mysqli = new mysqli("REDACTED","REDACTED","REDACTED");
if(mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM `characters` WHERE `username`='".$username."' and `charactername`='".$characterName."'";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
$mysqli->close();
?>
It's failing: $mysqli = new mysqli("REDACTED","REDACTED","REDACTED"); because you didn't choose a database.
Connecting to a database using the MySQLi API requires 4 parameters:
http://php.net/manual/en/function.mysqli-connect.php
If your password isn't required, you still need an (empty) parameter for it.
I.e.: $mysqli = new mysqli("host","user", "", "db");
Plus, as noted.
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Footnotes:
As stated in the original post. Strings require to be quoted in values.
You need to add quotes to the strings in your query:
$query = "SELECT *
FROM characters
WHERE username='".$username."' and charactername='".$characterName."'";
i have tried this code to insert value into database, but i don't Know why, the value was not send into the databases. The table i have created in the mysql :
<?php
require_once "connection.php";
$conn = connect();
$db = connectdb();
mysql_select_db($db,$conn) or die (mysql_error() . "\n");
$query_usr = "select * from soalselidik";
$usr = mysql_query($query_usr,$conn) or die(mysql_error()."\n".$query_usr);
$row_usr=mysql_fetch_assoc($usr);
//to insert in database
$a1=$_POST['a1'];
$a2=$_POST['a2'];
$a3=$_POST['a3'];
$a4=$_POST['a4'];
$b1=$_POST['b1'];
$b2=$_POST['b2'];
$b3=$_POST['b3'];
$b4=$_POST['b4'];
$c1=$_POST['c1'];
$c2=$_POST['c2'];
$c3=$_POST['c3'];
$c4=$_POST['c4'];
$d1=$_POST['d1'];
$d2=$_POST['d2'];
$d3=$_POST['d3'];
$d4=$_POST['d4'];
$e1=$_POST['e1'];
$f1=$_POST['f1'];
echo $query ="insert into soalselidik (a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4,e1,f1) values('$a1','$a2','$a3','$a4','$b1','$b2','$b3','$b4','$c1','$c2','$c3','$c4''$d1','$d2','$d3','$d4','$e1','$f1')";
$result = mysql_query($query);
echo "<script languange = 'Javascript'>
alert('thankyou ! Penilaian anda diterima ');
location.href = 'home.php';</script>";
?>
'$c4''$d1'
Find that in your query and fix it :) And please do some error checking, and please stop using MySQL_* for your own good. Why should people not run any error checking mechanism that's already provided in the language and expect others to debug typos?
In case you didn't get it, there's a comma missing
How can I prevent SQL injection in PHP?
Using SQLite in PHP (thus using PDO), I have this code:
try {
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
echo "Done.<br /><b>";
$query = "SELECT id FROM Devices LIMIT 5";
echo "Results: ";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
print_r($row)."|";
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
But that does not print out any data from the SQL. I know the database has data in it and the connection is valid. If I change the query to say:
$query = "SELECT BLAHid FROM FakeDevices LIMIT 5";
Nothing changes. Nothing from SQL gets printed out again, and I see no errors even though this is clearly an invalid SQL query.
In both situations, the "Done" and "Results" gets printed out okay. How can I print out SQL errors, like if the query is invalid?
You need to tell PDO to throw exceptions. You can do that by adding the following line after you connect to the database:
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
That way you can catch all exceptions except for a possible problem with the first line, the database connection itself.