Forms not rendering from database - javascript

I am using formbuilder plugin (https://formbuilder.online/) in jquery and I am trying to create a php application that stores forms in mysql database for a user. I am not able to display the forms on back from database to the html. Form data is in JSON.
I have tried a lot of different things and I am running out of ideas. Any suggestions would be helpful. I just need the right direction to think.
PHP file (form.php)
$dbhost = 'localhost';
$dbuser = 'abc';
$dbpass = 'password';
$dbname = 'xyz';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$sql = "SELECT id, code FROM data";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo $row["code"];
}
} else {
echo "0 results";
}
mysqli_close($link);
Jquery File
$('ul li a').click(function (e) {
$.post("./form.php", function (text) {
toggleEdit();
var renderedForm = $('.render-wrap');
formRenderOpts = {
dataType: 'json',
formData: text
};
console.log(text);
renderedForm.formRender(formRenderOpts);
});
});
So, I am getting all the entries for JSON in console. But I am looking for single entry. For example, lets say I have 2 forms stored in database I want to display 1st form on the website. Instead I am not getting anything displayed. But I am getting all the entries in JSON format in console. I new to PHP and I think that is why I am not able to figure this out.

Related

Return MySQL Query as Array for Specific Table Row Clicked

I've been working on this for about 3 days and still cannot figure out how to do this even with all my searches.
Here's what I've already accomplished:
I have a table in index.php that fetches data from a MySQL Database. When a user clicks on any given row in the table, I want the eventDetail.php page to open.
Here's what I haven't figured out yet:
THEN I need eventDetail.php to run a MySQL query that fetches the data for the table row which was clicked on the previous index.php page and store it in an array so I can use the data on the eventDetail.php page where needed.
Here is the code on the index.php page that opens my eventDetail.php page:
index.php
<script>
$(document).ready(function onClickRow() {
$('.clickDetail').click(function(){
var str=$(this).attr("value"); /* Find out which button is clicked, stores
its value in variable 'str'*/
$(window.location = 'eventDetail.php').load('eventDetail.php?str='); /* To
collect data from database */
})
})
</script>
Here's what I have so far in eventDetail.php but not even sure if I've started correctly:
eventDetail.php
<?php
$db_host = '127.0.0.1'; // Server Name
$db_user = 'root'; // Username
$db_pass = 'password'; // Password
$db_name = 'mydb'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$str=$_GET['str']; // collect the row id
$queryRow = ("SELECT id, eventName, description FROM mytable WHERE
id=:id");
I need the id, eventName, description from the row which was clicked on the previous page to be returned to an array so I can actually use that data on this page.
Finally figured this out thanks to #BobRodes.
This is the script you need in index.php:
<script>
$(document).ready(function onClickRow() {
$('.clickDetail').click(function(){
var str=$(this).attr('value'); // Find out which button is clicked, stores its value in variable 'str'
$(window.location = 'eventDetail.php?str='+str).load('eventDetail.php?str='+'/'+str); // To collect data from database
})
})
</script>
And this is the php code you need in eventDetail.php:
<?php
$db_host = '127.0.0.1'; // Server Name
$db_user = 'root'; // Username
$db_pass = 'password'; // Password
$db_name = 'mydb'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$str = $_GET['str']; // collect the row id
$queryRow = ("SELECT id, eventName, description FROM mytable WHERE id='$str'"); // SQL Statement
$result = mysqli_query($conn, $queryRow); // Execute SQL Query
$items = array(); // Create an array and store in a variable called $items
// Statement below fetches the row that was clicked and stores the data in the array $items
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$items[] = $row;
}
}
// Statement below separates each item in the array and converts it to a string and stores in variable named $item
foreach ($items as $item) {
echo $item['id'];
echo $item['eventName'];
echo $item['description'];
}
mysqli_close($conn);
?>
This will open eventDetail.php and return the table row in the database that was clicked in the url. You can then edit the code in the rest of the page to return the data from that row as you like on the page.

$_GET PHP is misbehaving

