Hi i need to do a request to mysql to get some data where filed name = $letter
but the variable $letter may contain '
my problem is this i try to use this :
$letter = mysqli_real_escape_string($conn,strtolower($letter));
$us = $conn->query("SELECT id FROM singers where trim(LOWER(name)) = '".$letter."'");
My problem is in if $letter was I'm legend, after executing this line it become I\'m legend so it can't be find in database because in database it's stored as i'm legend
how i can resolve this and get right result.
echo $letter;
$letter = mysqli_real_escape_string($conn,strtolower($letter));
echo $letter;
RESULT
i'm
i\'m
why you have used
trim and LOWER in your column name
"SELECT id FROM singers where trim(LOWER(name)) = '".$letter."'" //why trim and LOWER
use this
"SELECT id FROM singers where name = '".$letter."'"
Also try this like
$letter = mysqli_real_escape_string($conn,strtolower($letter));
$sql = "SELECT id FROM singers where name = '".$letter."'";
// echo $sql; die; print this and run in phpmyadmin to check
$us = $conn->query($sql);
if ($us !== false) {
echo 'done';
}
else{ die('failed!' . mysqli_error($conn));}
there is difference between field and value in where
the \ added is the problem
Related
I am trying to code it so users can type in their -- or others -- usernames which will be converted in their UUID then returns that user's stats from my MySql databse.
The code I attempted this with is
$username = $_POST['searchbox'];
$json = file_get_contents("https://api.mojang.com/users/profiles/minecraft/".$username);
$obj = json_decode($json);
$id = $obj->id;
$rank = Database::query("SELECT * FROM playerdata WHERE uuid=:uuid", array(':uuid'=>"".$id))[0]['rank'];
echo 'Showing results for '.$_POST['searchbox'].' '.$id.' Rank: '.$rank;
Except when I run this code it outputs:
"Showing results for kingbluesapphire 0d8d246d11c54cbbb197c6bc8ba01ee2 Rank:"
I know it's not a problem with the connection to the database because other queries are working
My goal right now is to get the field in the MySql Database thats called rank and I would like to display their rank.
Given the discussion in the comments, either you have to find out what is removing the dashes which I highly recomend to or change your query to:
$rank = Database::query("SELECT *
FROM playerdata
WHERE replace(uuid, '-','')=:uuid",
array(':uuid'=>"".$id))[0]['rank'];
Databases need to be given the exact value you are looking for, any different character in a equals operation will not give you any data.
It's more like:
<?php
if(isset($_POST['searchbox']){
$sb = $_POST['searchbox']);
$json = json_decode(file_get_contents("https://api.mojang.com/users/profiles/minecraft/$sb"));
if($queryRes = $connection->query("SELECT * FROM playerdata WHERE uuid={$json->id}")){
if($queryRes->num_rows){
$o = $queryRes->fetch_object(); // guessing there's only one row or you would put this in a while loop
echo "Showing results for $sb {$o->uuid} Rank:{$o->rank}";
}
}
else{
die($connection->connect_error);
}
}
?>
I'm assuming uuid is a number. Do tell.
We have a page tcount.php where we fetch counts for BOTH keyword1 and keyword2 occuring anywhere in a text field in mysql database using php script. The counts are displayed as hyperlinks. Now after that, we want that if someone clicks on the hyperlinks, they will see the detailed results in showt.php page showing those rows of the database corresponding to only those text field containing BOTH keywords.
The url of the second page showt.php is like
http://www.example.com/page.php?keyword=keyword1+keyword2
But problem is that it shows only those results which have keyword1 and keyword2 next to each other.
For example, keyword1 is car and keyword2 is cap and our text fields are as follows -
car cap
car best cap
car new
Then, we want it to show 1. and 2. as results but it is showing only no. 1 in the results page.
Please help.
Edit -
This is the code in page 1 tcount.php -
$kewyWordQ = $db->query("SELECT keywords FROM Table1 ");
<?php
while($row = $kewyWordQ->fetch(PDO::FETCH_ASSOC))
{$keyWord = $row['keywords'];
$keyWordsArr = explode(" ", $row['keywords']);
$countData = array();
$keyIndex = 0;
$tIndices = array();
$tArr = array();
$tIndices[] = "-1";
foreach($keyWordsArr as $keyword)
{
$t = $db->query("SELECT user_name FROM Table2 WHERE
t_text LIKE '%$keyWordsArr[$keyIndex]%'");
$tArr[] = $t;
while($row2 = $tweet->fetch(PDO::FETCH_ASSOC))
{
$found = TRUE;
foreach($keyWordsArr as $keyword1)
{
$ret = strpos(strtolower($row2['t_text']),
strtolower($keyword1));
if(($ret == 0) &&
strcmp(strtolower($row2['t_text'][0], strtolower($keyword1)[0])))
{
$found = FALSE;
break;
}
}
if($found == TRUE)
{
$ret = strpos($tIndices, $row2['t_id']);
if(($ret == 0) && strcmp($tIndices[0],
$row2['t_id']))
{
$tIndices[] = $row2['t_id'];
$countData[] = $row2['user_name'];
}
}
}
$keyIndex++;
}
?>
<tr><td><?php echo $row['keywords'];?></td>
<td><a href="showt.php?keyword=<?php echo
urlencode($keyWord); ?>" target="_blank"><?php echo count($countData); ?
></a></td>
<td><a href="showt.php?keyword=<?php echo
urlencode($keyWord); ?>" target="_blank"><?php echo
count(array_unique($countData)); ?></a></td>
</tr>
<?php } ?>
And this is the code in page 2 showt.php -
$keywords = $_GET['keyword'];
$sql="SELECT col1, col2, col3 from t AS s INNER JOIN users AS p ON
s.user_name=p.user_name where s.t_text LIKE '%$keywords%'
The WHERE statement of your query should look like:
WHERE my_text_field LIKE ?
and the binded parameter should be %$keyword1%$keyword2%
In order to define the $keyword1 and $keyword2 variables you can do something like:
list($keyword1, $keyword2) = explode(' ', $_GET['keyword']);
or you can simply use "%" . implode('%', explode(' ', $_GET['keyword'])) . "%" in case you have multiple possible keywords
There is a two way
one is hard way doing by php and mysql
$keyword = $_GET('keyword');
$keywordArray = explode(" ",$keyword);
$queryString = "";
foreach($keywordArray as $key=>$value) {
$queryString .= " column_name LIKE '%$value%' OR";
}
"SElECT * FROM table WHERE ".$queryString
second is mysql itself, that is Full text search
I'm trying to list data from my database, and I need to use variables inside of my array, but when echoing it I want it to remove the last comma but it doesn't seem to work.
$forum_usersonline = $kunaiDB->query("SELECT * FROM users WHERE user_loggedin = '1'");
while($forum_usersonline_fetch = $forum_usersonline->fetch_array()) {
$usersonlineuname = $forum_usersonline_fetch["user_name"];
$onlinelist = array($usersonlineuname, ' ');
echo implode($onlinelist, ',');
}
It always returns with user1, user2, so how should I do it?
Your can do this job easily in sql. If your database is mysql try following
SELECT GROUP_CONCAT(user_name) as user_name FROM users WHERE user_loggedin = '1'
or if your database is postgres try following
SELECT string_agg(user_name, ',') as user_name FROM users WHERE user_loggedin = '1'
above query result return comma separated user_name.
You could use chop(); which removes characters from the right end of a string.
An example:
<?php
$str = "Random String Ending With,";
echo $str . "<br>";
echo chop($str,",");
?>
Or you could use rtrim(); like:
<?php
$str = "Random String Ending With,";
echo $str . "<br>";
echo rtrim($str,',');
?>
Or you could also use substr like:
<?php
$str = "Random String Ending With,";
echo substr($str,0,-1)."<br>";
?>
use rtrim(string,',')
For reference goto http://www.w3schools.com/php/func_string_rtrim.asp
The problem is you're doing the implode inside the while loop, it should be done outside after building your final array. This is what I would do:
$forum_usersonline = $kunaiDB->query("SELECT * FROM users WHERE user_loggedin = 1");
while ($row = $forum_usersonline->fetch_array()) {
$onlinelist[] = $row["user_name"];
}
echo implode($onlinelist, ",");
However, this should not be the case as you should be using CONCAT when doing your database query.
EDIT1 : used double quotes and single quotes but I am getting same error.
EDIT2 : same query is returning me result in mysql shell
I am selecting a row from a table.
if(!isset($_GET['title']) || !isset($_GET['user'])){
echo "hi"; //something come here
}
else{
$title = $_GET['title'];
$title = mysqli_real_escape_string($conn,$title);
$user = $_GET['user'];
$user = mysqli_real_escape_string($conn,$user);
echo $title ;
echo $user ;
// tried giving value directly to test but no luck
$query = "SELECT * FROM site WHERE client=\"Chaitanya\" && title=\"werdfghb\" ";
$result5 = mysqli_query($conn,$query) or die(mysqli_error());
$count = mysqli_num_rows($result5);
echo $count ;
while($result9 = mysqli_fetch_array($result5)){
$kk=$result9['url'];
echo $kk ;
}
$page = $kk;
include ( 'counter.php');
addinfo($page);
}
In my database there is a row with columns title and client and the values I entered are in that row but when I echo count(no of rows) it is showing zero.
Is there anything wrong with code ?
The error you are getting is due to the line
$page = $kk;
in this code $kk is not declared previously. The defined $kk is in the while loop scope.
declare the variable like this in the outer scope from the while loop
...
$kk = null;
while($result9 = mysqli_fetch_array($result5)) {
$kk = $result9['url'];
echo $kk ;
}
$page = $kk;
...
Error on Fetching Data
You have to crack you SQl into smaller pieces and test the code like this.
run the query SELECT * FROM site without any where and get the count
run the query SELECT * FROM site WHERE client='Chaitanya' and get the count
SELECT * FROM site WHERE title='werdfghb' and check the count
Then run the whole query
And see the results. This way u can find out in where the issue is in your SQL code. I prefer you use the mysql client to execute this queries
As I pointed out in my comment, $kk is undefined in the $page = $kk;, since it is declared in the while loop.
Do something like:
$kk = ''; //can also do $kk=NULL; if you want.
while($result9 = mysqli_fetch_array($result5)) {
$kk=$result9['url'];
echo $kk ;
}
$page = $kk;
try this one
$client = "Chaitanya";
$title = "werdfghb";
$query="SELECT * FROM site WHERE client='".$client."' and title='".$title."' ";
you can also use this
$query="SELECT * FROM site WHERE client={$client} and title={$title} ";
i am doing a project where one may update the name, position, department and tag of the employee.
But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.
my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.
my php code (it now updating) but errors found:
<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);
if(isset($_POST['submitted']))
{
$sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
$result = mysql_query($sql) or die (mysql_error());
if(!$result || mysql_num_rows($result) <= 0)
{
return false;
}
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";
mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
}
?>
*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help
MisaChan
You use $_POST for 'name/pos/dep/tag' and $_GET for 'emp' so you're probably not getting the values.
Change the GETs to POST - that should do it.
Since you're updating, I'd recommend using POST over GET.
GET is more appropriate for searching.
Also, you can put all your update queries into one update query.
Like so.
$name = $_POST['name'];
$pos = $_POST['pos'];
$dep = $_POST['dep'];
$tag = $_POST['tag'];
$emp = $_POST['emp'];
$qry_start = "UPDATE gpl_employees_list SET ";
$where = " WHERE emp_id = $emp";
$fields = "";
$updates = "";
if($name){
$updates .= " `emp_name` = $name,";
}
if($pos){
$updates .= " `emp_pos` = $pos,";
}
if($dep){
$updates .= " `emp_dep` = $dep,";
}
if($tag){
$updates .= " `emp_tag` = $tag,";
}
$updates = substr($updates, 0, -1); //To get rid of the trailing comma.
$qry = $qry_start . $updates . $where;
this is what i used to keep it working :) i hope this could be a source for others as well :)
$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos'] = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep'] = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag'] = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val
$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
$queryString .="`".$key."`='".$val."',";
}
}
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
After making changes to an SQL database, remember to commit those changes, otherwise they'll be ignored.