Can't connect to my MySQL database using PHP mysqli_connect() - php

Background: I am attempting to run some AJAX on keyup in a search box that will go to the database for a lookup, then return the results without refreshing the page.
The Problem: I'm not confident that it's actually connecting to my database. I've tested the connection using THIS METHOD, and it says that it's successful for the credentials I'm using. However, I can change the host from locahost to www.MYDOMAINNAME.com OR the server name from my cPanel, and it still says it's a successful connection. If it's successful, then why isn't it running my SQL?
The Question: Is there something wrong with my code below, and if not, is there a better way for me to test what's happening?
Notes: The output in my console is "Error [object Object]". It's hitting search.php successfully, so I don't think it's a file path issue. I also ran the PHP on page load instead of doing it through AJAX and everything seemed to work just fine. I was able to get some results back when I hard-coded a value for $query.
File Structure:
(ROOT FOLDER)
index.php (where the form is)
(PHP FOLDER)
search.php
(JS FOLDER)
search.js
HTML:
<form action="php/search.php" method="post">
<input type="search" class="main-search" name="query" />
<div class="btn btn-lg btn-primary">Search</div></form>
</form>
jQuery:
$(function() {
$(".main-search").keyup(function() {
search($(this).val());
});
});
function search(query) {
$.ajax({
url:"./php/search.php",
type:"POST",
dataType:"json",
data: { query:query },
success: function(data) {
$(".result").html(data);
},
error: function(data) {
$(".result").html(data);
}
});
}
PHP:
<?php
$query = $_POST["query"];
$link = mysqli_connect('localhost', 'USER', 'PASS') or die ('Error connecting to mysql: ' . mysqli_error($link));
mysqli_select_db($link, 'DB_NAME');
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT actual FROM icons WHERE synonym = '$query'")) {
$row = mysqli_fetch_array($result);
echo $row["actual"];
mysqli_free_result($result);
}
else {
echo "No results found.";
}
mysqli_close($con);
?>

Try changing the AJAX call data paramenter to this
data: { 'query':query }
I think this should work

Just navigate and run the php code directly instead of relying on an AJAX call to test. If there is a connection error then it should be displayed in your echo statement in the browser.
Make sure you have php error reporting running.

Related

AJAX call error 500 (Internal Server Error)

I have a page that, upon loading, fills 3 drop down menus for uses to select from. On my localhost, this works fine, but on my live server I get the error in Developer Tools "POST (my site's name) 500 (Internal Server Error) jquery.js:8630.
Here is the jquery:
$(function() {
//after load, populate lists
Update_List_ProcedureAreas_Schedule();
Update_List_Patients_Cancel();
Update_List_Cancel_Reasons();
});
Here's one of the functions, but the other two are nearly identical, but all 3 fail. I send to a generic functions php file the function that I want to run, and if there are any parameters with the function as well. Maybe be a bit weird, but it helps me organize my code:
function Update_List_Patients_Cancel() {
$.ajax({
url: 'php/functions.php',
type: 'POST',
dataType: 'json',
cache: false,
data: {Function_ID: 'pull_patient_list_cancel'},
success: function(data){
var dropDown = document.getElementById("selectedpatient_cancel");
dropDown.options.length=0;
dropDown[dropDown.length] = new Option('', '')
for (i = 0; i < data.length; i++) {
dropDown[dropDown.length] = new Option(data[i].Patient_Name, data[i].Patient_UID)
}
},
error: function() {
}
});
}
Here is the PHP in 'php/functions.php' which takes the Function_ID and then uses a switch to verify the input and then call the function with any appropriate variables:
<?php
session_start();
//Make sure a funciton was sent
if(isset($_POST['Function_ID']) == true) {$tempFunction = $_POST['Function_ID'];}
else {echo "No fuction selected";}
//switch to functions
switch($tempFunction) {
case 'pull_patient_list_cancel':
pull_patient_list_cancel();
break;
}
//Pull patient list for cancel drop down
function pull_patient_list_cancel() {
require $_SESSION['db_connect']; //code to connect to the database, which is successful, btw
$returnArray = array();
$sql = "
SELECT Patient_UID, Patient_Name
FROM tbl_patients
WHERE Active = 1
";
if($result = $conn->query($sql)) {
$conn->close();
foreach($result->fetch_all(MYSQLI_ASSOC) as $row) {
$returnArray[] = $row;
}
echo json_encode($returnArray);
} else {
$conn->close();
echo "Failed - pull patient lists cancel";
}
}
It looks like for some reason, I'm not able to execute in the foreach loop. I've put in bogus echos to see where the function stops running, and it won't output any echo within the for each loop or after it, but it will up until that loop starts. I've check the response log in Development Tools and see the bogus echos coming through until the foreach loop, and then nothing.
Any ideas?
------------Solution-----------------
The problem was that I had mysqlnd installed on my localhost xampp setup, but it did not install on my digitalocean lampp server that I set up today. So that made the fetch_all(MYSQLI) not work. However, I could stick with the mysql installation and use fetch_assoc() and it worked fine.
But, I ended up installing mysqlnd on my digitalocean droplet by using:
apt-get install php5-mysqlnd
and then restarting the server with
service apache2 restart
and now all of my fetch_all(MYSQLI) functions work. Thanks everyone for your help.
You cannot close the connection before you fetch the results for the foreach. Move the connection close after the loop.
Better still, remove both connection close statements, and put a single one after the else block.
if($result = $conn->query($sql)) {
foreach($result->fetch_all(MYSQLI_ASSOC) as $row) {
$returnArray[] = $row;
}
echo json_encode($returnArray);
} else {
echo "Failed - pull patient lists cancel";
}
$conn->close();
There is syntax error on your PHP function page....
You cannot use isset like this
change your code from
if(isset($_POST['Function_ID']) == true) //which is wrong
To
if(isset($_POST['Function_ID']) && $_POST['Function_ID'])==true)
// this is the right way
Connection should be closed after all the program has executed and
else{}
$conn->close();

