select data when id is letters - not numbers - php

How can i use letters instead of numbers when selecting data from MySql?
This is working:
<?php
$page = '1001';
$result = mysqli_query($con,"SELECT * FROM `comment` WHERE `page` = $page LIMIT 1001");
?>
but not if $page = 'page_one'.. The row 'page' is VARCHAR (30)
EDIT - trying to clarify question:
This is what i would like to do, but its not working - gives an error:
$page = 'page_one';
$result = mysqli_query($con,"SELECT * FROM `comment` WHERE `page` = $page LIMIT page_one");

You should really use prepared statements:
$page = 'abcd';
$stmt = $con->prepare("SELECT * FROM `comment` WHERE `page` = ? LIMIT 1001"));
$stmt->bind_param("s", $page);
$stmt->execute();

Simply add ' around your parameter when its a string and not an integer:
$page = "somerandomtext";
SELECT * FROM `comment` WHERE `page` = '$page' LIMIT 1001

What he meant was:
<?php
$page = '1001';
$result = mysqli_query($con,"SELECT * FROM `comment` WHERE `page` = '$page' LIMIT 1001");
?>
That way the Query String will contain the ' characters..

Related

get result of query step by step codeigniter

I need to do something like this:
if (isset($account)) {
$this->db->where('account', $account);
}
if (isset($subject)) {
$this->db->where('subject', $subject);
}
if (isset($contact)) {
$this->db->where('_from', $contact);
}
//here i need to get result
$resul1 = $this->db->get('table');
$limit = 5; $offset =10;
$this->db->limit($limit, $offset);
//here i need to get result with offset and limit
$result2 = $this->db->get('table');
$result1 should execute this query
SELECT *
FROM `table`
WHERE `account` = 'some account'
AND `subject` = 'some subject'
AND `_from` = 'name'
and $result2 should execute this query ($query1 + offset and limit):
SELECT *
FROM `table`
WHERE `account` = 'some account'
AND `subject` = 'some subject'
AND `_from` = 'name'
LIMIT 10, 5
but $result2 execute as a separate query: select * FROM table LIMIT10, 5
is it possible to achieve this or I need to start the query from the begining?
LIMIT Without limit() Function
result = $this->db->get('table', 0, $offset);
Or using manual select:
$query = "SELECT *, COUNT(account) AS total FROM `table` WHERE `account` = ? AND `subject` = ? AND `_from` = ? LIMIT 0, ?";
$result = $this->db->query($query, array($account, $subject, $contact, $offset));

PHP and MySQL: How to get all database entries form two tables?

