Check in mysql if entry exists and not insert with php - php

I have got a problem with testing out if a string exists in my database!
This is what I've got so far:
$db = mysqli_connect("localhost", "database", "secret", "user");
if(!$db)
{
exit("Error: ".mysqli_connect_error());
}
$search = 'SELECT * FROM table WHERE ip = $client_ip';
$result = mysqli_query($db, $search);
while($row = mysqli_fetch_object($result)) {
if (isset($row->blocked)) {
echo 'You are blocked!';
} else {
echo 'You are not blocked!';
}
But this won't work for me.
$client_ip is defined correctly before.

You need to wrap $client_ip in quotes as it is a string:
$search = "SELECT * FROM table WHERE ip = '$client_ip'";

try this one :
$search = "SELECT * FROM table WHERE ip = '{$client_ip}'";

Related

Checking SQL Database for value

I am trying to use php to check my database to see if a value exists. My main goal is to use this value
$_GET['UDID']
and if it is equal to any value that is in the database it will return
echo 'FOUND';
I am using this code:
<?php
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "*****";
$connect = new mysqli($servername, $username, $password, $dbname);
if ($connect->connect_error) {
die("CONNECTION FAILED: " . $connect->connect_error);
}
$udid = $_GET['UDID'];
$id = mysqli_real_escape_string($connect, $udid);
$result = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '$id'");
if($result === FALSE) {
die("ERROR: " . mysqli_error($result));
}
else {
while ($row = mysqli_fetch_array($result)) {
if($row['udid'] == $udid) {
$results = 'Your device is already registered on our servers.';
$results2 = 'Please click the install button below.';
$button = 'Install';
$buttonlink = 'https://**link here**';
}
else {
$results = 'Your device is not registered on our servers';
$results2 = 'Please click the request access button below.';
$button = 'Request Access';
$buttonlink = 'https://**link here**';
}
}
}
?>
But for some reason it is not working, I am sure I am over looking something. your help is greatly appreciated.
Try this:
$sql = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '" .$udid. "'");
And also, make sure to set the value from 'GET' to $udid. Should be like this:
$udid = $_GET['UDID'];
We can use mysqli_fetch_array() instead to get the result row. I also include error handling. Now your code must look like this :
$udid = $_GET['UDID'];
$id = mysqli_real_escape_string($connect, $udid);
$result = mysqli_query($connect, "SELECT `udid` FROM `wmaystec_WMT-SS`.`data` = '$id'");
if($result === FALSE) {
die(mysqli_error("error message for the user")); //error handling
}
else {
while ($row = mysqli_fetch_array($result)) {
echo "FOUND :" .$row['thefieldnameofUDIDfromyourDB'];
}
}
I would suggest you to first escape the string, using the mysqli_real_escape_string function, and then call the SQL query.
$udid = mysqli_real_escape_string($connect, $udid);
$sql = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '$udid'");

PHP Register Script - check user exists not working

I've got a problem with my PHP Registration Script that firstly checks, if the user exists.
It always outputs "false".
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$database = #mysql_connect("***********", "********", "******") or die("Can't connect to the server. Error: ".mysql_error());
//$username = mysql_real_escape_string($username);
$passwort = hash("sha256", $passwort);
$numrows = mysql_query("SELECT * FROM *******.mikgames WHERE username='".$username."' LIMIT 1");
$checkuserexists = mysql_num_rows($numrows);
if($checkuserexists==0) {
$abfrage = mysql_query("INSERT INTO *******.mikgames (username,passwort) VALUES ('$username', '$passwort')");
echo'true';
}
else {
echo'false';
}
?>
Edit: Now I'am using MySQLi and I've changed the code into this:
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$con = mysqli_connect('************','******','******') or die(mysqli_error());
mysqli_select_db($con, "*******") or die("cannot select DB");
$passwort = hash("sha256", $passwort);
$query = mysqli_query($con,"SELECT * FROM *******.mikgames WHERE username='".$username."'");
$result = mysqli_num_rows($query);
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames (username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
echo 'true';
}
else {
echo 'false';
}
?>
And it works.
You could go one step better and take an OOP approach using the PDO driver; PDO invokes security by allowing secure parameter binding and uses the SQL preferred functions.
Inside your pdo_driver.php file:
namespace ProjectName\App\Drivers;
if(!defined('IN_PROJECTNAME'))
{
die('No Script Kiddies Please...');
}
interface EntityContainer
{
public function query($statement, array $values = array());
}
class Entity extends \PDO implements EntityContainer
{
public function __construct(
$dsn = 'mysql:host=XXXX;dbname=XXXX', $user = 'XXXX', $pass = 'XXXX'
) {
try {
parent::__construct($dsn,$user,$pass);
} catch (PDOException $ex) {
die('FATAL ERROR: ' . $ex->getMessage());
}
}
public function query(
$statement, array $values = array()
) {
$smpt = parent::Prepare($statement);
(empty($values)) ? $smpt->execute() : $smpt->execute($values);
return $smpt;
}
}
Inside any other php file:
define('IN_PROJECTNAME', 0);
require_once dirname(__FILE__) . '/path/to/pdo_driver.php';
$container = array();
$container['Connection'] = new ProjectName\App\Drivers\Entity();
$username = $_GET['username'];
$passwort = $_GET['passwort'];
if(empty($container['Connection']->query('SELECT passwort FROM ******.mikgames WHERE username = ?', [$username])->fetch()['passwort'])) {
$container['Connection']->query('INSERT INTO ******.mikgames (username,passwort) VALUES (?, ?)', [$username,$passwort]);
}
Two Factors:
Firt Factor
You need to add an error output for debugging purposes:
$query = mysqli_query($con,"SELECT * FROM <tablename> WHERE
username='".$username."'") or die(mysqli_error($con));
I can't see a clear error with the information you have displayed here so far so you should also check what the value of $username acutally is and how closely it fits the value in the DB. Also read and take on board what the error output tells you.
Second Factor:
Your problem is you're running/articulating a query twice, here:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
You see $abfrage is a MySQL result object and you're then plugging it back into a MySQL query call, with the variable declaration $result. So your result is querying a query. This is an error.
What you probably want to do is use MySQLi_affected_rows to count how many rows have been inserted and run the appropriate IF clause:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_affected_rows($con);
echo 'true';
}
else {
echo 'false';
}
Use #mysql_***** for your ptoject.
$sql="SELECT * FROM table_name";
$result=#mysql_query($sql, $conn);
while ($name = # mysql_fetch_array($result)){
echo $name ['username'];
}
You just used simple mysql_***

check if a value exists in my database table

I want to check if a URL exists in my MySQL database table for example if Url=exist, message=url already exist
<?php
if(isset($_POST['Submit'])){
$dbhost = 'localhost';
$dbuser = '####';
$dbpass = '#######';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$Title = $_POST['Title'];
$Url = $_POST['Url'];
$email_data = $_POST['email_data'];
$type_data = $_POST['type_data'];
$sql = "INSERT INTO table ". "(Title,Url,email_data,type_data)"."VALUES('$Title','$Url','$email_data','$type_data')";
mysql_select_db('dbname');
$retval = mysql_query( $sql, $conn );
if(! $retval ){
die('Could not enter data: ' . mysql_error());
}
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
mysql_close($conn);
} else {
?>
You can do like this
$sql = "SELECT Url FROM 'your_table_name' WHERE Url = $_POST['Url']";
Run this sql and if it is return true you can say its exist.
$query = mysql_query('select url from table-name where url=$_post['url']');
if(mysql_fetch_rows($query) != 0){
echo "URL allready Exists";
}else{
Insert Query
}
Hi, Try this code.
Its a bit hard know what you are doing by just looking at the code but if you wondering how to check if something is in the database you could do like this:
PHP:
$sql = mysql_query("SELECT * FROM dbname WHERE Url='$Url'");
if(mysql_num_rows($sql) > 0){
echo "alreday exist";
}

Query MySQL with PHP

I am trying to query a MySQL database with PHP and return the results as JSON. I'm new to PHP and web development so I'm not sure what I'm doing wrong. I've set up the database using MAMP. My parameters are being printed but I'm not getting the JSON. I've gotten this far with the help of a tutorial.
EDIT: I just went into phpMyAdmin to make sure it was working and when I click on Server:localhost:8889, a window pops up that says Error in processing request. Error code 404.
I'm thinking this is the problem, I'm just not sure why it isn't working. I may reinstall MAMP.
<?php
$user = 'root';
$password = 'root';
$db = 'TestDB';
$host = '127.0.0.1';
$port = '8889';
$first_name = filter_input(INPUT_GET, 'first_name');
$last_name = filter_input(INPUT_GET, 'last_name');
$membership_number = filter_input(INPUT_GET, 'membership_number');
echo $first_name;
echo $last_name;
echo $membership_number;
// Create connection
// $con = mysqli_connect("localhost", "root", "root", "TestDB");
// $con = mysqli_connect("localhost", "root", "root", "TestDB", "8889", $socket);
$link = mysqli_init();
$con = mysqli_real_connect($link, $host, $user, $password, $db, $port);
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = \'$first_name\' and LAST_NAME = \'$last_name\' and MEMBERSHIP_NUMBER = \'$membership_number\'";
$result = mysqli_query($con, $sql);
if(!$result) {
die('Query failed: ' . mysqli_error());
}
// Check for results
// if ($result = mysqli_query($con, $sql)) {
if($result) {
// If there are results, create results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
// while($row = $result->fetch_object()) {
while($row = mysqli_fetch_object($result)) {
// Add each row to the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo $tempArray;
echo $resultArray;
echo $result;
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
You need to change you $sql variable to remove the escapes on the single quotes. They register as part of the string because you are using double-quotes to wrap it. Basically, you're telling the database to run the query "SELECT * FROM NAME WHERE FIRST_NAME = \'John\' and LAST_NAME = \'Smith\' and MEMBERSHIP_NUMBER = \'VRX78435\'". This will error if you run it directly because the escape characters are not escaping.
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = '$first_name' and LAST_NAME = '$last_name' and MEMBERSHIP_NUMBER = '$membership_number'";
That should fix it for you.
There may also be an issue with your connection to the server. mysqli_query() uses the results of mysqli_connect() to run the query. mysqli_real_connect() only returns a boolean value, so it is invalid for this particular use (at least it failed to work on my server).
This would be a simple matter of replacing the $con and then you can drop the $link variable.
$con = mysqli_connect($host, $user, $password, $db, $port);
These changes, and assuming the $first_name, $last_name, and $membership_number are all valid, allowed your script to run for me, so I hope this helps.
Seems you are using procedural style coding
Instead of
while($row = $result->fetch_object()) {
You need mysqli_fetch_object in procedural style
while($row = mysqli_fetch_object($result)) {

php mysql query with hyphen character

I have a query problem with hyphen character.
$user = "test-user";
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
echo mysql_error(); //no error message
test-user record is in table but query result coming empty. Also mysql error message is empty. What is wrong?
EDIT:
Thank you for answers. I apologize to everyone. I found the problem and I see now the problem is not in the query. Problem coming form regex.
if (preg_match("/^[a-z0-9]+$/i", $user)) //dash character not in regex
{
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
}
I've corrected the problem as follows:
if (preg_match("/^[a-z0-9\-]+$/i", $user)) //added \- to regex for dash
{
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
}
Just use mysql_real_escape_string to escape the data string.
$user = "test-user";
$user = mysql_real_escape_string($user);
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
echo mysql_error(); //no error message
But I would also recommend using or die() syntax instead of the #mysql_query you have in place.
$user = "test-user";
$user = mysql_real_escape_string($user);
$q = mysql_query("SELECT id FROM table WHERE user='$user'") or die ("Error: " . mysql_error());
$p = mysql_query("SELECT id FROM table WHERE user='$user'");
if (!$p)
{
die('Could not query:' . mysql_error());
}
else
{
echo mysql_result($p>0);
}
try it
Try this:
$user = "test-user";
$q = mysql_query("SELECT id FROM `table` WHERE user='".$user."'")
or die(mysql_error());//no error message;
Full example with mysqli_:
$host = "";
$user = "";
$password = "";
$database = "";
$user_name_query = "test-user"; // If this value is from a form please read more about sql-injection.
// open connection to database
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
// SELECT QUERY
$query = "SELECT id FROM `table` WHERE user='".$user_name_query."'";
mysqli_query($link,$query) or die("Query failed");
}
// close connection to database
mysqli_close($link);
Any difference if you change the query to:
$q = mysql_query("SELECT id FROM table WHERE user='".$user."'");
Unless I'm having a very slow Sunday I think you're searching for the literal string $user rather than the variable value.

Categories