Checking variable in database via php (if statements) - php

So after a long rest of coding(around 5months) i started to forgot some of the codes and i need help with this one, i cant find in the google with this topic, etc
code :
<?php
$num1 = "0";
$database = mysql_connect('x', 'x', 'x') or die ("Error x01");
mysql_select_db('x') or die ("Error x02");
$SQL1 = "Select * FROM 'server_status' WHERE on = '$num1'";
$result_id1 = #mysql_query($SQL1) or die("DATABASE ERROR!");
$total1 = mysql_num_rows($result_id1);
if($result1){
echo "Server is under maintenance";
}
?>
right here i have a code where i'am gonna check the variable "on" in "server_status" table in my msql
somehow even when i have my "on" variable on 0 (int not bool [join_protection is on int too]) it still gives out the die which is
or die ("DATABASE ERROR!");
i can't find how to fix that i played around with it and not managed to make it work
here's the result
i'm looking forward for your answer
thanks for passing by and helping me
regards,
-itsproinc

You're using single quotes which are not the correct Identifier Qualifiers around your table name, remove them.
FROM server_status
or use ticks: (which resemble quotes, but are not the same).
FROM `server_status`
Plus, you are using a MySQL reserved word, being on for your column name and it needs to be wrapped in ticks.
$SQL1 = "Select * FROM `server_status` WHERE `on` = '$num1'";
Plus, as I stated in comments:
This doesn't help you or die ("DATABASE ERROR!"); this does mysql_error() and remove the # in #mysql_query it's an error suppressor.
Deprecation notice:
mysql_ is deprecated and will be removed from future PHP releases.
Use mysqli_ or PDO.
Better yet:
Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.

Related

Cannot retrieve and display images from mysql via php after upgrade to php7

I hope this question hasn't been posted/answered elsewhere. Searching didn't yield any satisfactory results so I am posting in the hope that someone will be able to help me out.
I used the code below to display images from mysql database. Used to work perfectly with php 5.6. Today I upgraded to php7 and I simply cannot get it to work.
Displays error message:
Could not get data:.
Here is the code. Please help if you can. Will be highly appreciated.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
$sql = 'SELECT * FROM table ORDER BY id DESC LIMIT 5';
mysqli_select_db('my_db');
$retval = mysqli_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysqli_error());
}
while($row = mysqli_fetch_array($retval, mysqli_NUM))
{
echo "{$row[0]}". "<em>" . "({$row[1]})"."</em>"."<br>";
}
mysqli_close($conn);
?>
Thanx for all the helpful comments. I have edited my code. It now displays the path and image filename but not the image. (images/avatars/filename.jpg). Here is the revised code:
mysqli_select_db($conn, 'my_db');
$retval = mysqli_query( $conn, $sql );
if(! $retval )
{
die('Could not get data: ' . mysqli_error($conn));
}
while($row = mysqli_fetch_array($retval, MYSQLI_NUM))
{
echo "{$row[0]}". "<em>" . "({$row[1]})"."</em>"."<br>";
}
mysqli_close($conn);
?>
Hi guys. I managed to get it working. Thank you all for your assistance and patience. As suggested I changed to echo "<img src='".$row['0']."'/>"."<br>";
echo "{$row[1]}". "<em>" . "({$row[2]})"."</em>";
I think you have the db Link and Query params swapped..
$retval = mysqli_query( $sql, $conn );
Should be
$retval = mysqli_query( $conn, $sql );
There are a few errors in your code.
mysqli_select_db('my_db') requires a db connection as the first parameter.
mysqli_select_db($conn, 'my_db')
However, you could have just as easily used all 4 parameters:
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, 'my_db');
Reference:
http://php.net/manual/en/function.mysqli-connect.php
Then:
mysqli_error() requires a parameter for it.
mysqli_error($conn)
Then:
mysqli_query( $sql, $conn ) You need to inverse those, the connection must be first.
mysqli_query( $conn, $sql )
References:
http://php.net/manual/en/mysqli.select-db.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.query.php
And just to be certain, table if that's your real table name, is a MySQL reserved word:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
So wrap it with ticks
$sql = 'SELECT * FROM `table` ORDER BY id DESC LIMIT 5';
Footnotes:
Since MYSQLI_NUM is a constant in PHP, the mysqli_NUM may fail here, so you may need to make it all in uppercase MYSQLI_NUM.
Reference:
http://php.net/manual/en/mysqli.constants.php
Additional notes:
Your question's title holds "Cannot retrieve and display images".
I don't see where you're wanting to display an image here, as there are no <img> tags.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
"Displays error message:
Could not get data:"
This tells me that either your PHP configuration is wrong, or you're accessing it as file:/// rather than http://localhost.
Or, as I already outlined, mysqli_error() requires a db connection parameter where yours does not include it and is erroring out but you're not seeing the message it's throwing.
Use error reporting also and to catch and display:
http://php.net/manual/en/function.error-reporting.php
As Blake outlined in comments:
"Did you update the mysql package, too? PHP7 uses a different package."
So, make sure your installation was successful and that all system files were correctly updated and pointing to the right path/.ini file(s), and that you restarted all services and are running.
Consult Migrating from PHP 5.6.x to PHP 7.0.x:
http://php.net/manual/en/migration70.php
As stated by RiggsFolly in comments:
"You are using mysqli_fetch_array() after doing a SELECT * so we have ZERO idea what columns are returned and what is in any of the columns."
and...
"PS: Using mysqli_fetch_array() with SELECT * is quite dangerous. If someone alters the order of the columns in the database, you are likely to get different columns returned in $row[0] than you where when you tested this code. Use mysqli_fetch_assoc() then you get NAMED columns like $row['id'] and $row['filename']."
I will say this again; you need to use <img src...> in order to show the images. Your code as shown, will not automagically show the images, that's what <img> is for.
I believe that you used to use mysql_*() functions in the previous php version and changed to mysqli when you upgraded to php7.
Although mysqli can be used very similarly to the mysql extension, there are subtle differences.
You can select the default db when you create the connection.
The connection and query parameters are reversed in mysqli_query().
There are other differences as well, so pls read the documentation before adding a letter i to the mysql_*() functions!

