I build my query like this:
foreach($ids as $key => $idi) {
$ids[$key] = "'" . $idi . "'";
};
$ids_imploded = implode(", ", $ids);
$sql = "SELECT record_id, email FROM `actions_attendees` WHERE `action_id` IN (" . $ids_imploded . ") AND `backup` = 1 ORDER BY `timestamp` ASC LIMIT " . count($ids) . ";";
$result = mysqli_query($con, $sql);
Where $ids is just array of few numbers (so the $ids_imploded = "'132', '165'").
When I run the generated query in phpMyAdmin, I get what I want. When I run it from PHP, it returns just object with nulls. Why?
I doesn't work neither if I remove the escaping loop.
EDIT: generated query is echoed like
SELECT record_id, email FROM `actions_attendees` WHERE `action_id` IN ('1614', '1615') AND `backup` = 1 ORDER BY `timestamp` ASC LIMIT 2;
The problem could be that you are querying the wrong database, try select a db first, try executing this before the query :
mysql_select_db('yourdb');
Is the result of your query true ? Check your connection object, it seems like you are not on the right database.
It appears that the query was indeed working even in PHP, but later when I was processing the results, intellisense tricked me and I was using mysql_fetch_assoc instead of mysqli_fetch_assoc...
Related
I am making a page that queries a table for all columns of all results ordered by entry time in descending order with a limit. When I query for a count of the rows, the query works just fine, but when I try to query the table again for data, I don't get anything. I decided to try cutting the query down to "SELECT * FROM comments" but I still got no results when "SELECT COUNT(*) AS count FROM comments" just beforehand worked. I've tried using mysqli_error(), but that didn't give me any information.
The query doesn't seem to be failing as the result from mysqli_query() isn't false and when I query in phpMyAdmin, the queries work. A little piece of my code below
//open databases
require_once($root . "databases/data.php");
//get number of suggestions in comments table
$cquery = mysqli_query($cbase, "SELECT COUNT(*) AS count FROM comments"); //this works
$c = mysqli_fetch_array($cquery);
$count = $c["count"];
//get all suggestions
//this query fails
$queryText = "SELECT * FROM comments ORDER BY time DESC LIMIT " . (($page - 1) * $pageLimit) . ", " . $pageLimit;
$query = mysqli_query($cbase, $queryText);
//validate query
if($query === false)
{
$failed = true;
}
//get all comments from query
while(!$failed && $array = mysqli_fetch_array($result))
Please try this on line 3
$c = mysqli_fetch_assoc($cquery);
You can also try like this also,
$c = mysqli_fetch_array($cquery, MYSQLI_ASSOC);
You are just using the wrong variable when reading out your query results in your while-loop. mysqli_fetch_array($result) while you saved the query-result in $query so it should be mysqli_fetch_array($query)
I want to update my mysql database, using php using variable method but it is not updating. I don't know what the problem is. This is my code:
$result = mysql_query("SELECT * FROM total") or die(mysql_error());
$i=$row['number'];
$n=$i+1;
$result = mysql_query("UPDATE total SET number = " . $n . " WHERE number = " . $i . "") or die(mysql_error());
How can I update my mysql database using php?
You can increment the column_value like this column_name = column_name + 1 without using SELECT.
UPDATE total SET number = number + 1
It can be just with SQL without need of select. When it is not required don't use php. What can be done in mysql should be done in mysql. It's faster.
UPDATE `total` SET number = number + 1;
Moreover, you should read the red box on mysql_* documentation. These functions are depracated and will be removed in future. Consider using MYSQLI or PDO
your query syntax is wrong, try this,
$result = mysql_query("UPDATE total SET number = '" . $n . "' WHERE number = '" . $i . "'");
The syntax fo your query is wrong it should be
UPDATE `total` SET number = number + 1;
you have done
UPDATE `total` S number = number + 1;
refer this mysql doc
I have a MySQL database with 6 columns in a table. There will eventually be about 100 rows, for now I have 3.
Column titles: FirstName, SecondName, Sentence1, Sentence2, Sentence3, Sentence4
All tables are set to VARCHAR
I want to use php on a web page to call random data from each row, eg mix and match row1 FirstName with row3 SecondName and row2 Sentence1 etc.
I read it is quicker to randomise using php but I really can't grasp how to do this despite searching.
I can connect to my MySQL database and get results returned using this code:
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error ());
// Select database
mysql_select_db("zzz") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['FirstName'] . "<br />";
}
// Close the database connection
mysql_close();
?>
but this just returns one column of data. I need the random code to be returned in the webpage using something like:
echo $firstname . $lastname . $sentence1 . $sentence2 . $sentence3 . $sentence4;
Note, this will be repeated for another 3 or 4 rows afterwards too
echo $firstname_2 . $lastname_2 . $sentence1_2 . $sentence2_2 . $sentence3_2 . $sentence4_2;
I'm not too hot on arrays but if someone can get me started it would be great, thanks.
All those telling you to use rand in the SQL query have not read the question. To those people: the asker wants a random combination of data from the rows, not a random row.
Something like this. It will take all the results from the database and echo a totally random combination. I couldn't avoid using arrays as they are super useful.
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error ());
// Select database
mysql_select_db("zzz") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Array to hold all data
$rows = array();
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// add row to array.
$rows[] = $row;
}
// Close the database connection
mysql_close();
// Max rand number
$max = count($rows) - 1;
// print out random combination of data.
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4] . " " . $rows[rand(0, $max)][5];
?>
Store all the values which you want to show in random in a variable, use rand() http://php.net/manual/en/function.rand.php and shuffle() http://php.net/manual/en/function.shuffle.php to make the random data and display them
there are several methods to get random data from db in php
SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;
another method: -
$range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM `table` ");
$range_row = mysql_fetch_object( $range_result );
$random = mt_rand( $range_row->min_id , $range_row->max_id );
$result = mysql_query( " SELECT * FROM `table` WHERE `id` >= $random LIMIT 0,1 ");
one more method:-
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `table` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `table` LIMIT $offset, 1 " );
SELECT * FROM `Users` ORDER BY RAND() LIMIT 0,1;
Use ORDER BY RAND() for random records selection.
Split it into two tables,
one for the user
Users:
id | firstname | lastname
Sentences:
id | userId | sentence
Join both at the "id / userId" and do a ORDER BY RAND() probably followed by a LIMIT 20
Trying to implement this but taking an entry from every column (14 at present) instead of a small random number. Would love to have Matthew McGovern's opinion since his code suited me except that it only called a few entries...
Here: Random Sentence Using PHP & MySQL
I'm running a very simple query that I think should work. The only thing that I haven't done before is put a php variable in the WHERE clause of the query. The variable $X is a numerical value, say 100. When I run this query, I just get a value of 0 returned. Am I doing something obviously stupid?
SELECT generator_64k.n
FROM generator_64k
WHERE generator_64k.n<= '$X'
I've looked around the web and also tried this:
SELECT generator_64k.n
FROM generator_64k
WHERE generator_64k.n<= '" . $X . "'
But this also just returns 0.
Any ideas? Thanks in advance.
$query = "SELECT generator_64k.n FROM generator_64k WHERE generator_64k.n<= {$X};";
Try this one, or post your PHP code.
<?php
$X = 100;
$query = "SELECT n FROM generator_64k WHERE n <= $X";
$result = mysql_query($query);
if (!$result) {
echo ('Query error: ' . mysql_error());
}
E.g of php and using variables
$query = "select * from table1 where col1 <=" .$myVariable;
$result= mysql_query($query);
The mysql_query() function returns false on error (false == 0), otherwise, it returns a resource. mysql_query does not return the value from the result set. You must use mysql_fetch_assoc or something similar to fetch the rows from the result set.
Also, ensure that you wrap the query in double quotes so PHP can expand the variable $X.
Use mysql_error to fetch the error from the last call to mysql_query.
make it like this
$sql="select `username` from `users` where id='$newid';";
mysql_query($sql);
here $newid is the int value.
The symbol used before and after username, to get this you have to press the key just below esc .
You can't have ' around your numeric value. MySQL will treat it as string.
You should do this instead
" WHERE number <= " . (int)$val . " .. "
// or (but not recommended due to security problem)
" WHERE number <= $val "
I am connecting to an SQL database in my PHP script and am having trouble with the LIMIT command:
$result = mysql_query("
SELECT *
FROM product
WHERE `category` like \"" . $_GET['category'] . "\"
LIMIT 0, 16
");
This all works, except that if I only have 10 rows then $result contains rows 0~10 and then 0~6 as well.
I am using a a while loop while($row = mysql_fetch_assoc($result)) to check if there is a result and then run an action. Is there any way of having it limit the select statement to only show rows 0~10?
$result = mysql_query("SELECT * FROM product
WHERE `category` like '" . mysql_real_escape_string($_GET['category']) . "' LIMIT 0, 10");
is it what are you looking for? It will give you ten rows maximally..
Additionally, please read this article about SQLi