ajax and php: how to select variables from database and insert in database using ajax

I really have never done this before and I am getting frustrated because I'm not sure how it fits together. I have a function that I want to call my php (one php file selects info from a database and the second inserts into the database)... I need to use ajax in the way my site is setup but I don't know how to pass data from and to the php files.
In first .js file:
q1LoadVar();
This is my ajax function in second .js file that I have so far (not working):
//ajax code has been edited here since original post:
function q1LoadVar() {
alert("called"); //works!
$.get( "q1LoadVar1.php", function( data ) {
console.log(data); //nothing happens!
// alert(data); //nothing happens!
}, "json" );
}
And here is the code I have in q1LoadVar1.php that I want to select data back from and be able to populate a text area in my html:
/*works when I type this file path directly into the url;
but the file is not communicating back to the ajax function on the
.js file that is calling it*/
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
echo '<script type="text/javascript">alert("working from php!");</script>';
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
$newRow[] = $row;
}
$json = json_encode($newRow);
echo $json; //works on php file directly!
/*while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_AnswerChoosen];
}*/
mysqli_free_result($result);
mysqli_close($link);
?>
Can someone help me understand how to make this all work together? Thank you, Kristen
You can retrieve post data from ajax in php with
$_POST['action']
//in your case will return: test
To return data to ajax you need to use echo
If the success: callback function doesnt get called try to remove datatype: 'json'
I also think that you need to echo $newrow instead of $row.
If this still doesnt work you can catch the error with the error: callback function to see what is wrong.
Try to start with a simple request and work from there.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "yourphp.php",
data: {simplestring: "hi"},
success: function(result){
alert(result);
}
});
});
and yourphp.php
<?php
$simplestring = $_POST['simplestring'];
echo $simplestring;

My href links not working when contained within ajax call