php inserting into a MySQL data field

I am not sure what I am doing wrong, can anybody tell me?
I have one variable - $tally5 - that I want to insert into database jdixon_WC14 table called PREDICTIONS - the field is called TOTAL_POINTS (int 11 with 0 as the default)
Here is the code I am using. I have made sure that the variable $tally5 is being calculated correctly, but the database won't update. I got the following from an online tutorial after trying one that used mysqli, but that left me a scary error I didn't understand at all :)
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
$sql = "INSERT INTO PREDICTIONS ".
"(TOTAL_POINTS) ".
"VALUES('$points', NOW())";
mysql_select_db('jdixon_WC14');
I amended it to suit my variable name, but I am sure I have really botched this up!
help! :)
I think you just need to learn more about PHP and its relation with MYSQL. I will share a simple example of insertion into a mysql database.
<?php
$con=mysqli_connect("localhost","peter","abc123","my_db");
// Check for errors in connection to database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)";
mysqli_query($con, $query);
mysqli_close($con); //Close connection
?>
First, you need to connect to the database with the mysqli_connect function. Then you can do the query and close the connection
Briefly,
For every PHP function you use, look it up here first.
(You will learn that it is better to go with mysqli).
http://www.php.net/manual/en/ <---use the search feature
Try working on the SQL statement first. If you have the INSERT process down, proceed.
You need to use mysql_connect() before using mysql_select_db()
Once you have a connection and have selected a database, now you my run a query
with mysql_query()
When you get more advanced, you'll learn how to integrate error checking and response into the connection, database selection, and query routines. Convert to mysqli or other solutions that are not going to be deprecated soon (it is all in the PHP manual). Good luck!
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
mysql_select_db('jdixon_WC14');
$sql = "INSERT INTO PREDICTIONS (TOTAL_POINTS,DATE) ". //write your date field name instead "DATE"
"VALUES('$points', NOW())";
mysql_query($sql);

Sql Variable PHP Inclusion Issue

Hi I'm having trouble adding a variable to my Sql script, if i replace $safe with 'text' it works fine, i guess its a simple synatax problem. I hope someone can help as i'm a bit of a newbie!
<?
$ORDERID = 'LH-PAY-'.rand(10000000,99999999);
$safe - mysql_escape_string($ORDERID);
mysql_connect("localhost", "youthtra_wp1", "pass") or die(mysql_error());
mysql_select_db("youthtra_wp1") or die(mysql_error());
$query = "INSERT INTO tblPayments (PaymentID,Created,Status,Type,FlgID,WpUser,FullAmount,InsuranceAmount) VALUES ('".$safe."',now(),'Started','edpq','12345678','LH23456','499.99','19.99' )";
mysql_query($query);
echo 'ok';
Some points:
a) $safe is anything but. mysql_escape_string() is NOT safe to use. That's why mysql_real_escape_string() exists.
b) You shouldn't be using the mysql_*() functions anyways
c) You're simply assuming your query will always succeed, and are deliberately IGNORING the return value of mysql_query() which could help you if/when things fail. e.g. your code should be, at minimum:
$result = mysql_query(...);
if ($result === FALSE) {
die(mysql_error());
}
Just fix the - for = on line 3:
$safe - mysql_escape_string($ORDERID);

