i need to perform a name search in the database based on a set of keywords. the result should be accent sensitive and case insensitive.
following the solution i found here plus few modifications to allow case insensitivity, i used the following code:
$sql = "SELECT name FROM table_names WHERE LOWER(name) LIKE _utf8 '%".strtolower($keyword)."%' COLLATE utf8_bin";
this does not work for me when the search keyword contains accents. but the strange thing is that this query works well in phpMyAdmin (but i read somewhere that this shouldn't be reliable). what could be the problem here?
UPDATE:
i revised my code to:
$sql = "SELECT name FROM table_names WHERE LOWER(name) LIKE LOWER(_utf8 '%$keyword%') COLLATE utf8_bin";
but i still have no results.
thanks!
You can try to echo the sql being executed and check if the accents are there.
My guess they are not...
[EDIT]
Can you try this:
php.
<html>
<head>
</head>
<body>
<form action="" method="get">
<input name="name" type="text"/>
<input type="submit" value="go"/>
</form>
<?php
if (!empty($_GET['name'])) {
$mysqli = new mysqli('localhost', 'root', '', 'test');
$mysqli->set_charset('latin1');
$_GET['name'] = utf8_encode($_GET['name']);
if ($result = $mysqli->query('select * from dummy where LOWER(name) LIKE _utf8 \'%' . $_GET['name'] . '%\' COLLATE utf8_bin')) {
while ($obj = $result->fetch_object()) {
var_dump($obj->name);
}
}
$mysqli->close();
}
?>
</body>
</html>
mysql: (doesn't matter)
CREATE TABLE `dummy` (
`id` int(11) NOT NULL,
`name` varchar(45) CHARACTER SET latin1 DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin5$$
This one works for me...
Related
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
How can I get useful error messages in PHP?
(41 answers)
Closed 1 year ago.
Update query not taking integer variable ($user):-
$user = $_POST["user"];
$user = (int)$user;
$sql = "UPDATE users_meta
SET
`meta_value` = '$plan_end'
WHERE
`user_id` = $user AND
`meta_name` = 'plan_end'";
$conn->query($sql);
user_id column in mysql database is set to int datatype.
When I simply put a number instead of the variable, it works:-
WHERE
`user_id` = 37 AND ...
I also tried without converting the number from string to int, and its not working. I have a feeling that it has something to do with quotes, so I played around with it based on suggestions online, but none worked.
As per based on my knowledge if database field is of Int type then it cannot accept character/string values even you are converting them into type of integer. You have to modify the database field to varchar or you have to pass only numeric values to the database field. Hope this suggestion may solve your problem.
Hi I have tested your query on my local it works fine so I don't think there is any thing wrong with you query.
<?php
$mysqli = new mysqli("localhost","root","","test_table");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
if(#$_POST["user"])
{
$user = $_POST["user"];
$tasone = $_POST["tasone"];
$user = (int)$user;
$sql = "UPDATE test_table SET `TAS_ONE` = '$tasone' WHERE `user_id` = $user and `TAS_TWO`='dsadsa'";
$mysqli->query($sql);
}
?>
<form action="" method="post">
<input type="text" id="user" name="user" value=""><br>
<input type="text" id="tasone" name="tasone" value=""><br>
<input type="submit" value="Submit">
</form>
CREATE TABLE `test_table` (
`USER_ID` int(9) NOT NULL,
`TAS_ONE` varchar(200) NOT NULL,
`TAS_TWO` varchar(200) NOT NULL,
`TAS_THREE` varchar(200) NOT NULL,
`TAS_FOUR` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
The following page open only when user logged in
members.php
<?php
require('includes/config.php');
//if not logged in redirect to login page
if (!$user->is_logged_in()) {
header('Location: login.php');
}
//define page title
$title = 'Members Page';
//include header template
require('layout/header.php');
?>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<h2>Member only page - Welcome <?php echo $_SESSION['username']; ?></h2>
<p><a href='logout.php'>Logout</a></p>
<hr>
</div>
</div>
<?php
// DATABASE INFORMATION
$server = '';
$database = '';
$dbuser = '';
$dbpassword = '';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($_SESSION['username']);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM members WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio1 = $row['active'];
$bio = $row['email'];
?>
SQL
CREATE TABLE `members` (
`memberID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(60) NOT NULL,
`email` varchar(255) NOT NULL,
`active` varchar(255) NOT NULL,
`resetToken` varchar(255) DEFAULT NULL,
`resetComplete` varchar(3) DEFAULT 'No',
PRIMARY KEY (`memberID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
here user name is stored in session
so i used second part of php to get user email and active
but i get following error
Internal Server Error
can someone help me whats wrong
after sucessfull login members.php should display user email from SQL
This means the ID column does not exist in the table members are you sure you spelled everything right? Are you sure the database you're working in is called members as well? It seems weird to me that you name your database and table the same. Also I noticed your session is called:$_SESSION['username'] which makes me think it consists a string and the column is called id which makes me think that it's an integer
Conclusion:
There is something wrong with your connection to mysql. We cant know what since we dont know what your table looks like. Steps to take:
Check if the column id exists
Check if the table you're working in is called: members
Check if the database you're working in is called: members
Make sure you actually compare the right value with the right column.
Offtopic:
No offense but
if you cant figure this error out by yourself, I would suggest you to actually study way more php
Stop Using mysql_ and move to mysqli_ or PDO
maybe change your mysql_numrows to mysql_num_rows.
$num = mysql_num_rows($query) or die(mysql_error());
let me know the outcome.
couldn't put it in a comment.
I've been trying to write a simple search and display site with a drop down menu, I've tried using mysqli and PDO and I'm not getting the results. I've just checked the server log in cpanel and found that the access has been denied to the results page. The access must be all right for the drop down page as it is populating the drop down list. I can't see why it is being stopped. The server is running PHP 5.3.27 and MYSQL 5.5.36.
This is the drop down.
<form action="search3.php" method="post" >
<?php
$mysqli = new mysqli('localhost','user','password','engraved_stamps');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$query = "SELECT DISTINCT Country FROM engravers ORDER BY Country";
$result = $mysqli->query($query);
?>
<select >
<?php
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['Country']}\">";
echo $row['Country'];
echo "</option>";
}
$mysqli->close();
?>
</select>
<input type="submit" name="dropdown" />
</form>
This is the results page (action for restul) (called Search3.php)
<?php
$hostname = "localhost";
$user = "user";
$password = "password";
$connection = mysqli_connect($hostname, $user, $password,);
if(!$connection){
echo"Could not connect to server";
};
mysqli_select_db($connection,'engraved_stamps');
if(!mysqli_select_db($connection,'engraved_stamps')){
echo"could not connect to database";
};
if(isset($_POST['dropdown'])){
$Country = $_POST['dropdown'];
}else{
$Country = "none";
}
$sql= "SELECT * FROM engravers WHERE Country = :Country";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Country', $Country, PDO::PARAM_STR);
$stmt->execute();
$total = $stmt->rowCount();
while ($row = $stmt->fetchObject()) {
echo $row->Country;
}
$mysqli->close();
?>
I think PDO and mysqli are different PHP extensions. You should choose only one thing to deal with your work.
e.g., you can use mysqli only, or PDO.
For more information about PDO, see: http://php.net/manual/en/pdo.construct.php
You are mixing two entirely different database extensions:
MySQL Improved Extension (aka mysqli):
$mysqli = new mysqli(...)
^^^^^^
PHP Data Objects (aka PDO):
$stmt->bindParam(':Country', $Country, PDO::PARAM_STR);
^^^
Despite your question title and tags, your code seems to use mysqli entirely. You'll just need to get rid of the PDO bits.
You're also using some undefined variables:
$stmt = $pdo->prepare($sql);
^^^^
You're apparently not getting the corresponding error messages, which suggests you haven't configured your PHP development box to do so. As soon as you do it, you'll be possibly warned of some other issues.
Sorry abas_rafiq. the comments only allow a certain number of characters.
Here is the structure:
CREATE TABLE IF NOT EXISTS engravers (
Key int(10) NOT NULL AUTO_INCREMENT,
StampImages text NOT NULL,
Images text NOT NULL,
Country text NOT NULL,
Year int(4) NOT NULL,
Description text NOT NULL,
SGNumber text NOT NULL,
ScottNumber text NOT NULL,
Engraver1Surname text NOT NULL,
Engraver1OtherNames text NOT NULL,
Engraver2Surname text NOT NULL,
Engraver2OtherNames text NOT NULL,
Engraver3Surname text NOT NULL,
Engraver3OtherNames text NOT NULL,
Designer1Surname text NOT NULL,
Designer1OtherNames text NOT NULL,
Designer2Surname text NOT NULL,
Designer2OtherNames text NOT NULL,
Printer text NOT NULL,
Notes text NOT NULL,
PRIMARY KEY (Key),
UNIQUE KEY Key (Key)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=91 ;
They were not all "Not Null" when I set it up but I see they are now.
<?php
try {
//here add user and password and database please be sure u have used correct one
$dbh = new PDO("mysql:host=localhost;dbname=engraved_stamps",'root','');
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<?php
$STM = $dbh->prepare("SELECT * FROM engravers WHERE Country = :Country");
if(isset($_POST['dropdown'])){
$Country = $_POST['dropdown'];
}else{
$Country = "name";//here you can assing % too for value of any if u need tell me to recode, NOTE here now the value u have assign is (name) is the record value on ur engravers table for column of Country.
}
$STM->bindParam(':Country', $Country, PDO::PARAM_STR);
$STM->execute();
$row= $STM->fetchAll();
if(count($row)){
foreach($row as $data){
echo $data['Country'] . "<br />";// here country is the column of ur table u can echo other columns too
}
}else {
echo 'no row found';
}
?>
I have a table with id which is the primary key and user_id which is a foreign key but the session is based on this in my code.
I have tried EVERYTHING, so I will post my full code.
The form should insert if there is not a user_id with the same session_id in the table. If there is, it should update.
At the moment, when the user has not visited the form before (no user_id in the table) and data is inserted in, the page returns to the location page: but the data is not inserted in the table. if the user changes the data once it is updated it doesn't change either.
This is the table structure:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
`complete` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
The code I have been using (and failing):
$err = array();
$user_id = intval($_SESSION['user_id']);
// otherwise
if (isset($_POST['doThesis'])) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
// check if current user is banned
$the_query = sprintf("SELECT COUNT(*) FROM users WHERE `banned` = '0' AND `id` = '%d'",
$user_id);
$result = mysql_query($the_query, $link);
$user_check = mysql_num_rows($result);
// user is ok
if ($user_check > 0) {
// required field name goes here...
$required_fields = array('thesis_Name','abstract');
// check for empty fields
foreach ($required_fields as $field_name) {
$value = trim($_POST[$field_name]);
if (empty($value)) {
$err[] = "ERROR - The $field_name is a required field" ;
}
} // no errors
if (empty($err)) {
$id = mysql_real_escape_string($_POST['id']);
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
//replace query
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query))
echo "the query failed";
else header ("location:myaccount.php?id=' . $user_id");
}}}
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");
?>
<br>
<form action="thesis.php" method="post" name="regForm" id="regForm" >
class="forms">
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) { ?>
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
Title of Proposed Thesis<span class="required">*</span>
<textarea name="thesis_Name" type="text" style="width:500px; height:150px"
id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?> </textarea>
</tr>
<tr>
<td>Abstract<span class="required">*</span>
</td>
<td><textarea name="abstract" style="width:500px; height:150px"
type="text" id="abstract" size="600"><?php echo $row_settings['abstract']; ?>
</textarea></td>
</tr>
<?php }
} else { ?>
//shows fields again without echo
I've tried var_dum($query) but nothing appears
PS I know the code isn't perfect but I'm not asking about this right now
I can't see how your replace statement will ever insert the initial row, as the where clause is always going to be false (there won't be a row with that user Id).
I think of you want to use replace you need to replace into thesis (id, userid, etc) without a where clause. If id and userid have a unique constraint and a row for userid exists then it will be updated; if it doesn't exist it will be inserted.
However- if you don't know id- which you won't if you are using auto increment, then I'm not sure you can do this with replace. See http://dev.mysql.com/doc/refman/5.0/en/replace.html
Why don't you check for the existence of a row an then use update or insert?
BTW, is the idea that a user can enter multiple theses into a form, or just one? Your table suggests they can have multiple. If this is what you are trying to achieve then I think you should be storing the id of each thesis in a hidden field as part of the form data. You would then be able to use REPLACE INTO thesis (id, user_id, thesis_name, abstract) VALUES ($id, $user_id, $thesis_name, $abstract) where id is the id of the thesis obtained from each hidden field. If this is not present, i.e. the user has entered a new thesis, then use NULL for id in the insert. This will work using the REPLACE INTO as the id column is auto increment.
Perhaps you mean user_id not id:
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE user_id='{$_SESSION['user_id']}'";
Or if you do mean the id from $_POST['id']
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE id='$id'";
Also instead of REPLACE you should use UPDATE. Im pretty sure its faster because REPLACE basically deletes the row then inserts it again, im pretty sure you need all the fields and values else your insert default values. From the manual:
Values for all columns are taken from the values specified in the
REPLACE statement. Any missing columns are set to their default
values, just as happens for INSERT
So you should use:
$query = "UPDATE thesis
SET thesis_Name='$thesis_Name', abstract='$abstract'
WHERE id='$id'";
You are doing everything right just one thing you are doing wrong
Your replace query variable is $query and you executing $the_query.
you wrong here:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query)) // this is wrong
echo "the query failed";
replace it with:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($query)) // use $query
echo "the query failed";
I'm unable to write to my database while using this script that I whipped up earlier.
<?php
include("db.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Data sent from form, then posted to "admin" table in database
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$author = mysql_real_escape_string($_POST['author']);
$image = mysql_real_escape_string($_POST['image']);
$category = mysql_real_escape_string($_POST['category']);
$sql = "INSERT INTO admin(name,description,author,image,category) VALUES('$name','$description','$author','$image','$category');";
$result = mysql_query($sql);
header("Location: video.php?file=' . $filename . '");
}
?>
And here's my SQL:
CREATE TABLE admin
(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) UNIQUE,
description VARCHAR(50) UNIQUE,
author VARCHAR(50) UNIQUE,
image VARCHAR(50) UNIQUE,
category VARCHAR(50) UNIQUE
);
Everything is submitted with POST via an HTML form. I'm not really sure what I'm doing wrong, so that why I'm wondering what you guys think. Any thoughts?
$result = mysql_query($sql) is not valid (no connection specified).
It needs to be $result = mysql_query($sql, [CONNECTION]);
There may be other issues, but that's an obvious one.
Follow these steps:
Open a MySQL connection (if not omitted in the snippet)
Check your MySQL statement by using var_dump($sql)
Check for the return value of mysql_query(), should be true if the INSERT statement succeeded.
Check for the number of rows affected by the INSERT statement: mysql_affected_rows()
Note:
I'm pretty sure that your INSERT statement fails because all your columns are defined as UNIQUE. As soon as you already have an author with the same name the statement fails!
$auhtor=mysql_real_escape_string($_POST['author']);
The Author variable is spelled wrong.