I have created a series of web pages one creates users into a sql database another page looks up all of these users then needs to show them in a drop down list for another database input.
On calling the php file and using echo to print out the array it works fine however when i put it within my html file the drop down menu simply displays "$username_array[] = "\"".$row['Username'].""\" once I believe its something to do with escaping quotes however cant figure it out any help would be greatly appreciated!!
This is the code held within the html file
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'fid';
echo "<label class=\"input\" for=\"investigator\" type=\"input\">Investigator:<select id=\"investigator\" name=\"investigator\">";
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
mysql_select_db($db);
$username_array = array();
$sql = mysql_query("SELECT `Username` FROM `user`");
while ($row = mysql_fetch_array($sql)){
//echo $username_array[] = "\"".$row['Username']."\"";
echo "<option value='null'>"$username_array[] = "\"".$row['Username'].""\"</option>";
}
echo "</label>";
mysql_close($conn)
?>
I want the username array to display one user after the other within a drop down list however currently just echos out the option value line without any interpretation
UPDATE
I've now changed the code to this
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'fid';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
mysql_select_db($db);
echo '<select id="investigator" name="investigator">';
$resource = mysql_query("SELECT `Username` FROM `user`");
if($resource && mysql_num_rows($resource)) {
while ($row = mysql_fetch_assoc($resource)){
echo '<option value="'.$row['Username'].'">'.$row['Username'].'</option>';
}
}
echo '</select>';
mysql_close($conn)
?>
however the html outputs the script rather than a drop down list and the usernames
html output
'; $resource = mysql_query("SELECT Username FROM user"); if($resource && mysql_num_rows($resource)) { while ($row = mysql_fetch_assoc($resource)){ echo ''; } } echo ''; mysql_close($conn) ?>
any help would be appeciated I just really need to get this working as its been bugging me for days!
This will do what you need
echo '<select id="investigator" name="investigator">';
$resource = mysql_query("SELECT `Username` FROM `user`");
if($resource && mysql_num_rows($resource)) {
while ($row = mysql_fetch_assoc($resource)){
echo '<option value="'.$row['Username'].'">'.$row['Username'].'</option>';
}
}
echo '</select>';
BUT you should also move to mysqli or PDO as mysql_* is depreciated
I have changed $sql to $resource as it is not an SQL statement but a resource.
I'd change your code to something similar to this:
echo "<select>";
while ($row = mysql_fetch_array($sql)) {
echo "<option value=\"VALUE\">".$row['Username']."</option>";
}
echo "</select>";
Related
I figured out the way to link to the page and set what ID i would like to call:
CLICK TEST **(IS THIS RIGHT?)**
But then I need page.php to pull the id, this is what I am using at the moment to pull the id manually. How would I make the following code pull it form the link?
<?php
$query = "select * from Drinklist where id = 10";
$result = mysqli_query($conn,$query);
while($Drinklist = mysqli_fetch_array($result)){
echo "<head>";
echo "<title>".$List['name']." - Site Name</title>";
}
?>
I tried the following (didn't work):
$query = "select * from List where id = . $id";
Seems like I can only find the way to do it with MYSQL and not MYSQLI... Any help would be appreciated.
UPDATED CODE:
<?php
$query = "select * from Drinklist where id = ?";
$result = mysqli_prepare($conn,$query);
mysqli_stmt_bind_param($result, 'i', $_GET['id']);
mysqli_stmt_execute($result);
while($Drinklist = mysqli_fetch_array($result)){
echo "<head>";
echo "<title>".$Drinklist['name']." - Mixed Drinks Station</title>";
}
?>
Getting error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
object given in public_html/page.com/test/inc/drink-page.php on line 6
Ok so I ended up figuring this one out with a ton of trial and error...
Thank you chris85 for the early support and hopefully this can help you out a little. This is fun ;)
<?php
$server = "localhost";
$user = "user";
$pass = "password";
$dbname = "database";
//Creating connection for mysqli
$conn = new mysqli($server, $user, $pass, $dbname);
//Checking connection
if($conn->connect_error){
die("Connection failed:" . $conn->connect_error);
}
$article_id = $_GET['id'];
if( ! is_numeric($article_id) )
die("Looks like you are lost! <a href='#'>Back to Home</a> ");
$query = "SELECT * FROM `Whatever` WHERE `ID` =$article_id LIMIT 0 , 30";
$info = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($info, MYSQL_ASSOC))
{
$name = $Whatever['name'];
$description = $Whatever['description'];
$keywords = $Whatever['keywords'];
$lrgpic = $Whatever['lrgpic'];
$vid = $Whatever['vid'];
$name = htmlspecialchars($row['name'],ENT_QUOTES);
$description = htmlspecialchars($row['description'],ENT_QUOTES);
$keywords = htmlspecialchars($row['keywords'],ENT_QUOTES);
$lrgpic = htmlspecialchars($row['lrgpic'],ENT_QUOTES);
$vid = $row['vid']; //Use <-- to be able to have HTML in your database otherwise the above would remove <, >, /, ', ", ect.
echo "<head>";
echo "<title>$name - Site title</title>";
echo "<meta name='description' content='$description'>";
echo "<meta name='keywords' content='$keywords'>";
include 'inc/head.php'; //includes already are in a php file ;)
echo "</head>";
echo "<body>";
include 'inc/header.php';
include 'inc/nav.php';
echo "<div class='wrapper'>";
echo "<div id='drink-name'>";
echo "<h2>$name</h2>";
echo "</div>";
// AND SO ON
}
?>
I'm trying to put the tables from MySQL database in a HTML page using PHP.
I'm beginner in PHP and I face a problem to the mysqli_query function.
This is my PHP code:
// connect to the db
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'testdb';
$connection = mysqli_connect($host, $user, $pass, $db) or die("cannot connect to db");
// show the tables
$result = mysqli_query($connection, 'SHOW TABLES') or die ('cannot show tables');
while($tableName = mysqli_fetch_row($result)) {
$table = $tableName[0];
echo '<h3>', $table, '</h3>';
$result2 = mysqli_query($table, 'SHOW COLUMNS FROM') or die("cannot show columns");
if(mysqli_num_rows($result2)) {
echo '<table cellpadding = "0" cellspacing = "0" class "db-table">';
echo '<tr><th>Field</th><th>Type</th><th>Null</th><th>Key</th><th>Default</th><th>Extra</th></tr>';
while($row2 = mysqli_fetch_row($result2)) {
echo '<tr>';
foreach ($row2 as $key=>$value) {
echo '<td>',$value, '</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
}
Unfortunately I get this error:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in
C:\xampp\htdocs\test\showtables.php on line 26, cannot show columns.
I've also tried with the mysql_query function, but I faced another error, I then I changed it back to the mysqli_query function.
This code show you all of the tables and tables rows. I try it works
<?PHP
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'testdb';
$mysqli = new mysqli($host, $user, $pass, $db);
//show tables
$result = $mysqli->query("SHOW TABLES from testdb");
//print_r($result);
while($tableName = mysqli_fetch_row($result))
{
$table = $tableName[0];
echo '<h3>' ,$table, '</h3>';
$result2 = $mysqli->query("SHOW COLUMNS from ".$table.""); //$result2 = mysqli_query($table, 'SHOW COLUMNS FROM') or die("cannot show columns");
if(mysqli_num_rows($result2))
{
echo '<table cellpadding = "0" cellspacing = "0" class "db-table">';
echo '<tr><th>Field</th><th>Type</th><th>Null</th><th>Key</th><th>Default</th><th>Extra</th></tr>';
while($row2 = mysqli_fetch_row($result2))
{
echo '<tr>';
foreach ($row2 as $key=>$value)
{
echo '<td>',$value, '</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
}
?>
Sample Output :
In the second call to the mysqli_query function, you're passing in the table name instead of the connection. Try something like this:
$result2 = mysqli_query($connection, "SHOW COLUMNS FROM $table") or die("cannot show columns");
http://php.net/manual/en/mysqli.query.php
I've tried for a couple of days to get all of the data from a MySQL column and put it inside an array, formatted in the following way:
$aSpam= array
( '.info'=> 'i'
, 'anal'=> 'i'
, 'anus'=> 'i'
, 'arse'=> 'i'
)
I've managed to echo it out formatted properly as you can see here: http://www.yourgrumble.com/phpbbforum/getSpam.php
with the following PHP code:
<?php
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT `SpamWord` FROM spamWords";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$counter = 0;
while($row = $result->fetch_assoc()) {
if($counter){
echo ", '" . $row["SpamWord"]. "'=> 'i'";
$counter++;
} else {
echo "'" . $row["SpamWord"]. "'=> 'i'";
$counter++;
}
}
} else {
echo "Error!";
}
$conn->close();
?>
I've read and tried more than 10 solutions found in the web and here at stackoverflow, however none of them worked. I've really got desperate and I cannot get through this without your help guys.
Edit
For example I tried with this solution, but it didn't work:
while ($row = mysql_fetch_array($result))
{
$new_array[$row['id']]['SpamWord'] = $row['SpamWord'];
}
foreach($new_array as $array)
{
echo $array['SpamWord'].'<br />';
}
Thank you all in advance,
Denis Saidov
Try like below:-
$sql = "SELECT `SpamWord` FROM spamWords";
$result = mysqli_query($conn ,$sql) or die(mysqli_error($conn));
$resultArray = array(); // create an array
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$resultArray[$row["SpamWord"]] = 'i'; // assing value
}
} else {
echo "Error!";
}
echo "<pre/>";print_r($resultArray); // print array
$conn->close();
Note: Here you will get your original array containing all SpamWord values comes from database.thanks
PHP array's are like dictionnaries (a list of key/value pairs)
First, before your loop, create your array empty:
$new_array = Array();
while...
Then for each column, you append the column value as a new key for the array
$new_array[$row['SpamWord']] = "i";
As in your example, I put "i" as the value for each array's row.
i'm a newbie to php still.
I'm using phpmyadmin as my database. I have a table called 'lessonno' and a column named 'lesson' in it. I tried using this code to retrieve out the number inside 'lesson'. But it's not printing out anything. Can someone help?
<?php
$server = 'localhost';
$username = '';
$password = '';
$database = 'project';
mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
$sql = "SELECT 'lesson' FROM 'lessonno'";
$lesson = $_POST['lesson'];
$result = mysql_query($sql);
?>
<?php
for($i = 1; $i <= $lesson; $i++) {
echo "<div>
<span>Lesson ".$i."</span>
</div>
<br>";
}
?>
You can use something like this:
$sql = "SELECT lesson FROM lessonno";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['lesson'];
}
If you would like to only print out a specific lesson with an certan ID, you can use something along the lines:
$id = $_GET['lessonid']; // If you would have something like index.php?lessonid=36 and you'd like it to only fetch the data for the lesson with the id of 36.
$sql = "SELECT lesson FROM lessonno WHERE id='$id'";
(by looking at the $_POST['lesson'] part, I suppose that's something you might be trying to do as it's in the for loop as well)
Also, I suggest you use mysqli.
And, this:
echo "<div>
<span>Lesson ".$i."</span>
</div>
<br>";
Will just echo the $i as both lesson= and the span with Lesson, which won't grab any information from the actual database but just go with the current number it's at, from the for loop you have.
i have made some changes in your code try this
<?php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'project';
$conn = mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database, $conn) or die(mysql_error());
$sql = "SELECT `lesson` FROM `lessonno`";
$lesson = $_POST['lesson'];
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$lesson_no = $row['lesson'];
echo "<div>
<span>Lesson ".$lesson_no."</span>
</div>
<br>";
}
?>
Note : mysql_* is deprecated. use mysqli_* OR PDO
For getting Values from DB you need to use something like this
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
For further reference please visit http://in2.php.net/manual/en/function.mysql-fetch-assoc.php
For counting the number of data in your database, just insert this code
$sql = "SELECT 'lesson' FROM 'lessonno'";
$lesson = $_POST['lesson'];
$result = mysql_query($sql);
$count=mysql_num_rows($result);//this will count the number of rows in your table.
echo "<div>
<span>Lesson ".$count."</span>
</div>
<br>";
Why does this only print the sites specific content under the first site, and doesn't do it for the other 2?
<?php
echo 'NPSIN Data will be here soon!';
// connect to DB
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to DB');
$dbname = 'npsin';
mysql_select_db($dbname);
// get number of sites
$query = 'select count(*) from sites';
$result = mysql_query($query) or die ('Query failed: ' . mysql_error());
$resultArray = mysql_fetch_array($result);
$numSites = $resultArray[0];
echo "<br><br>";
// get all sites
$query = 'select site_name from sites';
$result = mysql_query($query);
// get site content
$query2 = 'select content_name, site_id from content';
$result2 = mysql_query($query2);
// get site files
// print info
$count = 1;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "Site $count: ";
echo "$row[0]";
echo "<br>";
$contentCount = 1;
while ($row2 = mysql_fetch_array($result2, MYSQL_NUM)) {
$id = $row2[1];
if ($id == ($count - 1)) {
echo "Content $contentCount: ";
echo "$row2[0]";
echo "<br>";
}
$contentCount++;
}
$count++;
}
?>
The problem is that you assume that once your finished looking for the row with the same id as the site row, that it'll reset the $result2 query to the beginning. This means that after you find your first row (unless you were to sort the two queries), that the second pass of the while loop wouldn't have any results left. You should consider caching the inner while loop first and then using an array lookup to get the value.
An even better solution would involve a join from sites to content which wouldn't require this complex matching process. Joins are a VERY important part of SQL, I highly suggest learning how to use them. http://dev.mysql.com/doc/refman/5.0/en/join.html