I have this simple PHP code:
$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5");
$query2 = mysql_fetch_assoc($quer);
print_r($query2);
It only returns this:
Array ( [title] => Kill Bill Vol 1. [url_title] => kill_bill_vol_1 )
I have 3500+ rows in the table, and running the SQL in PhpMyAdmin works perfectly.
$query = mysql_query("SELECT `title`,
`url_title`
FROM `fastsearch`
WHERE `tags`
LIKE '%$q%'
LIMIT 5");
while ($row = mysql_fetch_assoc($query)) {
print_r($row);
}
You misspelled $query in your example
mysql_fetch_assoc() will return a row each time it is called, and FALSE when out of rows. Use that to your advantage, by assigning a variable to it in the condition. Within the while() loop, $row will be the current row.
Right, you are not fetching the results properly.
mysql_fetch_assoc() only returns one row at a time. Use a loop to read all rows.
$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5");
$resultSet = array();
while ($cRecord = mysql_fetch_assoc($query)) {
$resultSet[] = $cRecord;
}
As documentation http://php.net/manual/en/function.mysql-fetch-assoc.php states:
mysql_fetch_assoc — Fetch a result row as an associative array
So if you want to iterate over result you have to use a loop e.g.:
while ($row = mysql_fetch_assoc($result)) {
echo $row["title"];
echo $row["url_title"];
}
mysqli_fetch_assoc() is functions which is fetching multiple records
and displaying through print_r().
$query = "SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5";
$result = mysqli_query($conn,$query);
while(null ! == ($query = mysqli_fetch_assoc($result))){
print_r($query);
}
the method fetch_assoc() returns one row, you need to loop with it
Related
I have a for loop in PHP in which each time it runs, it executes a modified SQL statement and returns the result. The modification is comparing a field in my database to an element in an array, but I get the error message
Warning: Array to string conversion in ...
I only want to return the first row from the query so I am not using a while loop.
Array declaration:
$sql = "SELECT usersID FROM users";
$result = mysqli_query($conn, $sql) or die("Bad Query: $sql");
$ids = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$ids[] = $row;
}
}
For Loop:
$count = mysqli_num_rows($result);
for($i = 0; $i < $count; $i++){
$sql2 = "SELECT * FROM messages
WHERE (messagesFrom LIKE 'echo $messagesFrom' AND messagesTo LIKE '$ids[$i]')
OR (messagesFrom LIKE '$ids[$i]' AND messagesTo LIKE '%$messagesFrom%')
ORDER BY messagesID DESC";
$result2 = mysqli_query($conn, $sql2) or die("Bad Query: $sql2");
$row2 = mysqli_fetch_assoc($result2);
print($row2);
}
I have tried a foreach loop but there is no change in my error message. I don't believe using implode() would work because I do not want to join the entire array together, I want to compare each individual element in the array.
$ids[$i] is an array containing the row of the table. Even when you're only selecting a single column, mysqli_fetch_assoc() returns an array. So you should extract the column into your array with:
$ids[] = $row['usersID'];
Then you should use a prepared statement with parameters rather than substituting the variable directly into the SQL. It's also easier to use foreach rather than for.
$stmt = $conn->prepare("
SELECT *
FROM messages
WHERE (messagesFrom LIKE CONCAT('%', ?, '%') AND messagesTo = ?)
OR(messagesFrom = ? AND messagesTo LIKE CONCAT('%', ?, '%'))")
$stmt->bind_param("ssss", $id, $messagesFrom, $id, $messagesFrom);
foreach ($ids as $id) {
$stmt->execute();
$result = $stmt->get_result();
$row2 = $mysqli_fetch_assoc($result);
var_dump($row2);
}
You can't print an array, use var_dump() to print $row2.
I'm trying my best here to find a solution for my issue, but with no luck.
I have a SELECT in my PHP to retrieve some products information like their IDs.
mysql_query("SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
Every time I run this SELECT, I get 5 rows as result. After that I need to run a DELETE to kill those 5 rows using their id_item in my WHERE condition. When I run, manually, something like:
DELETE FROM mytable WHERE id_item IN (1,2,3,4,5);
It works! But my issue is that I don't know how to make an array in PHP to return (1,2,3,4,5) as this kind of array from my SELECT up there, because those 2 other conditions may vary and I have more "status = 0" in my db that can't be killed together. How am I suppose to do so? Please, I appreciate any help.
Unless there is more going on than what is shown, you should never have to select just to determine what to delete. Just form the DELETE query WHERE condition as you would in the SELECT:
DELETE FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'
But to answer how to get the IDs:
$result = mysqli_query($link, "SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
while($row = mysqli_fetch_assoc($result)) {
$ids[] = $row['id_item'];
}
$ids = implode(',', $ids);
Move to PDO or MySQLi now.
First of all you shouldn't be using mysql_query anymore as the function is deprecated - see php.net
If this is a legacy application and you MUST use mysql_query you'll need to loop through the resource that's returned by mysql_query, which should look something like this
$result = mysql_query("SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
$idArray = array();
while ($row = mysql_fetch_assoc($result)) {
$idArray[] = $row['id_item'];
}
if(count($idArray) > 0) {
mysql_query("DELETE FROM mytable WHERE id_item IN (" . implode(',' $idArray) . ")");
}
As said before, probably you don't even need a select. But you can do a select, grouping all ids together, and then put it in the delete IN.
$result = mysql_query("SELECT GROUP_CONCAT(DISTINCT id_item) AS ids FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
$ids = mysql_result( $result , 0, 'ids') ; // 1,2,3,4,5
if ($ids != ""){
mysql_query("DELETE FROM mytable WHERE id_item IN (" . $ids . ")");
}
GROUP_CONCAT
i have this table
Column_1 Column_2
1 value1
2 value1
3 value2
My php query is
$query = "SELECT * FROM `table` WHERE `Column_1` = 'value1' ";
print_r($query);
This returns only the 1st row. I am looking to display row 1 and 2. When I run the SQL in phpmyadmin it returns row 1 and 2. However, the php script only returns row 1... I also did an
echo count($query);
But it returns only 1. What am i doing wrong?
$query = "SELECT * FROM `table` WHERE `Column_2` = 'value1' ";
$res = mysql_query($query);
if(mysql_num_rows($res)!=0) {
while($rowData = mysql_fetch_array($res)) {
var_dump($rowData);
}
}
Use mysql_num_rows to count number of results.
Use mysql_fetch_array or mysql_fetch_assoc to fetch data.
$query = "SELECT * FROM `table` WHERE `Column_1` = 'value1' ";
$res = mysql_query($query);
while($row = mysql_fetch_assoc())
print_r($row);
You need add fetch in cycle.
Use mysql_fetch_array() function
$query = "SELECT * FROM `table` WHERE `Column_1` = 'value1' ";
$res = mysql_query($query);
while($row = mysql_fetch_array($res))
{
echo $row['Column_1'];
echo $row['value_1'];
}
Hi guys.
I'm currently try to make an mysql query than take the results and use them in an another query. So I thought I'm calling my database and use mysql_fetch_array and than implode it do insert , so I can use it in an another query. I read here many questions about this and based on the questions i wrote my own piece of code but I'm getting this error:
Warning: array_values() expects parameter 1 to be array, string given in /var/www/html/lager_management/warenkorb.php on line 107
Warning: implode(): Invalid arguments passed in /var/www/html/lager_management/warenkorb.php on line 108
Here is the piece of code what is going wrong I can't explain myself and I know mysql is old and I should use myqli
$sql3 = "SELECT `Index` FROM lm_Warenkorb;";
$result3 = mysql_query($sql3);
while($resultarray3 = mysql_fetch_array($result3))
{
$anfrage = array();
$anfrage = $resultarray3['Index'];
$anfrage = implode(", ", $anfrage);
$sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".$anfrage.");";
}
The table lm_Warenkorb looks like this:
Index:
10
2
6
I think you could do it using one query with nested SELECT:
$sql3 = "
SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort`
FROM `lm_Artikel`
WHERE `Index` IN (
SELECT `Index` FROM lm_Warenkorb
)";
$result3 = mysql_query($sql3);
while($resultarray3 = mysql_fetch_array($result3)) {
// handle the results
}
you use mysql_fetch_array($result) in a while loop, which is perfectly right.
But this obviously will only return one row of your table from database and not the whole column.
therefore $resultarray3['Index']; returns the value of Index column of your first table row, which is not an array.
Try this
$anfrage = array();
while($resultarray3 = mysql_fetch_array($result3))
{
$anfrage[] = $resultarray3['Index'];
}
if(count($anfrage) > 0) {
$anfrage = implode(",", $anfrage);
$sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".$anfrage.");";
}
$sql3 = "SELECT `Index` FROM lm_Warenkorb;";
$result3 = mysql_query($sql3);
$data = array(0);
while($resultarray3 = mysql_fetch_assoc($result3))
{
$data[] = $resultarray3['Index'];
}
$sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".implode(',', $data).");";
echo $sql2;
I have database such as
I want to create an associative array such that each att_name value is associated with its possible values from att_value:
array('att_name' => array('att_value_1', 'att_value_2', 'att_value_3'))
What is the best way to achieve this?
While it is easily possible to do this simply by selecting the results you want and iterating them in PHP to create the data structure you want, you could sub some of the work out to MySQL with GROUP_CONCAT():
$query = "
SELECT att_name, GROUP_CONCAT(att_value SEPARATOR ',') AS values
FROM table_name
GROUP BY att_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']] = explode(',', $values);
}
print_r($array);
Of course, this only works if your values will never contain the character (or sequence of characters) you use for the SEPARATOR in the MySQL query, so the safer pure-PHP way would be:
$query = "
SELECT att_name, att_value
FROM table_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']][] = $row['att_value'];
}
print_r($array);
Try below:
$sql = "SELECT * from tablename";
$result = mysql_query($sql,$con);
$final_array=array();
while ($row = mysql_fetch_object($result))
{
$final_array[$row->att_name][0]=$row->att_value_1;
$final_array[$row->att_name][1]=$row->att_value_2;
....
....
}
This way :
SELECT
item,
att_name,
GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value
FROM
table
GROUP BY
att_name
Will give you something like that :
item att_name att_value
-----------------------------
books height 150 mm<!>250 mm
books price rs:20<!>Rs:20
books size 15 pg<!>30 pg<!>60 pg
books width 300 mm<!>400 mm
You have to explode the result from att_value by a <!>. I use this <!> so it highly impossible to have a value inside att_value with this. If you think you would someday use this, take another separator. Example : [{--}], _SEPARATOR_, [_-CUT-_], etc. Something you are sure at 100% you won't use a choice but always as a separator to split the text.
So example :
$SQL = 'SELECT item, att_name, GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value FROM table GROUP BY att_name';
$Query = mysql_query($SQL) or die('MySQL Error : '.mysql_error());
while($Assoc = mysql_fetch_assoc($Query)){
$Assoc['att_value'] = ($Assoc['att_value'] != '' ? explode('<!>', $Assoc['att_value']) : NULL);
print_r($Assoc);
}