How optimize while in while code? [duplicate] - php

This question already has an answer here:
Optimize while and SQL in foreach
(1 answer)
Closed 8 years ago.
My code is :
$text = '12-10-4-32-45-name-sara-x-y-86';
$array = explode('-',$text);
foreach($array as $value) {
$sql = mysql_query("SELECT * FROM `table` WHERE `pid`='$value' ORDER BY `id` LIMIT 3");
while($row = mysql_fetch_array($sql)) {
echo $row['title'];
echo '';
}
echo '';
}
This code work full but if in $text use 150 variable , server down !
How optimize this code for most variable ?!
Thx

If you need all of them as ids (which includes a string which is weird). Consider this example:
$text = '12-10-4-32-45-name-sara-x-y-86';
$text = array_unique(explode('-', $text)); // just in case there are duplicate ids
$statement = 'SELECT * FROM `table` WHERE `pid` IN("'.implode('", "', $text).'") ORDER BY `id` LIMIT 3';
// should be like this
// SELECT * FROM `table` WHERE `pid` IN("12", "10", "4", "32", "45", "name", "sara", "x", "y", "86") ORDER BY `id` LIMIT 3
// then just continue on your mysql_query
$sql = mysql_query($statement);
while($row = mysql_fetch_assoc($sql)) {
// print your values or whatever it is you need to do
// echo $row['title'];
}
Note: You don't need to query each value, that would be a total waste of resources. Imagine your text has (as you said) 150 numbers. Try to use the IN() of mysql so that it just make a single trip of query.

Related

Im having trouble with selecting data from database using like and order by

Im making a filter where you can select colors and select newest. It would filter them, but the order by doesn't work for some reason.
I tried it this way. It outputs the colors that match the database table, but it doesn't sort them by date.
$color_arr = ["red", "blue", "white"];
foreach($color_arr as $color) {
$data = $conn->query("SELECT * FROM `prod_items` WHERE item_color LIKE '%$color%' ORDER BY `item_date` DESC");
while ($row = $data->fetch()) {
print_r($row);
}
}
You can order by multiple fields, below is the MYSQL query:
SELECT * FROM `prod_items` WHERE item_color LIKE '%$color%' ORDER BY `item_date` DESC, `price` DESC"
This will first sort by item_date and then by price.
Don't run sql query inside loop.
$sql = array('0'); // Stop errors when $color_arr is empty
$color_arr = ["red", "blue", "white"];
foreach($color_arr as $color){
$sql[] = 'item_color LIKE "%'.$color.'%"';
}
$sql1 = implode(" OR ", $sql). " ORDER BY `item_date` DESC";
$sql = "SELECT * FROM `test` WHERE $sql1";
$data = $conn->query($sql);
while ($row = $data->fetch_array()) {
print_r($row);
}

MySQL query with and array [duplicate]

This question already has answers here:
Array in SQL Query? [duplicate]
(4 answers)
Closed 5 years ago.
I'm trying to create a tag function in my webpage and I'm using an array of tags to query the database.
array[tag1, tag2, tag3];
The tags are created in a field
what I'm trying to archive is something like
$query = "SELECT * FROM TABLE WHERE `Tags` = '$tag1' AND '$tag2' AND '$tag3'";
Except with an array, so
$query = "SELECT * FROM TABLE WHERE `Tags` = $array[]";
Thanks
$tag = $_POST['tag'];
$query = "SELECT * FROM ComicStripTags WHERE `Tag` = '$tag'";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
$ID[] = $row['ImageID'];
print_r ($ID);
}
BTW I want to use $ID[] to use in another query
Try using implode to convert array to string, and use "IN" operator instead of equal:
$query = "SELECT * FROM TABLE WHERE `Tags` in (". implode(", ",$array) .")";

How to use PDO prepared statements with IN clause? [duplicate]

