SQL Query of checking existing entry in database is not working - php

<?php
error_reporting(0);
$link = mysqli_connect("localhost", "root", "", "checksql");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$myemailaddress=$_POST['useremail'];
$mypassword=$_POST['userpassword'];
$sql = mysqli_query("SELECT * FROM register WHERE Email = '$myemailaddress' ");
$count = mysqli_num_rows($sql);
echo $count;
if($count > 0){
echo "success";
} else{
echo "failed";
}
?>
I am trying to check whether an email exists in the database or not. I searched different thread on stackoverflow and tried to correct it but failed. Even the echo of $count isn't showing it's value. Is there any other way to check it?

You didn't pass db connection to your query
$sql = mysqli_query($link, "SELECT ...
^^^^^^
Btw, your code is open to SQL injection.
Use a prepared statement
https://en.wikipedia.org/wiki/Prepared_statement
More on SQL injection:
https://en.wikipedia.org/wiki/SQL_injection
http://php.net/manual/en/security.database.sql-injection.php
How can I prevent SQL injection in PHP?
Also make sure your POST arrays are not failing you.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
error_reporting(0); doesn't help you, it turns it off.
Add or die(mysqli_error($link)) to mysqli_query() to check for errors.
http://php.net/manual/en/mysqli.error.php
Your form should be using a POST method with name attributes for both your POSTs. That is unclear and wasn't posted in your question; call it an insight.
If you are using both your form and PHP/MySQL inside the same file, then that will trigger undefined index notices on initial page load.
Use !empty() for them.
Reference(s):
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/tutorial.forms.php
http://php.net/manual/en/function.empty.php

Related

Echoing Out A Mysql Query

Alright. I have searched and searched for an answer, but I just could not find it.
I am writing a simple php script that takes the url information and runs it through a MySQL query to see if a result comes up. I try to echo the variable holding the query out, but nothing shows up. I know there must be a result because if I enter the query manually in MySQL it displays my desired result.
$result = mysqli_query("SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
I have tried to echo out both the $result and $data. But there is nothing displayed. I am so new to programming, and this is my first StackOverflow post, so forgive me if I am making huge errors.
Actually mysqli_query() requires two parameters... check the following sample example ..
<?php
$conn = mysqli_connect('localhost','root','','your_test_db');
$_GET['page'] = 1;
$result = mysqli_query($conn,"SELECT * FROM your_table WHERE id = '" . $_GET['page'] . "'");
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
?>
As you have stated you are just in a learning phase, it is okay to code these sort of queries just to learn yourself but do not code these kind of queries as these queries are vulnerable so i would suggest you to use prepare queries or PDO...
Also never use SELECT * in your queries, this is a bad practice, only deal with the fields which you requires in return.
Also, you can always check whether your database is connected or not. So that you have a better idea.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
you have not mentioned whether you are following OOP structure or not .. so i would suggest you to check error_reporting() and connect database on the same page to check the things around ..
Also you can check whether you without WHERE condition for now "SELECT * FROM your_table just to make sure whether you are getting atleast all the records or not.
The problem is that you're not setting up the connection in the query. mysqli_query() requires two parameters.
Make the connection first:
$conn = mysqli_connect("localhost", "user", "password", "dbname");
Now execute the query:
$result = mysqli_query($conn,"SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
NOTE: Your code is heavily vulnerable to MySQL injections. Use MySQLi or PDO Prepared statements.
Also, you should use mysqli_errno() to find out your query bugs.
Edit:
Also do this:
while($row=mysqli_fetch_assoc($result)){
//do the result output.
}

Not adding values to database

I just created ajax function which sends data to php and php to database. Inserting to dotp_task_log table, works fine. But further, when I need to add data to dotp_tasks after adding to dotp_task_log, it isn't adding, and I cant find why... I get the Gerror, Here is my php file which adds data to database.
<?php
$currentUser = isset($_POST['currentUser']) ? $_POST['currentUser'] : '';
$currentTasken = isset($_POST['currentTasken']) ? $_POST['currentTasken'] : '';
$currentPercent = isset($_POST['currentPercent']) ? $_POST['currentPercent'] : '';
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows >= 1)
{
//$pass = md5($pass);
$ins = mysql_query("INSERT INTO dotp_task_log (task_log_creator, task_log_Task) VALUES ('$currentUser' , '$currentTasken')" ) ;
if($ins)
{
$check = mysql_query("SELECT * FROM dotp_tasks");
$numrows = mysql_num_rows($check);
if($numrows > 1)
{
//$pass = md5($pass);
$inss = mysql_query("INSERT INTO dotp_tasks (task_percent_complete) VALUES ('$currentPercent') WHERE task_id='$currentTasken'" ) ;
if($inss)
{
die("Succesfully added Percent!");
}
else
{
die("GERROR");
}
}
else
{
die("Log already exists!");
}
}
else
{
die("ERROR");
}
}
else
{
die("Log already exists!");
}
?>
As I stated in comments:
INSERT... doesn't have a WHERE clause. Error checking would have signaled the syntax error. INSERT ON DUPLICATE KEY does. You may have wanted to use UPDATE instead
$inss = mysql_query("UPDATE dotp_tasks
SET task_percent_complete = '$currentPercent'
WHERE task_id='$currentTasken'" );
References:
https://dev.mysql.com/doc/refman/5.0/en/update.html
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
Plus, do use error checking when testing:
http://php.net/manual/en/function.mysql-error.php
instead of echoing custom messages.
Add or die(mysql_error()) to mysql_query().
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Footnotes:
Make sure your HTML form does hold a POST method and that all inputs bear the name attributes and no typos. Using error reporting, will signal that.
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Fred -ii- nailed it in his comment - you're using improper syntax in that query.
It looks like you want an update query, for example:
update dotp_tasks
set task_percent_complete = '$currentPercent'
where task_id = '$currentTasken'
Additionally - it's always best to avoid creating queries by formatting strings manually - you'll want to look into prepared statements to improve this code further.

Get Results from mySQL in PHP

I am trying to get result from as table in mySQL in the following code.
It does not work. I am newbie in PHP.
Maybe someone can help whatws wrong in my code? I think that my SQL sentence is not written well. Is it?
<?php
header("Content-type: text/html; charset=utf8");
// header('Content-Type:text/html;charset=utf-8');
//1. create connection
$connection=mysql_connect("localhost","user","pass");
if(!$connection){
die("database connection failed:" . mysql_error());
}
//2. select database
$db = mysql_select_db("database",$connection);
if(!db) {
die("database connection failed:" . mysql_error());
}
//if i want to work with hebrew databases
mysql_query("SET NAMES 'utf8'",$connection); // reading heberer from phpadmin database - only for hebrew sites
$MessageNo = $_POST['MsgNo']
//$MessageN0=(int)$MessageNo
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");;;
$messages = array();
while ($row = mysql_fetch_array($query)) {
$messages[] = array('MsgContId' => $row['MsgContId'], 'MsgNo' => $row['MsgNo'],'MsgContent' => $row['MsgContent'], 'AddedBy' => $row['AddedBy'],'AddedAt'=>$row['AddedAt']);
}
// echo json_encode(array('users' => $users));
echo json_encode($messages);
mysql_close($connection);
?>
I can see on this line you have formatting errors:
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");;;
Remove the extra two semi-colons:
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");
Also this:
$MessageNo = $_POST['MsgNo']
Needs a semi-colon:
$MessageNo = $_POST['MsgNo'];
Additionally you're using deprecated functions. I would suggest you look into MySQLi functions or PDO.
Consult: mysqli with prepared statements, or PDO with prepared statements.
EDIT: Also in your second query, you're not using the connection string:
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'",$connection);
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Also add or die(mysql_error()) to mysql_query().
Sidenote:
Your present code is open to SQL injection.

PHP echo a variable showing blank screen

So I have the following PHP code
<?php
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$poscote = $_POST['postcode'];
mysql_real_escape_string($poscote);
//! Checks for direct access to page
if (empty($_POST)) {
header('location:index.php?nothingentered');
die();
}
require_once('../Connections/PropSuite.php');
mysql_select_db($database_Takeaway, $Takeaway);
$query_PC = "SELECT * FROM Postcodes WHERE pc = '$postcode'";
$PC = mysql_query($query_PC, $Takeaway) or die(mysql_error());
$row_PC = mysql_fetch_assoc($PC);
if( mysql_errno() != 0){
// mysql error
// note: message like this should never appear to user, should be only stored in log
echo "Mysql error: " . htmlspecialchars( mysql_error());
die();
}
else {
echo $row_PC['oc'];
}
?>
This is to process a form with the following code
<form action="search_postcode.php" method="post">
<input type="text" name="postcode" />
<button>Go</button>
</form>
Strangely its just showing a blank screen, no errors, nothing I have checked through and cannot seem to find a solution.
Many thanks in advance for your help.
As your $postcode variable is undefined, you are looking in your database for a row where pc is an error message.
That query could very well finish without errors, but it probably produces 0 rows, so you don't have an error, nor do you have a result. In that case you output nothing, so you will see a blank screen.
You probably want:
$postcode = mysql_real_escape_string($poscote);
instead of:
mysql_real_escape_string($poscote);
and put it below the database connection section.
Also, you should switch to PDO (or mysqli) and prepared statements to avoid sql injection problems and because the mysql_* functions are deprecated. Note that your mysql_real_escape_string does not do anything (except removing the contents of your variable...) when you don't have a database connection open.
In addition to the other answers, and without mentioning that you should be using PDO or mysqli, you could be having a character encoding issue. Try doing something like this:
define('DB_CHARSET', 'ISO-8859-1');
define('REPLACE_FLAGS', ENT_COMPAT | ENT_XHTML);
...
echo "Mysql error: " . htmlentities(mysql_error(), REPLACE_FLAGS, DB_CHARSET);
Replace the value of DB_CHARSET with whatever encoding your database is using. If you try to use htmlentities() with an invalid character it will produce an empty string.
As of php.net, to enable php errors using the ini_set, you have to do it like this
ini_set('display_errors', '1')
This is taken from this link

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.

Categories