PHP mysql query syntax errors

I'm fairly new to PHP/MySQL and I seem to be having a newbie issue.
The following code keeps throwing me errors no matter what I change, and I have a feeling it's got to be somewhere in the syntax that I'm messing up with. It all worked at home 'localhost' but now that I'm trying to host it online it seems to be much more temperamental with spaces and whatnot.
It's a simple login system, problem code is as follows:
<?php
session_start();
require 'connect.php';
echo "Test";
//Hash passwords using MD5 hash (32bit string).
$username=($_POST['username']);
$password=MD5($_POST['password']);
//Get required information from admin_logins table
$sql=mysql_query("SELECT * FROM admin_logins WHERE Username='$username' ");
$row=mysql_fetch_array($sql);
//Check that entered username is valid by checking returned UserID
if($row['UserID'] === NULL){
header("Location: ../adminlogin.php?errCode=UserFail");
}
//Where username is correct, check corresponding password
else if ($row['UserID'] != NULL && $row['Password'] != $password){
header("Location: ../adminlogin.php?errCode=PassFail");
}
else{
$_SESSION['isAdmin'] = true;
header("Location: ../admincontrols.php");
}
mysql_close($con);
?>
The test is just in there, so I know why the page is throwing an error, which is:
`Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in 'THISPAGE' on line 12`
It seems to dislike my SQL query.
Any help is much appreciated.
EDIT:
connect.php page is:
<?php
$con = mysql_connect("localhost","username","password");
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
?>
and yes it is mysql_*, LOL, I'll get to fix that too.
You should escape column name username using backtick, try
SELECT *
FROM admin_logins
WHERE `Username` = '$username'
You're code is prone to SQL Injection. Use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("SELECT * FROM admin_logins WHERE `Username` = ?");
$stmt->bindParam(1, $username);
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
Sean, you have to use dots around your variable, like this:
$sql = mysql_query("SELECT * FROM admin_logins WHERE Username = '". mysql_real_escape_string($username)."' ");
If you use your code just like this then it's vulnerable for SQL Injection. I would strongly recommend using mysql_real_escape_string as you insert data into your database to prevent SQL injections, as a quick solution or better use PDO or MySQLi.
Besides if you use mysql_* to connect to your database, then I'd recommend reading the PHP manual chapter on the mysql_* functions,
where they point out, that this extension is not recommended for writing new code. Instead, they say, you should use either the MySQLi or PDO_MySQL extension.
EDITED:
I also checked your mysql_connect and found a weird regularity which is - if you use " on mysql_connect arguments, then it fails to connect and in my case, when I was testing it for you, it happened just described way, so, please try this instead:
$con = mysql_connect('localhost','username','password');
Try to replace " to ' as it's shown in the PHP Manual examples and it will work, I think!
If it still doesn't work just print $row, with print_r($row); right after $sql=mysql_query() and see what you have on $row array or variable.

Basic SQL output question

this is probably the most basic question in the world, but I cannot figure it out.
I would like to simply display a users First name, and Email adress from my table. I have tried using a loop, but that was entirely worthless considering I am only selecting one row. I know this is a menial question but I could not find/remember how to do it. Thank you!
$db = mysql_connect("server","un", "pw");
mysql_select_db("db", $db);
$sql = "SELECT FirstName, EmailAddress"
. " FROM Student"
. " WHERE StudentID = '$student' ";
$result = mysql_query($sql, $db);
$num = mysql_num_rows($result);
$userinfo = mysql_result($result,$userinfo);
$student is a session variable. I want to echo the First name and email address somewhere in the page, but I cannot believe how much pain thats causing me. Thanks again!
mysql_fetch_assoc() turns a result row into an array.
$result = mysql_query($sql, $db);
$user = mysql_fetch_assoc($result);
echo $user['FirstName'];
echo $user['EmailAddress'];
It looks like you spelled address wrong, so it probably doesn't match your real column name. More importantly, your code appears vulnerable to SQL injection. You really need to use prepared statements (see How to create a secure mysql prepared statement in php?) or escaping.
To fetch a row, you must use one of the mysql_fetch functions (e.g. mysql_ fetch_ array, mysql_ fetch_ object, etc.)

Categories