USE LIKE with php variable - php

I have a problem using LIKE with PHP variables. I would like to select, based on a username, what matches the username in the DB. Here is my code:
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "coffeecorner";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$user = $_SESSION['username'];
$sql = "select username ";
$sql .= "from add_reservation";
$sql .= "where username like" . $user;
$result = mysqli_query($connection, $sql);
if(!$result)
{
die("database query fail!" . mysqli_error($connection));
}
Error
database query fail! You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'likeipin' at line 1
Any help would be appreciated!

You need quotes around the username. Also, if you're using LIKE to match a pattern, you should have wildcards in it.
$sql .= "where username likem '%$user%'";
But it's better to use a parametrized query.
$sql = 'SELECT username
FROM add_reservation
WHERE username like ?';
$user_pattern = "%$user%";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, "s", $user_pattern);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
die("database query fail!" . mysqli_error($connection));
}

You neeed to add a little a space after like :
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "coffeecorner";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$user = $_SESSION['username'];
$sql = "select username ";
$sql .= "from add_reservation";
$sql .= "where username like " . $user;
$result = mysqli_query($connection, $sql);
if(!$result)
{
die("database query fail!" . mysqli_error($connection));
}
check the error message :
database query fail!You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'likeipin' at line 1
the word like is stuck with the username forming a single string likeipin ; it should be like ipin meaning $sql .= "where username like " . $user;
Be carefull on session, session_start should be used before accessing session variable.
You can use this query string : $sql = "SELECT username FROM add_reservation
WHERE username LIKE '%". mysql_real_escape_string($user) ."%'" or this one :
$sql = "SELECT username FROM add_reservation
WHERE username LIKE '%".$user."%'"
Hope it help.

after a few hours thinking and trying i have found the solution. this a the new code. We need to input a braces () on it;
if(session_id()=='' || isset($_SESSION['username'])){
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "coffeecorner";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$user = $_SESSION['username'];
$sql = "(SELECT * FROM add_reservation WHERE username like '$user')";
$result = mysqli_query($connection, $sql);
if(!$result)
{
die("database query fail!" . mysqli_error($connection) . mysqli_errno($connection));
}
Hope it helped !

Related

How can I get the id of the record with the email, mysql

I have a test MySQL with a field which is unique as e-mailadres. Now I want to check before adding a record if the email already exists. I have the following code
<?php
$servername = "localhost";
$username = "xxxxxx";
$password = "xxxxxx";
$dbname = "xxxxxxx";
$servername = "localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//test met voorbeeld
$emailtest="adres#me.com ";
$sql = "SELECT * FROM salonkeuze WHERE emailadres='$emailtest' ";
$data = mysqli_query($connect, $sql);
$row = mysqli_fetch_assoc($data);
$id = $row['voorkeur_id'];
Echo $id;
?>
When I use an email address which is in de table. I don’t get any output. What do I wrong?
Here $emailtest="adres#me.com "; you can extra space after com, try to remove it -> $emailtest="adres#me.com";
Firstly, you use wrong variable in this line:
$data = mysqli_query($connect, $sql);
Correct:
$data = mysqli_query($conn, $sql);
And it's optional, but it will be good, if you use trim() function for your $email. Because if your data comes from inputs and if $email have spaces, you can't show correct results:
$emailtest = "adres#me.com ";
$emailtest = trim($emailtest);
$sql = "SELECT * FROM salonkeuze WHERE emailadres='$emailtest' ";

how mysql query written in php to get json format output [duplicate]

This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 6 years ago.
i have written code in php file that to connect to database and get the requested data .
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
$subject = mysqli_fetch_assoc($result);
print_r($subject);
?>
i am getting the output in array format ,i want to get the out put in json format.how to change the code ,please help me .
You need to use php json_encode() method. Please check php doc for json_encode here
Use json_encode:
I suppose you're making API to return JSON string, make sure you return it as a JSON response instead of HTML. It's a good practice :)
To return JSON string as a JSON response, You can do the following.
<?php
header('Content-Type: application/json');
echo json_encode($subject);
?>
create a array or results and use json_encode.
$subject = array();
while($row = $result->fetch_assoc() ){
$subject[] = $row;
}
echo json_encode($subject);
You have to use json_encode($subject).
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
$subject = mysqli_fetch_assoc($result);
if($subject)
{
$json_subject = json_encode($subject);
print_r($json_subject);
}
?>

php delete record using id