I have the following code which gets data from a table entry and displays some html for each entry. It works fine but i want it to display html for the entries in that table AND another table. I could just duplicate this code and change it a bit to get the entries in a different table but that creates another problem, all the entries from the second table would start at the end of the entree list from the first table. How can I display the entries from both table in the order of most relevant to what the user types in? Here is my code that just displays entries from the first table in order of when they were inserted into the table. Can someone tell me how to display all the entries from two different tables in order of relavace to a user search query? My code so far, I have not been able to get much further than this.
$pagesQuery = mysql_query("SELECT count(id) FROM(`posts`) WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '%{$terms}%'");
$pageNum = ceil(mysql_result($pagesQuery, 0)/5);
$start = (($page-1)*5);
$currentname = mysql_query("SELECT * FROM `posts` WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '%{$terms}%' LIMIT $start, 5");
while ($row = mysql_fetch_array($currentname)) {
//recieve relevant data.
$title = $row[0];
$desc = $row[13];
$ID = $row[6];
$views = $row[3];
$user = $row[7];
$type = $row[15];
//fetch the last id from accounts table.
$fetchlast1 = mysql_query("SELECT * FROM allaccounts WHERE id=(SELECT MAX(id) FROM allaccounts)");
$lastrow1 = mysql_fetch_row($fetchlast1);
$lastid1 = $lastrow1[6];
//acquire the username of postee.
for ($i1=1; $i1 <= $lastid1; $i1++) {
$currentname1 = mysql_query("SELECT * FROM allaccounts WHERE id=$user");
while ($row1 = mysql_fetch_array($currentname1)) {
$username1 = $row1[0];
}
}
//Format Title, description and view count.
$title2 = rtrim($title);
$donetitle = str_replace(" ", "-", $title2);
$donetitle1 = str_replace(".", "", $donetitle);
$donetitle2 = str_replace("-", "-", $donetitle1);
$donetitle3 = str_replace(":", "-", $donetitle2);
$url = "articles/".$ID."/".$donetitle3."";
$donetitle = strlen($title) > 40 ? substr($title,0,40)."..." : $title;
$donedesc = '';
if(strlen($desc) > 150) {
$donedesc = explode( "\n", wordwrap( $desc, 150));
$donedesc1 = $donedesc[0] . '...';
} else {
$donedesc1 = $desc;
}
$SRCIMG = '';
$finviews = number_format($views, 0, '.', ',');
if($type == '1'){
$SRCIMG = "img/icons/video.png";
} else {
$SRCIMG = "img/icons/article.png";
}
//Give results
if($row[10] == null){
$SRC = "img/tempsmall.jpg";
}else{
$SRC ="generateThumbnailSmall.php?id=$ID";
}
echo "<div id = \"feature\">
<img src=\"$SRC\" alt = \"article thumbnail\" />
<img src=\"$SRCIMG\" alt = \"icon\" id=\"icondisp\"/>
</div>
<div id = \"feature2\">
$donetitle
<p id=\"resultuser\" >$username1</p>
<p id=\"resultp\">$donedesc1</p>
<img src=\"img/icons/flag.png\"/><b id=\"resultview\">$finviews views</b>
</div>
<div id = \"border\"></div>";
}
In this case you ought to use UNION to merge SELECT results from two or more tables.
So you query should look like this:
(SELECT *
FROM `posts`
WHERE `title` LIKE '%{$terms}%'
OR `descrip` LIKE '%{$terms}%')
UNION
(SELECT *
FROM `posts2`
WHERE `title` LIKE '%{$terms}%'
OR `descrip` LIKE '%{$terms}%')
LIMIT $start, 5
Notice that number and names of columns in both SELECTS should be the same.
Why not try union ?
SELECT * FROM `posts` WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '% {$terms}%'
union
SELECT * FROM `otherposts table` WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '%{$terms}%'
order by yourRelevanceField
LIMIT $start, 5"
Actually it just hit me, I should probably create a new table called SearchElements where I store data needed for a search result. I would create a SearchElement each time an entree is added to either table. still dont understand relevance yet though.
Well you can go for UNION of two tables and try something like this
INSERT INTO table3
SELECT * FROM tabel1
UNION
SELECT * FROM tabel2

How to update a row in sql with loop?

I'm trying to figure how to call a query once.
I have 6 different variables for images, title and desc.
In this code, I need to know how to loop for id from 0 to 6.
$date = new DateTime("NOW");
$image1 = 'SSSS';
$title1 = 'AAAA';
$desc1 = 'BBBB';
$image2 = 'RRRR';
$title2 = 'GGGG';
$desc2 = 'VVVV';
/// 4 vars later....
$id = 6;
$get = $this->db->queryRow("UPDATE `featured` SET `image` = '{$image.$id}', `title` = '{$title.$id}', `desc` = '{$desc.$id}', `date` = '{$date->format('Y-m-d H:i:s')}' WHERE id = '{$id}'");
return(object) $get;
To build a collection of Querys use the multi_query function.
Loop to build your Query string to pass to the db and concatenated by a semicolon.
<?php
for($i=0;$i <= $maxquerys;$i++){
$query = "UPDATE `featured` SET `image` = '".$image.$id."', `title` = ".$title.$id."', `desc` = '".$desc.$id."', `date` = '".$date->format('Y-m-d H:i:s')."' WHERE id = '".$id."';"
}
/* execute multi query */
if ($mysqli->multi_query($query)) {
while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
you may check also the result by
echo $mysqli->affected_rows;
?>
I have tried to use a simple $query model and it works fine.
Create a valid Query string to pass to the db
<?php
$query = "UPDATE `featured` SET `image` = '".$image.$id."', `title` = ".$title.$id."', `desc` = '".$desc.$id}."', `date` = '".$date->format('Y-m-d H:i:s')."' WHERE id = '".$id."';"
$result=$mysqli->query($query);
// Verify results
if(!$result) {
$ErrMessage = "ErrSqlQuery:" . $mysqli->error . "\n";
$mysqli->close();
die($ErrMessage);
}
you can check also the result by
echo $mysqli->affected_rows;
?>
$query_build = "";
foreach($arr as $$image){
$query_build .= "UPDATE `featured` SET `image` = '{$image.$id}', `title` = '{$title.$id}', `desc` = '{$desc.$id}', `date` = '{$date->format('Y-m-d H:i:s')}' WHERE id = '{$id}';";
}
$get = $this->db->queryRow($query_build);
Accumulate all the queries and execute all at once.

Fast random row in MySql