This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Closed 1 year ago.
I stored some data in a field inside MySQL in this format: 1,5,9,4
I named this field related. Now I want to use this field inside an IN clause with PDO. I stored that field contents in $related variabe. This is my next codes:
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (?) LIMIT 4";
$q = $db->prepare($sql);
$q->execute(array($related));
echo $q->rowCount();
But after executing this code, I can fetch only one record whereas I have to fetch 4 records (1,5,9,4). What did I do wrong?
using named place holders
$values = array(":val1"=>"value1", ":val2"=>"value2", ":val2"=>"value3");
$statement = 'SELECT * FROM <table> WHERE `column` in(:'.implode(', :',array_keys($values)).')';
using ??
$values = array("value1", "value2", "value3");
$statement = 'SELECT * FROM <table> WHERE `column` in('.trim(str_repeat(', ?', count($values)), ', ').')';
You need as many ? placeholders as your "IN" values.
So:
$related = array(1,2,3); // your "IN" values
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (";
$questionmarks = "";
for($i=0;$i<count($related);$i++)
{
$questionmarks .= "?,";
}
$sql .= trim($questionmarks,",");
$sql .= ") LIMIT 3;";
// echo $sql; // outputs: SELECT id,title,pic1 FROM tbl_products WHERE id IN (?,?,?) LIMIT 3;
$q = $db->prepare($sql);
$q->execute($related); // edited this line no need to array($related), since $related is already an array
echo $q->rowCount();
https://3v4l.org/No4h1
(also if you want 4 records returned get rid of the LIMIT 3)
More elegantly you can use str_repeat to append your placeholders like this:
$related = array(1,2,3); // your "IN" values
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (";
$sql .= trim(str_repeat("?,",count($related)),",");
$sql .= ") LIMIT 3;";
// echo $sql; // outputs: SELECT id,title,pic1 FROM tbl_products WHERE id IN (?,?,?) LIMIT 3;
$q = $db->prepare($sql);
$q->execute($related); // edited this line no need to array($related), since $related is already an array
echo $q->rowCount();
https://3v4l.org/qot2k
Also, by reading again your question i can guess that your $related variable is just a string with value comma-separated numbers like 1,40,6,99. If that's the case you need to make it an array. do: $related = explode($related,","); to make it an array of numbers. Then in your execute method pass $related as-is.

php return last row with truncate (sbstr)

I've got just a quick problem. I've got code that returns the last post for separate titles for a forum. I want to limit the number of characters shown and put the (... …).
I'm having difficulty with a nested if statement in my while loop:
$query = "SELECT comment FROM Assembly WHERE title = 'Checkered' ORDER BY date DESC LIMIT 1";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($message))
{
if(strlen($message) > 10)
{
echo substr($message, 0, 10)."…";
}
else
{
echo "Last Post:<br>";
echo strip_tags("{$row['comment']}");
}
}
thanks in advance :)
**edit
yes css text-overflow:ellipsis; works great!! Thanks guys
***edit working code incase you want
$query = "SELECT comment FROM Assembly WHERE title = 'Checkered' ORDER BY date DESC LIMIT 1";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$comment = strip_tags($row['comment']);
if(strlen($comment) > 30)
{
echo substr($comment, 0, 30)."...";
}
else
{
echo "Last Post:<br>";
echo $comment;
}
}
The problem you have with your code is that you have some badly named variables. You assign the result resource returned by mysql_query() to $result, you then try and fetch a row from a variable called $message (which you don't show the assignment of) and you then switch to treating $message as if it were a string, rather than manipulating the value in $row.
Regardless of that, if you just want to fetch the string from the DB and apply an ellipsis, and you don't need the full text, I would get MySQL to do the work for me:
SELECT IF(CHAR_LENGTH(`comment`) > 10, CONCAT(SUBSTRING(`comment`, 1, 10), '...'), `comment`) AS `comment`
FROM `Assembly`
WHERE `title` = 'Checkered'
ORDER BY `date` DESC
LIMIT 1
In PHP:
$query = "
SELECT IF(CHAR_LENGTH(`comment`) > 10, CONCAT(SUBSTRING(`comment`, 1, 10), '...'), `comment`) AS `comment`
FROM `Assembly`
WHERE `title` = 'Checkered'
ORDER BY `date` DESC
LIMIT 1
";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo "Last Post:<br>";
echo htmlspecialchars($row['comment']);
}
EDIT
Following #Jared's comments about the potential for broken strings displaying partial HTML tags, here is the way to do it that will avoid this:
$query = "
SELECT `comment`
FROM `Assembly`
WHERE `title` = 'Checkered'
ORDER BY `date` DESC
LIMIT 1
";
$result = mysql_query($query);
// Loop is pointless because of the LIMIT 1
$row = mysql_fetch_assoc($result);
$maxlen = 10; // Max length before trim
$comment = strip_tags($row['comment']);
if (strlen($comment) > $maxlen) {
$comment = substr($comment, 0, $maxlen).'...';
}
$comment = htmlspecialchars($comment);
echo "Last Post:<br>";
echo $comment;
You give nout over as to the problem but I am going to go out on a limb and guess the problem. Try this:
while($row = mysql_fetch_assoc($message))
{
$comment = strip_tags($row['comment']);
if(strlen($coment) > 10)
{
echo substr($comment, 0, 10)."...";
}
else
{
echo "Last Post:<br>";
echo $comment;
}
}

Array in SQL Query? [duplicate]

This question already has answers here:
Passing an array to a query using a WHERE clause
(17 answers)
Closed 8 years ago.
i have a problem making a SQL Query with an array in my WHERE clause.
For example:
My Array:
$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
My MySQL Statement:
SELECT * FROM myTable WHERE title='".$myarray[]."'
Is there any way to realize that?
I solved it myself like this:
for(...) {
$where = $where." title='".$myarray[$count]."' OR ";
}
$where = substr($where , 0, -3);
.....
SELECT * FROM myTable WHERE ".$where."
But if i had thousands of entries in my array, the SQL Statement would be too big and slow, right?
Thanks
You can use mysql's IN-function
EDIT: As amosrevira said, you need to escape you strings in the array.
$myarray[1] = "'hi'";
$myarray[2] = "'there'";
$myarray[3] = "'everybody'";
$newarray = implode(", ", $myarray); //makes format 'hi', 'there', 'everybody'
SELECT * FROM myTable WHERE title IN ($newarray);
$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
//every quoted string should be escaped according to SQL rules
foreach($myarray as $key => $val) {
$myarray[$key] = mysql_real_escape_string($val);
}
$in_str = "'".implode("', '", $myarray)."'"; //makes format 'hi', 'there', 'everybody'
SELECT * FROM myTable WHERE title IN ($in_str);
You can try use of IN in your WHERE clause,
SELECT * FROM myTable WHERE title IN ('hi', 'there', 'everybody');
or
SELECT * FROM myTable WHERE title IN ('.implode(',', $myarray).');
You can us the IN operator. You want it to look like:
title IN ('hi', 'there', 'everybody')
So you'd do something like:
$sql = "SELECT * FROM myTable WHERE title IN '" . implode("','", $myarray) . "';"
Note that you need to filter your array for SQL injection issues first.

Categories