This program is meant to delete a record when given the id.
php:
if ($_GET['type']=="file"){
$servername = "localhost";
$username = "****";
$password = "****";
$dbname = "****";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_error($conn)) {
die("Connection failed: " . mysqli_connect_error($conn));
}
$sql = "SELECT id,user, FROM CreationsAndFiles WHERE id =".$_GET['id']." LIMIT 1";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
if ($row['user'] == $login_session){
$sql = "DELETE FROM CreationsAndFiles WHERE id=".$_GET['id'];
if(mysqli_query($conn, $sql)){echo "deleted";}
}
mysqli_close($conn);
//header("location: index.php?page=CreationsAndFiles");
}
the header is type=file&id=9
there is a record where id=9
It for no apparent reason will not work.
Your SQL syntax is wrong;
SELECT id,user, FROM CreationsAndFiles...
^ extra comma
should be simply
SELECT id,user FROM CreationsAndFiles...
You may want to sanitize your input though, for example simply entering type=file&id=id will most likely do bad things.

I can not update database using php

For some reason I am can not update my database. Can anyone spot what I am doing wrong ?
Here is the code.
.......
session_start();
$user = mysql_real_escape_string($_POST['user']);
$email = mysql_real_escape_string($_POST['email']);
.......
if ($errorMessage == "") {
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ----- CHECKING SERVER
include('connect.php');
if (isset($user)) {
$sql = "UPDATE hookers ".
"SET user= ´$user´".
"WHERE email= ´$email´" ;
mysqli_query($con, $sql) or die("Can´t find user". mysql_error());
print "user updated";
mysqli_close($con);
}
}
connect.php file
$host = 'localhost';
$username = 'root';
$password = '';
$db = 'putas';
$con = mysqli_connect($host, $username, $password) or die("Can´t connect to server");
mysqli_select_db($con, $db) or die("Can´t connect to database");
Whenever I run the script it prints "Can´t find user". The variables $user & $email have the right data as I have checked it.
I would appreciate any help you guys can provide me.
Thanks in advance.
Oliver Tangari
You need to change all instances of ´ to '.
Your Sql Query Will Be like this:--
$sql = "UPDATE hookers ".
"SET `user`= '$user'".
"WHERE `email`= '$email'" ;
Hope it helps you...
Use ' single quote not `
$sql = "UPDATE hookers ".
"SET user= '$user'".
"WHERE email= '$email'" ;
As already mentioned the problem is ´
Why don't you use PDO and parameter binding instead? This won't give you this type of errors in the future.
<?php
// configuration
$dbtype = "sqlite";
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$user = 'Belén Esteban';
$email = 'belenesteban#telecinco.es';
// query
$sql = "UPDATE hookers
SET user=?
WHERE email=?";
$q = $conn->prepare($sql);
$q->execute(array($user,$email));
?>

PHP, MySQL table query syntax error?

I hope someone can help see what's wrong here:
I have a form with two field EMAIL and PASSWORD that opens a php page where I intend to run a simple query on a table.
I get an error message that makes no sense:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#gmail.com' at line 1.
The email address I entered in this case did end with '#gmail.com'
Here's the code:
<?php
$dbhost = 'somewhere.net';
$dbuser = 'someUser';
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn));
$email = mysql_real_escape_string($_POST['email']);
$query = "SELECT * FROM employee WHERE email = $email";
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));
while ($row = mysql_fetch_array($result)) {
extract($row);
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>
Any advice would be appreciated.
You are missing quotes around string fields:
$query = "SELECT * FROM employee WHERE email = '$email'";
Additionally,
extract(mysql_fetch_assoc($result));
will fetch the first row from the database, so your while loop will start from the second row.
You have to put the value in quotes inside SQL string.
$email = mysql_real_escape_string($_POST['email']);
$query = "SELECT * FROM employee WHERE email = '$email'";
(mind the extra '' around $email)
Your query translates to:
SELECT * FROM emloyee WHERE email = foo#bar.com
This doesn't work, you have to put strings in quotes. Change your code to the following and it will work:
$query = "SELECT * FROM employee WHERE email = '$email'";
Just single quote the variable '$email' because it varchar type value and field .
As wrote, Darhazer :)
Full fixed code:
<?php
$dbhost = 'somewhere.net';
$dbuser = 'someUser';
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn));
$email = mysql_real_escape_string($_POST['email']);
$query = "SELECT * FROM employee WHERE email = '$email'";
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));
while ($row = mysql_fetch_array($result)) {
extract($row);
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>

Categories