I've been trying a few different methods of getting Select2 to use information from my MySQL database. Currently, it seems something has been lost in translation and it's just showing the literal name of the array(".$title"). The database is called vettigevrijdag and the table is called article.
My PHP snippet that is to be included in the navbar:
<head>
<link href="select2.css" rel="stylesheet"/>
<script src="select2.js"></script>
<script>
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
</script>
<select class="js-example-basic-single">
<?php
include('db.php');
$stmt=$db_con->prepare("SELECT * FROM article");
$stmt->execute();
if($stmt->rowCount() > 0){
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$id = $row['if'];
$title = $row['title'];
echo '<option value="'.$id.'">'.$title.'</option>';
}
}
?>
</select>
</head>
My db.php file:
<?php
$dbhost = "localhost"; /* Host name */
$dbname = "vettigevrijdag"; /* Database name */
$dbuser = "localhost"; /* User */
$dbpassword = "123456"; /* Password */
try {
$db_con = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpassword);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $ex) {
die($ex->getMessage());
//throw $th;
}
?>
<select class="js-example-basic-single">
<?php
include('db.php');
$stmt=$db_con->query("SELECT * FROM article")->fetchall(PDO::FETCH_ASSOC));
foreach($stmt as $key=>$row){
echo "<option value=\"".$row['if']."\">".$row['title']."</option>";
}
?>
</select>
Related
I need to define my website var from mySQL, but I don't know how to get the data to the var. This is what I have so far.
I'm able to get the data in JSON with this:
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
?>
I'm stuck in this part.
<?php
$connect = mysqli_connect("localhost", "user", "", "pricesdb");
$sql = "SELECT * FROM precios";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result)) ?>
<script type="text/javascript">
var websiteVars = {
priceusd: <?php echo ''.$row['priceusd'].''?>,
pricebs: <?php echo ''.$row['pricebs'].''?>
};
</script>
You're redefining the variable websiteVars each time through the loop.
You should keep the original loop that creates the array $json_array, and then encode the entire thing into the JavaScript variable;
var websiteVars = <?php echo json_encode($json_array); ?>;
Thank you very much, I was able to solve the problem this way.
<?php
$db = mysqli_connect("localhost", "root", "", "db");
$sql = "SELECT * FROM precios";
$result = mysqli_query($db, $sql);
while($row=mysqli_fetch_array($result, MYSQLI_ASSOC)){
?>
<script type="text/javascript">
var websiteVars = {priceUsd: <?php echo ''.$row['priceUsd'].''?>, priceBS: <?php echo ''.$row['priceBS'].''?>};
<?php
}
?>
</script>
I got multiple database dropdown lists with javascript, and I want to display result in dropdown menu. But at this moment, nothing shows. It shows Regions (drop down menu), but dosn't show Countries (drop down menu)
My Core Code(I want to display result in Country drop down menu):
<html>
<body>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function abc(){
var e = document.getElementById("Region_ID");
var val = e.options[e.selectedIndex].value;
$.post("getSecondDropDown.php",{ Region_ID:val}, function( data ) {
$("#Country_ID").html(data);
});
}
</script>
<form action="/NewService.php" id="ServiceForm" method="post">
Name:<input type="text" name="Service_Name"></br>
Region: <select name="Region_ID" id="Region_ID" onchange="abc()" form="ServiceForm">
<?php
include('config.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Region_ID, Region_Name FROM Regions");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Region_ID'] ."'>" . $v['Region_Name'] ."</option>";
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
</select></br>
Country: <select name="Country_ID" form="ServiceForm">
<script>document.write($("#Country_ID"))</script>
</select></br>
<input type="submit">
</form>
</body>
</html>
Second php file(getSecondDropDownMenu.php):
<?php
$Region_ID =$_POST['Region_ID'];
$option="";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='$Region_ID'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>";
}
echo $option;
?>
I Think that problem is here, but don't really know it :
Country: <select name="Country_ID" form="ServiceForm">
<script>document.write($("#Country_ID"))</script>
</select></br>
In the second file ( getSecondDropDownMenu ) you need to create a function
<?php
function functionName(){
$Region_ID =$_POST['Region_ID'];
$option[] = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='$Region_ID'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
array_push($option, "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>");
}
return option;
}
?>
Then in the other file the first one include it
include('getSecondDropDownMenu.php');
and do
$arrayForSecondDropdown[] = functionName();
and then do the foreach like
foreach($arrayForSecondDropdown as $v){
echo $v;
}
You can simplify the abc function by calling it with onchange='abc(this.value)' and the target dropdown requires an ID attribute to enable the callback to add the html data. Also, as you are not passing any variables to the sql statement you do not really require the prepared statement, a simple query should suffice.
<html>
<head>
<title>dependant select menu</title>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function abc( value ){
$.post("getSecondDropDown.php",{ Region_ID:value }, function( data ) {
$("#Country_ID").html( data );
}
);
}
</script>
</head>
<body>
<form action="/NewService.php" id="ServiceForm" method="post">
Name:<input type="text" name="Service_Name"></br>
Region: <select name="Region_ID" id="Region_ID" onchange="abc( this.value )" form="ServiceForm">
<?php
include('config.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $conn->prepare( "SELECT Region_ID, Region_Name FROM Regions" );
$stmt->execute();
$result = $stmt->setFetchMode( PDO::FETCH_ASSOC );
foreach($stmt as $v) {
echo "<option value='" . $v['Region_ID'] ."'>" . $v['Region_Name'] ."</option>";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
</select>
</br>
Country: <select id='Country_ID' name="Country_ID" form="ServiceForm"></select>
</br>
<input type="submit">
</form>
</body>
</html>
I think your missed the config file to include in your Second php file(getSecondDropDownMenu.php):. So the scripts in this is not able to run. Why this happens means this page is able to get database connection .ou are fetching the country list from database on the basis of region so here no database connection is achieved.So please include config.php and try again.And also you have done another mistake in concatenation of php variable with the string .IE in the country fetching query you should concatenate the region variable with correct syntax.Please see the below code.
Second php file(getSecondDropDownMenu.php):
<?php
include('config.php');
$Region_ID =$_POST['Region_ID'];
$option="";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='".$Region_ID."'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>";
}
echo $option;
?>
I think this may help you.
You have written the code to display with the help of ID for the select tag but you have not been given any ID for the select tag
<script>document.write($("#Country_ID"))</script>
As per the script you have provided you have to add an ID Attribute for the select tag.
I would recommend not using document.write, especially after the page has loaded. It can lead to unexpected results. Just use this method:
Try Replacing with this:
document.getElementById('Country_ID').innerHTML = "something important";
If however, you are not willing to replace the whole innerHTML, you could append something to it:
document.getElementById('Country_ID').insertAdjacentHTML('beforeend', "something added");
I've done some research and followed a tutorial exactly, with minor changes, but I can't seem to get this to work. No dropdown appears. Can you look at the code and tell me what is not happening?
<div class="ui-widget">
<label for="skills">Skills: </label>
<input id="skills">
</div>
<script>
$(function() {
$( "#skills" ).autocomplete({
width:448,
delimiter: /(,|;)\s*/,
lookup: <?php echo "'autocomplete(#skills)'" ?>
});
});
</script>
<?php
$servername = 'localhost';
$username = 'xx';
$password = 'xx';
$con = mysql_connect($servername,$username,$password);
mysql_select_db('c9', $con);
function autocomplete($inputName){
$searchTerm = $_GET[$inputName];
$query = mysql_query("SELECT * FROM clients WHERE fname LIKE '%".$searchTerm."%' ORDER BY fname ASC");
while ($row = mysql_fetch_array(MYSQL_ASSOC)) {
$data[] = $row['fname'];
}
//return json data
echo json_encode($data);
}
?>
I am connecting to an SQL server via PHP script and displaying the contents retrieved on the browser.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"
href="http://cdn.sencha.com/ext/trial/5.0.0/build/packages/ext-theme-neptune/build/resources/ext-
theme-neptune-all.css">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/php" src="connection.php"></script>
</head>
<body>
</body>
</html>
app.js
document.addEventListener('DOMContentLoaded', function() {
d3.json("connection.php", function (data) {
document.write(data);
});
});
connection.php
<?php
// Server Name
$myServer = "10.112.1.2";
// Database
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=>"logs", "CharacterSet"=>"UTF-8");
$conn = sqlsrv_connect($myServer, $connectionInfo);
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
}
$sql = "SELECT * FROM dbo.logsData";
$data = sqlsrv_query( $conn, $sql );
if( $data === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$result = array();
do {
while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while ( sqlsrv_next_result($data) );
echo json_encode($result);
sqlsrv_free_stmt($data);
sqlsrv_close($conn);
?>
All 3 files are in the same folder.
The browser just displays a null and I don't hit any of the logging information from the .php file. Is my method right? Am I using the right javascript event?
Change your connection.php in this way:
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
header('Content-Type: application/json');
}
You need to change mime type of your response. Moreover you cannot print out anything else than json data. That's way I removed from your code these lines:
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
Try using a relative pathname for connection.php here: d3.json("connection.php"
Something like "/dirname/connection.php".
You can test connection.php alone using a full pathname, like http://www.yourserver.xxx/dirname1/dirname2/...connection.php
I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql.
now i want to post more information to mysql using where clause (form data) in sql statement.
This is my code to submit and post data.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select>Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<body>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="addNew"><span>Add New</span></p>
<div id="addinput">
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<?php
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
its working fine now when am trying to use a select statement and post data to mysql its not working
here is code
<?php
$con=mysqli_connect("localhost","root","","inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
}
mysqli_close($con);
?>
then i modify the post code of above file like this
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$price = $row['price'];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
but nothing is inserted in to database in price column
Change your code to store the price value in a new variable:-
<?php
$con=mysqli_connect("localhost","root","","inventory");
$price = array(); //declare
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
$price = $row['price']; //initiate
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);
}
?>
Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.
Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.
Also, as the other guys have said remove the double $$ and just use one on this line:-
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
Hope this is of some help to you :)
As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.
But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)
I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :
Change this:
<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
to this:
<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);
Change this:
<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );
to this :
<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
EDIT :
Some documentation:
MySQLi
mysqli_prepare (sql queries more protected from sql injection)
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result
mysqli_stmt_fetch