I need to generate a random row from my MySql database and i have found example here:
http://akinas.com/pages/en/blog/mysql_random_row/
And i want to use solution 3 which looks like this:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `users` LIMIT $offset, 1 " );
My code looks like this now:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( "SELECT * FROM `users` WHERE profile_image='2' LIMIT $offset, 1 " );
$random_date = mysql_fetch_array($result);
echo $random_date['user_name']; //display username of random user
But when i refresh the page: approximatly 7 of 10 times nonthing shows up. No username at all and also im trying to print out the id of the user but it's also empty.
It seems that it's not getting anything at all from the database when refreshing and sometimes it get's data from the database. Any idea why this might happen?
In this particular case, the problem is that you're working with two different queries; the first query is:
SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users`
Whereas the second one includes a condition:
SELECT * FROM `users` WHERE profile_image='2' LIMIT $offset, 1
^^^^^^^^^^^^^^^^^^^^^^^
Both queries should operate over the same result set.
Its because in your first query you dont have a where, but in the second query you do.
if you have 50 rows and only 15 with profile_image = 2 That will be the reason why most appear as nothing.
Your query becomes LIMIT 30,1 when there are only 15 results for example
Make sure the same where is used in both queries.
Also avoid using mysql_* functions in new code
The solution for my problem was this, BIG thanks to: #Jack
This query will find random row in a mysql table very fast.
$gender_search = $logged_in_user['gender_search'];
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` WHERE profile_image='2' AND gender='$gender_search'");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( "SELECT * FROM `users` WHERE profile_image='2' AND gender='$gender_search' LIMIT $offset, 1 " );
$random_date = mysql_fetch_array($result);
I have now converted this string to PDO if someone needs it.
$statement = $dbConn->prepare("SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` WHERE profile_image=? AND gender=?");
$statement->execute(array('2',$logged_in_user['gender_search']));
$offset_row = $statement->fetch(PDO::FETCH_OBJ);
$offset = $offset_row->offset;
$statement2 = $dbConn->prepare("SELECT * FROM `users` WHERE profile_image=? AND gender=? LIMIT ?, 1");
$statement2->execute(array('2', $logged_in_user['gender_search'], $offset));
$random_date = $statement2->fetch(PDO::FETCH_BOTH);

Mysql query with multiple ands and ors

I'm trying to make a filter function for servers on my site. Users are able to check different options for the categories they want to filter for, and I have an ajax request that returns the servers satisfying their conditions. However, my mysql_query isn't working, I think I might have the wrong syntax.
By default, each category has the option set as 1. My current query is:
$order = "SELECT * FROM `servers`
WHERE `size` = '$size' or
1 = '$size' and
`type` = '$type' or
1 = '$type' and
`mode` = '$gamemode' or
1 = '$gamemode' and
`main` = '$main' or
1 = '$main'
ORDER BY $orderby
LIMIT 5";
It doesn't seem to get the correct servers, do I have an error in my query?
Thanks!
When mixing and and or in your query you must use parenthesis to group the conditions. Also, I think when you say 1 = '$size', I think you mean `size`=1.
$order = "SELECT * FROM `servers`
WHERE
(`size` = '$size' or `size` = '1') and
(`type` = '$type' or `type` = 1) and
(`mode` = '$gamemode' or `mode`= 1 ) and
(`main` = '$main' or `main` = 1)
ORDER BY $orderby
LIMIT 5";
"SELECT * FROM `servers` WHERE
`size` in ('$size', 1) and
`type` in( '$type' ,1) and
`mode` in('$gamemode' ,1) and
`main` in ( '$main' , 1 )
ORDER BY $orderby LIMIT 5";
You need to add parentheses because or and and have a different order of operations and needs parentheses to allow what you are needing to accomplish
SELECT * FROM `servers` WHERE
(`size` = '$size' or 1 = '$size') and
(`type` = '$type' or 1 = '$type') and
(`mode` = '$gamemode' or 1 = '$gamemode') and
(`main` = '$main' or 1 = '$main')
ORDER BY $orderby LIMIT 5
you must have to use brackets to use multiple OR condition in query
like
mysql_query("SELECT * FROM servers WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo')");
you can change with your column name
and also you can use IN condtion like
mysql_query("SELECT * FROM servers WHERE email='$Email' AND date IN ('$Date_Today','$Date_Yesterday','$Date_TwoDaysAgo')");
pls let me know if i can help you more
Just try to put brace around the or conditions
$order = "SELECT * FROM `servers` WHERE (`size` = '$size' or 1 = '$size') and (`type` = '$type' or 1 = '$type') and (`mode` = '$gamemode' or 1 = '$gamemode') and (`main` = '$main' or 1 = '$main') ORDER BY '$orderby' LIMIT 5";

Categories