Im using a PHP search function on my website and it is currently only displaying one result from my SQL database - i would like it to display all results included in the site_keywords!
Here is the PHP code i'm currently using on my page
<?php
mysql_connect("danieljosephdesignsc.ipagemysql.com", "searchdata", "danieljoseph");
mysql_select_db("my_db");
if(isset($_GET['search'])) {
$search_value = $_GET['value'];
$query = "select * from sites where site_keywords like '%$search_value%'";
$run = mysql_query($query);
while($row=mysql_fetch_array($run)){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
}
}
?>
Here is what is included in my body:
<?php echo "<div><a href='$link'><h2>$title</h2></a><p>$desc</p><a href='$link'>$link</a></div>";?>
Please let me know if you require further info. Any assistance on this would be greatly appreciated.
Thanks
You problem is that you aren't echoing the results within your loop.
you need something like this:
while($row=mysql_fetch_assoc($run)){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
echo "<div><a href='$link'><h2>$title</h2></a><p>$desc</p><a href='$link'>$link</a></div>";
}
Important Note:
You are using deprecated code. This is true of any function that begins with mysql_. This means that your code will no longer work in newer versions of php, and is likely to be not secure if you call any of your variables in your queries. You really need to look up using prepared statements using either mysqli or PDO.
From the official site
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
Here's how to use mysqli prepared statements
or PDO prepared statements
The problem is in this block of code:
while($row=mysql_fetch_array($run)){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
}
Even though you're getting multiple results, each result overwrites the values of the previous one. So in the end you only have a single row. Try saving the results to an array instead and iterating over it in the body.
$rows =array();
while($row=mysql_fetch_array($run)){
$rows[] =$row;
}
foreach($rows as $row){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
echo "<div><a href='$link'><h2>$title</h2></a><p>$desc</p><a href='$link'>$link</a></div>";
}
Related
here is my code
$query = mysql_query("SELECT * FROM accommodation_vacancies WHERE accommodation_id = '$accom'");
$results = mysql_fetch_array($query);
if($query === FALSE) {
die(mysql_error());
} else {
print_r($results);
foreach ($results as $result) {
echo $result['start_date']; echo "<br/>";
}
}
And here is my output
By using the print_r commant i can see that The variable $results works properly,the query works properly also, i guess that i have mistakes on the foreach loop.
Thank you.
You are only fetching a single result. Use a while loop instead.
while ($result = mysql_fetch_array($query)) {
Side note: As stated in the comments, the mysql_* functions are deprecated. You should NOT learn how to use mysql using these deprecated methods. They will be removed from PHP in some future version and your code will stop working then. If you learn it, use mysqli_* or PDO.
I have following code:
<?php
include_once 'init/init.funcs.php';
$pollid=$_GET['pollid'];
$result = mysql_query('SELECT question FROM questions where survey_id="' . $pollid . '"');
$question = mysql_result($result, 0);
echo $pollid;
echo $question;
?>
And it will echo first question which has survey_id=$pollid. But I want to make an array of all the questions, which have survey_id=$pollid.How I can do that?
Just loop through the results and add them to an array:
$pollid = (int) $_GET['pollid'];
$questions = array();
$result = mysql_query('SELECT question FROM questions where survey_id="' . $pollid . '"');
while($row = mysql_fetch_assoc($result)) {
$questions[$pollid] = $row['question '];
}
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You are also wide open to SQL injections. In my example I casted $_GET['pollid'] to an integer to help protect against them. A better approach would be to use prepared statements as mentioned above.
Try to use mysqli_ instead of mysql_,
// MYSQLI
$mysqli = new mysqli('localhost', 'example', 'example', 'test');
print '<h3>MYSQLI: simple select</h3>';
$rs = $mysqli->query( YOUR SELECT QUERY);
while($row = $rs->fetch_object())
{
//DATA
}
I am currently working on an AJAX testing platform. I am experiencing stupid errors in PHP programming. Here is my code. I get the error: Maximum execution time of 30 seconds exceeded.
<?php
$resultFromJson;
$databaseConnection = mysql_connect("localhost", "root", "password");
if($databaseConnection)mysql_select_db("fastdata", $databaseConnection);
else echo mysql_error($databaseConnection);
if(isset($_GET['command'])){
switch($_GET['command']){
case "loadPeople":
{
$sqlCommandString = "SELECT * FROM `people` LIMIT 0 , 30";
$people = array();
$index = 0;
while($row = mysql_fetch_assoc(mysql_query($sqlCommandString))){
$people[$index] = $row;
$index++;
}
echo json_encode( $people );
}
break;
}
}
if(!isset($_GET['command']))echo json_encode( "Error#001" );
?>
What can I do to solve this error? What actually causes the error?
P.S. I am currently testing my PHP script directly in the browser with main.php?command=loadPeople as URL.
Execute the query, then loop through the results; don't try to re-execute the query in every iteration of the while
$resultset = mysql_query($sqlCommandString);
while ($row = mysql_fetch_assoc($resultset)) {
As you're clearly just learning the basics, I'd suggest that you learn to use MySQLi or PDO rather than the deprecated MySQL library... being able to use prepared statements and bind variables doesn't affect this query, but knowing how to use them will become more important later
i haven't written any PHP code in a while so this is a wild guess but in this piece of code:
while($row = mysql_fetch_assoc(mysql_query($sqlCommandString)))
you essentially have a neverending loop because $row will be assigned every time mysql_fetch_assoc(mysql_query($sqlCommandString)) returns a result
you need to save mysql_query($sqlCommandString) into a variable and then mysql_fetch_assoc from that variable in a loop
I know I need to use the MySQL fetch to prevent getting a resource ID in my variable but I wondered if you could help me out how to do that. I see from several tutorials they use a loop but I just want to select the one string into a variable. Here is the code I have:
$img = mysql_query('SELECT pname FROM photos WHERE pphotoid=21');
echo $img;
I basically want $img to contain the string in the database not Resource id #3 it is currently showing. Also is what I wrote prone to an SQL injection?
Learning MySQL so any help would be great!
$img=mysql_fetch_assoc(mysql_query('SELECT pname FROM photos WHERE pphotoid=21'));
echo $img["pname"];
Better would be
$img=mysqli_fetch_assoc(mysqli_query($link,'SELECT pname FROM photos WHERE pphotoid=21'));
echo $img["pname"];
$handle = mysql_query('SELECT pname FROM photos WHERE pphotoid=21');
$row = mysql_fetch_row($handle);
echo $img[0];
http://pl1.php.net/mysql_fetch_row
this code will work for you.
To prevent SQL injection you should use escape functions like mysql_escape_string()
you should also check what is your input and valid it
here you will learn more
How can I prevent SQL injection in PHP?
also it's better to use PDO because mysql_* are deprecated as of PHP 5.5.0, and will be removed in the future.
here is tutorial to learn connecting to db with PDO
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
your code in PDO(assuming you are connected to db) will look like:
$id = intval(21); //this code here is senseless however if you get 21 for example via $_GET it will cast it to integer and prevent injection
$stmt = $db->prepare("SELECT pname FROM photos WHERE pphotoid=?");
$stmt->execute(array($id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['pname'];
I like the following:
connection.php:
//All the $*_db variables are pulled from a file kept outside of the document root directory but referenced here to connect to the database
include('/path/to/file/not/in/docroot/connection_info.php');
$DBi = mysqli_connect($hostname_db, $username_db, $password_db, $database_db);
if($mysqli->connect_error) {
//Do something for errors here...
};
file.php
include('connection.php');
$q_myQuery = "SELECT `pname` FROM `photos` WHERE `pphotoid` = 21";
$rsmyQuery = mysqli_query($DBi, $q_myQuery) or die(mysqli_error($DBi));
$row_rsmyQuery = mysqli_fetch_assoc($rsmyQuery);
$img = $row_rsmyQuery['pname'];
That's using mysqli* functions, not mysql* which have been deprecated. More on that here: http://us3.php.net/manual/en/mysqlinfo.api.choosing.php
In asp.net, you can retrieve MULTIPLE datatables from a single call to the database. Can you do the same thing in php?
Example:
$sql ="select * from t1; select * from t2;";
$result = SomeQueryFunc($sql);
print_r($result[0]); // dump results for t1
print_r($result[1]); // dump results for t2
Can you do something like this?
This is called "multi-query." The mysql extension in PHP does not have any means to enable multi-query. The mysqli extension does allow you to use multi-query, but only through the multi_query() method. See http://php.net/manual/en/mysqli.multi-query.php
Using multi-query is not recommended, because it can increase the potential damage caused by SQL injection attacks. If you use multi-query, you should use rigorous code inspection habits to avoid SQL injection vulnerability.
This should be possible with newer MySQL and the mysqli (improved) php extension.
I'm not sure if any DB abstraction layers support this.
See relevant MySQL docs and
PHP docs.
PDOStatement::nextRowset() seems to be what you're after.
If you're using classic MySQL, you can't. You can create a function which will look like
function SomeQueryFunc($queries) {
$queries = explode(';', $queries);
$return = array();
foreach($queries as $index => $query) {
$result = mysql_query($query);
$return[$index] = array();
while($row = mysql_fetch_assoc($result)) {
foreach($row as $column => $value) {
$return[$index][$column] = $value;
}
}
}
return $return;
}
which will work as expected