First of all sorry for the English:)
so hello im a new web programmer and im working on some school manager project.
i have to display all courses in school and then when i click course display his description.
this is my display php code
<?php
$conn = mysqli_connect("localhost", "root", "", "school");
if($conn){
$result = $conn->query("SELECT * FROM `courses`");
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$id=$row['id'];
echo '<div class="alex" onclick="myFunction(this.id)" id="'.$id.'">'.$row['name'].'</div>'.'<br>'.'<br>';
}
}
}else{
echo die("connection faild");
}
mysqli_close($conn);
?>
as you can see i gave it the id of the table which i what to display description.
that is my function code in js file
function myFunction(id){
$.post(
"api/courses/description.php",
{ id:id }
).done(function( data ) {
console.log(id);
$('#desc').load("api/courses/description.php");
});
}
and here is my description php to get id and display description:
<?php $conn = mysqli_connect("localhost", "root", "", "school");
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
if($conn){ $result = $conn->query("SELECT * FROM courses WHERE id = '$id'");
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo $row['description'];
}
}
}else{
echo die("connection faild");
}
mysqli_close($conn); ?>
when i click the displayed courses i get the ids on console!
For every course I click I get his id on console.
hope you could help me!
Im sittin on it for many hours and cant get the problem.
hope its readable T_T
edit:forgot to say..
error i have is
Notice: Undefined index: id in
C:\xampp\htdocs\project\api\courses\description.php on line 9---cant
get id NULL ----------------------------------------> on var dump
Notice: Undefined variable: id in
C:\xampp\htdocs\project\api\courses\description.php on line 10
(---->id = $id undefined -> $id)
You're calling description.php twice. First you call it in an AJAX POST request and successfully supply it the id parameter. This does not generate an error. But then look at what you do with the result of that operation:
console.log(id);
$('#desc').load("api/courses/description.php");
You log the id, which is also successful. Then you ignore the data response and call description.php again. This time as an AJAX GET request where you do not supply it with the id parameter. This is what generates the errors.
Instead of making the second request, just use the returned value of the first request. It looks like you want something like this:
console.log(id);
$('#desc').html(data);
Related
this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe
I have a simple AJAX function bound to a button that should execute a PostgreSQL query. However, when I click the button that I bound the ajax query to, all I get is the confirmation that the database connection was successful. Nothing seems to happen withe the ajax result (should be printing to console in the handleAjax() function. What am I doing wrong?
This is the javascript code (with jquery):
$(document).ready(function() {
function sendAjax() {
$.ajax({
url: "db/database.php",
success: function (result) {
handleAjax(result);
}
});
}
function handleAjax(result) {
console.log(result);
}
$("#submit-button").on("click", sendAjax);
});
And this it the contents of database.php:
<?php
function dbconn(){
ini_set('display_errors', 1); // Displays errors
//database login info
$host = 'localhost';
$port = 5432;
$dbname = 'sms';
$user = 'postgres';
$password = 'postgres';
// establish connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
}
}
$conn = dbconn();
$sql = "SELECT * FROM numbers;";
$result = pg_query( $sql ) or die('Query Failed: ' .pg_last_error());
$count = 0;
$text = 'error';
while( $row = pg_fetch_array( $result, null, PGSQL_ASSOC ) ) {
$text = $row['message'];
//echo $text;
}
pg_free_result( $result );
?>
The problem is in the database.php file, all you get is "Connected." because you don't print your result at the end. Ajax only receive the output of the php file.
So at the end of your php file you should add :
echo $text;
And you also should remove the echo "Connected.";
AJAX is not a magic wand that in magic way reads PHP code. Let's say AJAX is a user. So what does user do.
Open web page
Wait until PHP execute code and display data
Tells you what he sees
If you don't display anything, ajax can't tell you what he saw.
In thi's place is worth to say that the best way to communicate between PHP and AJAX is using JSON format.
Your code generally is good. All you have to do is to display your data. All your data is in your $text var. So let's convert your array ($text) to JSON.
header('Content-Type: application/json');
echo json_encode($text);
First you set content-type to json, so ajax knows that he reads json. Then you encode (convert) your PHP array to js-friendly format (JSON). Also delete unnecessary echoes like 'Conntected' because as I said, AJAX reads everything what he sees.
You should return $conn from dbconn()
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
return $conn;
}
I having written a php script which makes an SQL query and fetches a list of unique names from the database.
I am making an AJAX GET request using jQuery to the php script. When I check resources in the console I see that the php script is being called, and when I check the response it contains a list of unique names.
However, the jquery GET request is failing, and is displaying an error message in the console.
It may be easier and clearer to look at my code, as I have no idea what is the issue here. Please see code below.
php
<?php
header('Content-Type: application/json');
$servername = "****";
$username = "****";
$password = "****";
$dbname = "****";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DISTINCT(name) FROM customer";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo json_encode(array('customer' => $row["name"]));
}
} else {
echo "0 results";
}
$conn->close();
?>
JS
$.ajax({
type: 'GET',
url: 'getcustomers.php',
success: function(data){
console.log(data);
},
error: function() {
console.log('error');
}
});
In the console it simply says error, meaning it has executed the error function.
When I load the php file in the browser it displays the following.
{"name":"Peter"}{"name":"Alan"}{"name":"Mike"}
Your JSON response is not a valid one. You are printing each data row on each iteration. So replace the while statement with this one,
if ($result->num_rows > 0) {
$return = array();
while($row = $result->fetch_assoc()) {
$return[] = array('customer' => $row["name"]);
}
echo json_encode($return);
} else {
echo "0 results";
}
Considering your script returns any result (I hope you've tried running it in broswer) then you can use something like this:
$.get('path/to/file/filename.php').done(function(response) {
$('#exampleDiv').html(response);
});
Although, common errors because you must specify the directory path if the php file you're requesting is outside the current working directory.
change your error handler function header to the following:
error: function (jqXHR, textStatus, errorThrown) {
then print that and see what the error is
you are echoing json_encode string in side while loop, instead of that you will have to push row in an array and at the end you can echo json string only once.
$outputArr = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push(outputArr ,array('customer' => $row["name"]));
}
} else {
echo "0 results";
}
echo json_encode($outputArr);
I'm trying to make a query from my MySQL database here is the code
<?php
$link = new MySQLi('localhost','root','Rrtynt','copy');
if(isset($_POST['id'])){
$name = $_POST['id'];
$profile = 'profile';
$thestring = $name.$profile;
//echo $thestring;
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");
echo $result;
}
?>
the code for the query
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");
works in a different php script the same exact code but it keeps giving me http 500 error, I'm using this to post from a javascript file
$.post("/getfirstfolder.php", { id: value1 }, function (data) {
cop = data;
console.log("Data: " + data);
});
if I take out
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");
and just echo $thestring it works fine, I cant figure out the problem so thank you for your time and your help is greatly appreciated
The fact that you mentioned $thestring, makes me think that perhaps you should be using $thestring as the parameter to the query like this:
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$thestring'");
I'm trying to use php to run a sql select statement to pull data from a database and then only output one column(username) to an array that I can then use to filter using a JS script. Similar to how facebook/twitter does their real time searching of contacts when you start typing someone's name in. I keep getting an error though in php when I try to pull the username column and set it to an array and output that:
<?php
session_start();
include_once 'dbconnect.php';
$contact = mysql_real_escape_string($con, $_POST['contact']);
$sql = "select * from users";
$result = $con->query($sql);
if ($result->num_rows > 0) {
($row = $result->fetch_assoc()) {
printf($row["username"]);
}
} else {
echo "0 results";
}
?>
It would help to know what the exact error PHP is giving you is. But from a cursory look on your code I believe you are missing a while keyword.
while ($row = $result->fetch_assoc()) {
printf($row["username"]);
}