PHP / MySQLi drop-down empty - php

Im just starting out with MySQL and PHP. Im trying to create a drop-down menu, to pick a certain competence within a company.
Later on, i want a total of 3 dropdowns, so that i can combine user/competence/avaliable date, to display sort of a calendar to show which users are avaliable a certain date, with information about their competence.
However, the code below just returns this:
Result
The same query to the database returns 12 values.
What am i doing wrong? I get no errors, just a blank drop-down.
<!DOCTYPE html>
<html>
<head>
<title> Greetings. </title>
<meta charset="UTF-8"/>
</head>
<body>
<?php
session_start();
$con = mysqli_connect("127.0.0.1", "root", "", "service");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
echo "<br />";
$query_kompetens = "SELECT kompetens FROM kompetens";
$kompetens = mysqli_query($con, $query_kompetens);
echo "<select name='Kompetens'>";
echo "<option size =30 ></option>";
while ($row = mysqli_fetch_array($kompetens)) {
echo "<option value='" . $row['Kompetens'] . "'>" . $row['Kompetens'] . "</option>";
}
echo "</select>";
;
?>
</body>
</html>

Try This code, actually you used $row['Kompetens'] instead of $row['kompetens'].
<!DOCTYPE html>
<html>
<head>
<title> Greetings. </title>
<meta charset="UTF-8"/>
</head>
<body>
<?php
session_start();
$con = mysqli_connect("127.0.0.1", "root", "", "servicedesk");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
echo "<br />";
$query_kompetens = "SELECT kompetens FROM kompetens";
$kompetens = mysqli_query($con, $query_kompetens);
echo "<select name='Kompetens'>";
echo "<option size =30 ></option>";
while ($row = mysqli_fetch_array($kompetens)) {
echo "<option value='" . $row['kompetens'] . "'>" . $row['kompetens'] . "</option>";
}
echo "</select>";
;
?>
</body>
</html>

Related

PHP code is not working inside HTML

As all have commented I have changed my code. Now the thing is when I am running my below php code as separate file its running like charm:
<?php
require("phpsqlajax_dbinfo.php");
$conn = new mysqli($hostname, $username, $password, $database);
$sql = "SELECT username FROM users";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
echo "</select>";
?>
Like this:
But when I am trying to include this into html code its not working:
<!DOCTYPE html>
<html>
<head>
<title>FusionCharts Column 2D Sample</title>
</head>
<body>
<div>
<?php
require("phpsqlajax_dbinfo.php");
$conn = new mysqli($hostname, $username, $password, $database);
$sql = "SELECT username FROM users";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
echo "</select>";
?>
</div>
<div id="chart-container">LOADING....</div>
<script src="js/jquery-2.2.4.js"></script>
<script src="js/fusioncharts.js"></script>
<script src="js/fusioncharts.charts.js"></script>
<script src="js/themes/fusioncharts.theme.zune.js"></script>
<script src="js/userChart.js"></script>
</body>
</html>
Its giving empty drop box:
Remove select inside select and don't mix mysqli_* with mysql_*.Do like below:-
<div>
<select>
<?php
require("phpsqlajax_dbinfo.php");
$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT username FROM users";
$result = $conn->query($query);
?>
<?php
while ($line = $result->fetch_assoc()) {
?>
<option value="<?php echo $line['username'];?>"> <?php echo $line['username'];?> </option>
<?php
}
?>
</select>
</div>
Note:-
file extension must be .php not .html.
Don't use (deprecated + removed) mysql_* library. Use mysqli_* or PDO

UPDATE single column in database: PHP&MYSQL