I am having a bizarre problem that I cannot figure out. It is quite possible that I just do not know something fundamental which is the cause. I really have no idea. Anyway; I have a function on a page that uses mysql to look up divisions; then it has buttons for each division; and when you click each button; a team list for each division appears within a div container. the buttons send a "div_id" value to the container. The container then uses ajax to go back to mysql and then look up the teams for that division and output information on them. This is all working. But when I try and have the php file which is called from ajax list a simple href link for each team; the links do not appear. It really seems that I cannot have href links present in the php file that is called by ajax.
I do not think I need to post all of the code for all the buttons and all that, if so please let me know; here is the script that does the ajax call on the php file:
<script>
function MyRadFunction(DivId) {
var answer = DivId;
$.ajax({
cache: false,
type: 'GET',
url: 'http://jba.gtdsites.com/gscript3_links.php',
data: 'answer=' + answer,
dataType: 'html',
success: function(response) {
$('#ajax_content').html(response);
}
});
}
</script>
and here is the php file that is called:
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
$div_id=$answer;
/* Connect to a mysql database using driver invocation */
$dsn = 'mysql:dbname=gtdtables;host=gtdtables.db.1567753.hostedresource.com';
$user = 'username';
$password = 'password';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT * FROM teams WHERE div_id=$div_id";
foreach ($dbh->query($sql) as $resultsg1)
{
$team_id=$resultsg1[team_id];
$team_name=$resultsg1[team_name];
echo "<a href='/team-schedules/?gc_start=2&team_id=<?php echo $team_id; ?>'><?php echo $team_name; ?></a><br/>";
echo $team_name . "<br/>";
echo $team_id . "<br/>";
?>
Teams Page not link
Final Exam 1
<?php echo $team_name; ?><br/>
<?php
}
}
?>
I echoes the team name and team id just fine; and where i just have it print text that works as well; but all of the html hyperlink stuff just does not appear; I tried a few different ways. Can anyone tell me why this is happening?
Your error is kinda funny, but here it is, upon examining the site, on the network tab the markup built from PHP is rendered correctly. But the thing is:
The CSS is the problem:
a { color: #fff; }
Your text color on the links are white. Therefore its not seen, but its there, just change it accordingly.
a { color: #000; } /** or which color you want **/
And in your PHP, properly concatenate the values:
echo "<a href='/team-schedules/?gc_start=2&team_id=".$team_id."'>".$team_name."</a><br/>";
Important note: Don't just directly use variables inside your statements, use prepared statements to produce safer queries. Here is a tutorial for that.

Best way to check the connection to my database js

I work on a web interface which receives and send informations to a distant PostGreSQL database.
From what I found on the internet it seems that the best way is to create a small php script in an external .php file.
I followed that idea,
so I have that script pg_connection.php which tests the connectivity to my database (with a pg_connect) in that style :
$db = pg_connect("host=localhost port=5432 dbname=**** user=**** password=****")
or die("Not Connected");
if ($db) {echo (Connected);} else {echo (Not Connected);}
If I launch only that pg_connection.php in my webbrowser, it works fine (I just have wrotten Connected with the correct login infos entered in my script or Not connected if I put a random ip address).
Then in my .js(+jquery) external script I use :
$(document).ready(function(){
$("#dbstatus").load("php-services/pg_connection.php");
var dbstatus = new String();
dbstatus = $("#dbstatus").val();
if (dbstatus == "Connected")
{ /*jquery code to show a green light on a section in my html page*/}
else { /*jquery code to show a red light*/}
}
And that works partially :
In my $("#dbstatus") object it will replace the default text by Connected or Not Connected,
But it doesn't produce any effect on the green/red light in my conditionnal
Then I went in my Chrome console and type dbstatus, and I realized that the content of my var is
<div id=​"dbstatus" class=​"span3">​Connected​</div>​
when I expected it to be just "Connected".
Any idea on how to clean that var from all these extra html stuffs ?
Is there more simple method implemented in js or Jquery to check a postgreSQL database status ?
Try to modify your code to:
$db = pg_connect("host=localhost port=5432 dbname=**** user=**** password=****") or die("0");
if ($db) {echo "1";} else {echo "0"}
And in JS:
$(document).ready(function(){
$.ajax({
url: "http://fullpathto/php-services/pg_connection.php",
cache: false
}).done(function( result ) {
if(result=="1") {
/*jquery code to show a green light on a section in my html page*/
}
else
{
/*jquery code to show a red light*/}
}
});
});
Instead of $("#dbstatus").val(); use $("#dbstatus").html();.

Query string parameters from Javascript do not make it to processing PHP script

I want to populate a jQWidgets listbox control on my webpage(when page finished loading and rendering) with values from an actual MySQL database table.
PARTIAL SOLUTION: Here
NEW PROBLEM:
I've updated the source code and if I hardcode the SQL string - the listbox gets populated. But I want to make a small JS function - popList(field, table) - which can be called when you want to generate a jQWidgets listbox with values from a MySQL database on a page.
Problem is - for some reason the $field and $table are empty when the PHP script is being executed, and I receive You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM' at line 1 error. What gives?
The page:
<div id="ListBox">
<script type="text/javascript">
popList("name", "categories");
</script>
</div>
popList(field, value):
function popList(field, table) {
$.ajax({
type: "GET",
url: 'getListOfValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: 'json',
success: function(response) {
var source = $.parseJSON(response);
$("#ListBox").jqxListBox({ source: source, checkboxes: true, width: '400px', height: '150px', theme: 'summer'});
},
error: function() {
alert('sources unavailable');
}
});
}
getListOfValues.php:
<?php
require "dbinfo.php";
// Opens a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$field = $_GET["field"];
$table = $_GET["table"];
$field = mysql_real_escape_string($field);
$table = mysql_real_escape_string($table);
$qryString = "SELECT " . $field . " FROM " . $table;
$qryResult = mysql_query($qryString) or die(mysql_error());
$source = array();
while ($row = mysql_fetch_array($qryResult)){
array_push($source, $row[$field]);
}
mysql_close($connection);
echo json_encode($source);
?>
Ok, you have a few things here. First off you need a callback function when you do the ajaxRequest. (I'll explain why in a bit.) So add the following line BEFORE your ajaxReqest.send(null);
ajaxRequest.onreadystatechange = processAjaxResponse;
Then you need to add the processAjaxResponse function which will be called.
function processAjaxResponse() {
if (ajaxRequest.readySTate == 4) {
var response = ajaxRequest.responseText;
//do something with the response
//if you want to decode the JSON returned from PHP use this line
var arr = eval(response);
}
}
Ok, now the problem on your PHP side is you are using the return method. Instead you want PHP to print or echo output. Think about it this way. Each ajax call you do is like an invisible browser. Your PHP script needs to print something to the screen for the invisible browser to grab and work with.
In this specific case you are trying to pass an array from PHP back to JS so json_encode is your friend. Change your return line to the following:
print json_encode($listOfReturnedValues);
Let me know if you have any questions or need any help beyond this point. As an aside, I would really recommend using something like jQuery to do the ajax call and parse the response. Not only will it make sure the ajax call is compliant in every browser, it can automatically parse the JSON response into an array/object/whatever for you. Here's what your popList function would look like in jQuery (NOTE: you wouldn't need the processAjaxResponse function above)
function popList(field,table) {
$.ajax({
type: "GET",
url: 'getListofValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: "json",
success: function(response) {
//the response variable here would have your array automatically decoded
}
});
}
It's just a lot cleaner and easier to maintain. I had to go back to some old code to remember how I did it before ;)
Good luck!

Categories