I'm a javascript newbie and I'm writing an application using javascript with php on the server side, I'm trying to use AJAX to send data to my php script. This is my code below
Javascript:
$(document).on("click", ".uib_w_18", function(evt)
{
var lecturer = document.getElementById("reg_name").value;
//var lecturer = $("#reg_name").val();
var dept = document.getElementById("reg_dept").value;
var level = document.getElementById("reg_level").value;
var course = document.getElementById("reg_course").value;
var start = document.getElementById("reg_time_1").value;
var ade = 2;
window.alert(lecturer);
var dataString = '?ade=' + ade+'&lecturer='+lecturer+'&dept='+dept +'&level='+level+'&course='+course+'&start='+start;
$.ajax({
type: "GET",
url: 'http://localhost/my_queries.php',
data: dataString,
success: window.alert ("I've been to localhost.")
});
window.alert(dataString);
});
and on the server side:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbname = "myDatabase";
$dbpass = null;
//Connect to MySQL Server
echo "yo";
$con = mysqli_connect($dbhost, $dbuser,$dbpass,$dbname);
$level = $_GET['level'];
$lecturer = $_GET['lecturer'];
$sql = "INSERT INTO level1(message, department)
VALUES ($level,'Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ($lecturer,'Jane')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
?>
now the problem is '$sql1' executes successfully but '$sql2' doesn't. I've been on this for a while and found out that $_GET in the script only works for numerical data. I've confirmed that the problem is not from the data type of my table, I can insert literal strings directly from PHP, I'm also confirmed that "dataString" collects data just like I want it to. (window.alert(dataString);) displays correct output.
I feel like I'm missing something very basic but I just can't figure out what it is. and i felt extra pairs of eyes would help, any help would be appreciated, Thank you.
The proper way to pass "dynamic" SQL queries is like so :
$sql = "INSERT INTO level1(message, department)
VALUES ('".$level."','Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ('".$lecturer."','Jane')";

Why is my PHP script returning different results on similar inputs?

Background: I am doing ajax calls to a PHP script which returns data to fill a form based on some file key a user inputs. This form is used so users may edit an incorrectly inputted file key from their original submission.
Problem: If a user wanted to edit a file key, they input it into a text box, hit a button for an ajax pull, the form fills, they can then correct their mistakes and submit. However, if they try to edit the new file key again, the form will not fill and I am getting no results returned from the query. This is the php script I have been using to pull the data from the server.
A sample file key might be: 10000010000-0D-MAN.
This is a good response: 10000010000-0D-MAN,N/A,amibaguest,dfgfdgfd,Electrical
This is the response I get on a newly edited file key: Nothing returned. Id: 20000010000-0D-MAN.
Really baffled at the moment. If more information is needed, please let me know.
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("database", $dbhandle)
or die("Could not select database");
$id = $_GET['param'];
if(isset($_GET['param'])) {
$sql = sprintf("SELECT a.File_key, a.Name, a.Uploader, a.File_descriptor, b.keyword1 FROM files as a, keyword as b WHERE a.File_key='%s' AND a.File_key=b.File_key", mysql_real_escape_string($id));
$result = mysql_query($sql);
if($result === FALSE) {
echo mysql_error();
}
if(mysql_num_rows($result)==1) {
while($myrow = mysql_fetch_array($result)) {
$file_key = $myrow["File_key"];
$name = $myrow["Name"];
$uploader = $myrow["Uploader"];
$file_desc = $myrow["File_descriptor"];
$keyword = $myrow["keyword1"];
$text_out .= $file_key.",".$name.",".$uploader.",".$file_desc.",".$keyword;
}// end while
} else {
$text_out = " Nothing returned. Id: ".$id;
}// end else
}// endif
echo $text_out;

Accessing MySQL database in d3.js with php file

I need some help with MySQL and D3 with a php file.
I am trying to get access to my database using D3. I have created a php file where I make the connection to MySQL.
My problem is however that I get an empty array when printing out my output to the console from D3. I can't seem to find what I am doing wrong. Below is my code for both the D3 call and the php file: (I have appropriate names from username, password and database name.)
<?php
$host = "localhost";
$port = 8889;
$username = "********";
$password = "********";
$database="***datebasename***";
if (!$server) {
die('Not connected : ' .mysql_error());
}
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
if (isset($_GET['type'])) {
$type = $_GET['type'];
} else {
$type = "null";
echo "Type not passed";
}
if($type=='load'){
$string = '';
$gene = $_GET["gene"];
$data = $_GET["data"];
$myquery = "select gene_data.gene_data from genes inner join gene_data on genes.id=gene_data.g_id where genes.name ='$gene' and genes.type='$data'";
$query = mysql_query($myquery);
if ( !$myquery || !$query) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
}
?>
My file are all running from a server. The MySQL server is also on the same server, so I jut call localhost to get access. Also since I need several different parameters for my SQL calls I send the values from D3 ("gene" and "human").
The following the call I make from D3:
d3.json("getdata.php?type=load&gene=CLL5&data=human", function(error, data) {
console.log(data);
});
Also it is worth mentioning that my query is tested and works.
Some help would be greatly appreciated! Any ideas on how to debug with and prints or write.outs would be appretiated as well!

Does SJCL content need to be json_encode(d) when it is read from a database?

Overview
I am attempting to encrypt data, send it to a database, then decrypt the data using the Stanford Javascript Crypto Library (SJCL).
Problem
Whenever I attempt to call the data from the database, I get a "CORRUPT: ccm: tag doesn't match" error. I have looked this up and it seems as if my content or password is corrupted, and because the password is being straight from a textbox, I have narrowed it down to the content.
Code Snippet
(PHP)
$paste = $_GET['url'];
$query = "SELECT * FROM posts WHERE url='$paste'";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
$t = $row['title'];
$c = $row['content'];
$con = json_encode($c);
$e = $row['encode'];
$ca = $row['Catagory'];
$en = $row['encrypted'];
(Javascript) -Invokes SJCL-
<script type="text/javascript">
var content = <?php echo $con; ?>;
function decryptPaste() {
try {
sjcl.decrypt(document.getElementById("decrypt-pass").value, content)
} catch (e) {
alert("Can't decrypt: " + e);
}}
Any and all help appreciated, thanks in advance!

Categories