So, I am trying to figure out how do this this and it boggling me. THIS WILL NOT BE USED ONLINE LIVE SO SQL INJECTION I DONT' CARE ABOUT. What am I doing wrong/right?
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_GET['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = $id";
$comment1 = mysql_query($sql);
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
echo $sql;
The main problem is with the statement itself, the connection is fine. I am trying to read $comment, and then update that into a MYSQL table and then have it read back in a different file.
EDIT: Mark up for the form I'm taking $comment from.
<!DOCTYPE html>
<html lang="en">
<LINK href="stylesheet.css" rel="stylesheet" type="text/css">
<script src ="js/validateform.js"></script>
<head>
<meta charset="UTF-8">
<title>UniHelp Home</title>
</head>
<body>
<div id="headeruni">
<h1>Welcome <?php echo $_GET["name"]; ?> to UniHelp!</h1>
</div>
<div id ="infouni">
<h3>Welcome to UniHelp. The social Network getting you connected to other people all over the University for any help you require!</h3>
</div>
<div id ="nameandemail">
<form action="formsend.php" method="post">
First name: <br> <input type="text" name="name"><br>
Email: <br> <input type="text" name="email"><br>
Comment: <br> <input type="text" name="message"><br>
<input type="submit" name="submit">
</form>`enter code here`
</div>
<div id="grabphpdiv">
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$result = mysql_query("SELECT * FROM Dbsaved", $db);
if (!$result) {
die ("Database query failed: " . mysql_error());
}
$comment = $_POST['$comment'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo 'Comment: <br>
<input type=text name=comment><br>
<a href=addcomment.php?id=' . $row[0]. '&comment='. $row['$comment'].'>Comment</a>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
</div>
</body>
<div id="footer">Copyright &copy James Taylor 2016</div>
</html>
I just ran this code:
$comment = "Hello World!";
$id = 1;
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = {$id}";
echo $sql;
and saw:
UPDATE Dbsaved SET comment = 'Hello World!' WHERE id = 1
which is a correct SQL statement, so if it is not working, you might want to play with SQL directly to get something working. Hope that helps!
SOLUTION:
$comment = $_GET['$comment'];
$id = $_GET['$id'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo $row[4] . "";
echo "<br>";
echo 'Comment: <br>
<form action="addcomment.php?id=' . $row[0]. '" method="post">
<input type=text name=comment><br>
<input type=submit name="submit">
</form>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
and:
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_POST['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '$comment' WHERE id = $id ";
$comment1 = mysql_query($sql);
echo $sql;
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
else {
header("location: UniHelpindex.php");
}
It was to do with mainly needing to get the id which was used in $row[0]' in the form created in the while loop. And actually using the correct syntax for the update Dbsaved... bit.

how to access form data using post in loop

I am trying to access data from form field which is dynamically created and store it to db.I don't know how to do that.I tried many ways but didn't worked.please help me.Thank you for reading this.....
<html lang="en">
<head>
<title>toggle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'attendance';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from student', $link);
if(isset($_POST["submit"]))
{
$name=$_POST['student'];
echo $name;
}
?>
<script type="text/javascript">
function change(obj) {
var tr=obj.parentNode; // this may change depending on the html used
tr.style.backgroundColor=(obj.checked)? 'green' : 'red';
}
</script>
<style type="text/css">
.nochange, tr {background-color:green;}
</style>
</head>
<body onLoad="change(this)">
Report Attendance
<table border="1" cellspacing="2" cellpadding="5" summary="">
<form name="myform" action="" method="post">
<?php while ($row = mysql_fetch_assoc($res)){
echo "<tr class='nochange'><td><input type='checkbox' name='student' value='" . $row['stu_id'] . "' checked style='background:#f00;' onClick='change(this);'>" . $row['stu_name'] . "<br />"."</td></tr>";
}?>
<input type="submit" name="submit" value="submit"/>
</form>
</table>
</body>
</html>
Make checkbox an array
<html lang="en">
<head>
<title>toggle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'attendance';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from student', $link);
if(isset($_POST["submit"]))
{
//Here goes array
for($i=0;$i<count($_POST['student']);$i++)
{
$name=$_POST['student'][$i];
echo $name;
}
}
?>
<script type="text/javascript">
function change(obj) {
var tr=obj.parentNode; // this may change depending on the html used
tr.style.backgroundColor=(obj.checked)? 'green' : 'red';
}
</script>
<style type="text/css">
.nochange, tr {background-color:green;}
</style>
</head>
<body onLoad="change(this)">
Report Attendance
<table border="1" cellspacing="2" cellpadding="5" summary="">
<form name="myform" action="" method="post">
<?php while ($row = mysql_fetch_assoc($res)){
echo "<tr class='nochange'><td><input type='checkbox' name='student[]' value='" . $row['stu_id'] . "' checked style='background:#f00;' onClick='change(this);'>" . $row['stu_name'] . "<br />"."</td></tr>";
}?>
<input type="submit" name="submit" value="submit"/>
</form>
</table>
</body>
</html>
You need to create array of checkboxes and then loop over it in $_POST.
HTML:
<?php while ($row = mysql_fetch_assoc($res)){
echo "<tr class='nochange'><td><input type='checkbox' name='student[".$row['stu_id']>"]' value='" . $row['stu_id'] . "' checked style='background:#f00;' onClick='change(this);'>" . $row['stu_name'] . "<br />"."</td></tr>";
}?>
In PHP posted file,
if (! empty($_POST['student'])) {
foreach ($_POST['student'] as $stu_id -> $student) {
echo '<br/> Student Id: ' . $stu_id;
}
}
Also, never user mysql_* functions are they are deprecated and will be removed in PHP's further releases.

Why will it not update to the database?

This is my code :
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="blah"; // Mysql password
$db_name="test"; // Database name
$tbl_name="SubCategories"; // Table name
$con=mysqli_connect("$host", "$username", "$password", "$db_name");
if (mysqli_connect_errno()) // Check connection
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="untitled.php" method="post"><!-- untitled.php -->
<?php
//print_r($_POST); //print all checked elements
//echo "<br>".$email, $_POST["update"][$i];
//mysql_real_escape_string ($route )
if(isset($_POST['submit'])) {
foreach ($_POST["holder"] as $i=>$email) {
$y=$email;
$h=$_POST["update"][$i];
$res2=mysqli_query("UPDATE ".$tbl_name." SET subCat2 = '" . $y . "' WHERE id =". $h,$con);
if ($res2){
}
else{
echo "<h1>NOT WORKING!</h1>";
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
}
$result = mysqli_query($con,"SELECT * FROM $tbl_name");
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo '<input type="text" name="holder[]" id="checkbox-1" class="custom" value=" ' . $row['subCat2'] . '"/>';
echo '<input type="hidden" name="update[]" id="checkbox-1" class="custom" value=" ' . $row['subCatNum'] . '"/>';
echo "<br>";
}
?>
</br>
<input type="submit" name="submit">
</form>
</body>
</html>
I can't update the table in my database. I am able to extract the variables properly and echo them, however it does not work.
I have gotten the following error in the past 'no database selected'.
I think that you forgot to select the database. Try to put this after your connection:
if (!mysqli_select_db($con, $db_name)) {
die("Uh oh, couldn't select database $db_name");
}
If this happens, double check the name, permissions, etc.
Try it again, but without the quotes surrounding the DB connection variables. I mean, they are variables & not strings, right?
Original with quotes:
$con=mysqli_connect("$host","$username","$password","$db_name");
Cleaned without quotes:
$con=mysqli_connect($host,$username,$password,$db_name);
You should change your code adding the snippet below. This way you can debug your code better:
if (!$result = $mysqli->query("YOUR-SQL", MYSQLI_USE_RESULT)) {
printf("Error: %s\n", $mysqli->error);
}
...do something here..
$result->close();
Someone in my class helped me figure it out, thanks though! Here is the code, just wonderful :)
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="blah"; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
$con=mysqli_connect($host,$username,$password,$db_name);
if (mysqli_connect_errno()) // Check connection
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="untitled.php" method="post"><!-- untitled.php -->
<?php
if(isset($_POST['submit'])) {
foreach ($_POST["holder"] as $i=>$email) {
$y=$email;
$h=$_POST["update"][$i];
$sql2="UPDATE ".$tbl_name." SET name = '" . $y . "' WHERE id =". $h;
//$res2=mysqli_query("UPDATE ".$tbl_name." SET name = '" . $y . "' WHERE id =". $h,$con);
$res2=mysqli_query($con,$sql2);
if ($res2){
}
else{
echo "<h1>NOPE!</h1>";
print "Failed to connect to MySQL: " . mysqli_error();
}
}
}
$result = mysqli_query($con,"SELECT * FROM ".$tbl_name);
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo '<input type="text" name="holder[]" id="checkbox-1" class="custom" value=" ' . $row['name'] . '"/>';
echo '<input type="hidden" name="update[]" id="checkbox-1" class="custom" value=" ' . $row['id'] . '"/>';
//echo '<input type="text" class="a" name="holder2[]" id="checkbox-1" class="custom" value="' . $row['price'] . '" />';
echo "<br>";
}
?>
</br>
<input type="submit" name="submit">
</form>
</body>
</html>

how can i insert the values of my checkboxes into my database?

i have here my codes regarding my checkboxes, but i got some errors when i click my submit button. though it prints all the values i selected on the checkbox but ive got an error on my sql script saying "Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\project\candidate\president2.php on line 21". i just want to save the values i selected on my database. pls help..
<?php session_start(); ?>
<?php
//server info
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'user';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
?>
<?php
if ($_POST['representatives']){
$check = $_POST['representatives'];
foreach ($check as $ch){
//this is my line 21 error. what i want here is to save the selected checkbox into my database but i got some error and i couldnt save it to my database
mysqli_query("INSERT INTO sample (name) VALUES ('". $ch ."') ");
echo $ch. "<br>";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<script type="text/javascript">
<!--
function get_representatives_value()
{
for (var i=0; i < document.list.representatives.length; i++)
{
if (document.list.representatives[i].value = true)
{
return document.getElementById('txt').innerHTML =document.list.representatives[i].value
}
}
}
//-->
</script>
title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="candidate.css" rel="stylesheet" type="text/css">
</head>
<body> <p id="txt"></p>
<form name="list" action="president2.php" method="post" onSubmit="return get_representatives_value()">
<div id="form">
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM candidate_info WHERE position= 'representatives' AND department ='CCEITE' ORDER BY cand_id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>Student ID</th><th>Candidate ID</td><th>Course</th><th colspan = '3'>Name</th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->cand_studid . "</td>";
echo "<td>".$row->cand_id."</td>";
echo "<td>" . $row->course . "</td>";
echo "<td coslpan ='5'>" . $row->fname . " ". $row->mname ." ". $row->lname ." </td>";
echo "<td><input type ='checkbox' name='representatives[]' id='". $row->studid ."' value='" . $row->fname . " ". $row->mname ." ". $row->lname . "'onchange='get_representatives_value()' /></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
echo "<input type='submit' name='representatives value='Submit' />";
?>
</div>
</form>
</body>
</html>
heres the preview of my output, first pic is i selected 2 candidate and the other is one.
The mysqli_query function requires the $mysqli link to be the first parameter. There are two ways you can fix your error. Below is the ERROR
mysqli_query("INSERT INTO sample (name) VALUES ('". $ch ."') ");
To fix this simply change it to one of the two below > (Id use the first option because you already use it in your code somewhere.)
$mysqli->query("INSERT INTO sample (name) VALUES ('". $ch ."') ");
OR
mysqli_query($mysqli, "INSERT INTO sample (name) VALUES ('". $ch ."') ");
As it says, the function mysqli_query() expects at least two parameters. According to the PHP documentation, the first parameter should be:
A link identifier returned by mysqli_connect() or mysqli_init()
Followed by the query as the second parameter. You don't appear to be using either of those functions in your code. Seeing that you declared a mysqli object, you probably meant to use $mysqli->query() instead.
Just take a look at my example and i'm hoping that it would helps you..:-
<?php
if(isset($_POST['team']))
{
foreach($_POST['team'] as $value){
$insert=mysql_query("INSERT INTO team('team') VALUES ('$value')");
}
}
?>
<html>
<body>
<form method="post" action="lol.php">
<input type="checkbox" name="team[]" value="IN"> India<br />
<input type="checkbox" name="team[]" value="DK"> Dark <br />
<input type="checkbox" name="team[]" value="LA"> lolax <br />
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>

Categories