Search to MySQL table using jQuery, Ajax and PHP not working [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to create a search engine for a MySQL table with jQuery, Ajax and PHP. I have a database on my external server in order to get data from. Here is a pic of the MySQL database table.
I have these two scripts for the search engine:
index.html
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<input id="searchdb"/>
<div id="resultdb"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#searchdb').change(function() {
$.ajax({
type: 'GET',
url: 'getdb.php',
data: 'ip=' + $('#searchdb').val(),
success: function(msg) {
$('#resultdb').html(msg);
}
});
});
});
</script>
</body>
</html>
getdb.php
<?php
if ($_GET['insert']) :
$insert = preg_replace('#[^0-9]#', '', $_GET['insert']);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM test WHERE id='.$insert.'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc()
echo $row["name"];
}
endif;
?>
What I want is to type the id, hit enter and get back the name or "0 results". There seems to be something wrong with the code I wrote. Could you please help me? Thanks in advance.

The period characters in your SQL text string are being interpreted as literal dot characters, not PHP concatenation.
e.g.
$sql = "SELECT id, name FROM test WHERE id='.$insert.'";
echo "SQL=" . $sql;
should return:
SQL=SELECT id, name FROM test WHERE id='.123.'
That would be easy enough to fix. But why include the value as part of the SQL text in the first place.
Using prepared statements and bind placeholders is really not that hard.
Use a static string as a SQL statement, use a question mark as a bind place holder, and call the mysqli_stmt_bind_param function. And check the prepare and execute calls for errors. (Those return FALSE if an error occurs.) And the call to num_rows isn't necessary. Just do a fetch. If it returns a row, you've got a row. If it returns FALSE, there wasn't a row to return.
Something like this:
$sql = "SELECT id, name FROM test WHERE id = ? ";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("i",$insert);
if ($stmt->execute()) {
if ($row = $stmt->fetch_assoc()) {
echo $row['name'];
} else {
echo "0 results";
}
} else {
// handle error
die $conn->error;
}
} else {
// handle error
die $conn->error;
}
You could handle the error conditions differently, depending on your requirements.

Related

Reload an html page without refreshing/redirecting it [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 4 years ago.
I would like to try to find a way to reload my HTML page without making it refresh. For example, I want through a PHP file to reload my 1st page to a second page. Here is my try, but it shows me this message -->
Parse error: syntax error, unexpected '<' in C:\wamp64\www\PHP\pesto.php on line 26
Here is my php file:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
$result[]=$row['site_id'];
}
if ($res){
if($result[0] <20){
<script>
$.get("updated-content.html", function(data, status){ $("body").html(data); }).fail(function(e) { alert( "error" +JSON.stringify(e)); })
</script>
});
}
}
// while($row = mysqli_fetch_array($res)){
// array_push($result, array($row[0]));}
// echo json_encode(array($result));
// Close connection
mysqli_close($link);
?>
I don't want to use PHP redirection. I want to make that happen with the usage of jquery. Is it possible?
The error unexpected syntax clearly explains what the problem is... it does not expect that to be there!
Common fix : Check your semicolon and brackets.
It is obious you MUST use a " or '.
if ($res){
if($result[0] <20){
echo '<script>
$.get("updated-content.html", function(data, status){ $("body").html(data); }).fail(function(e) { alert( "error" +JSON.stringify(e)); })
</script>';
}
}
Also you should be using prepared statements as your code above is vulnerable to SQL injection. You can learn more by Googling "SQL Injection" and "Prepared Statements PHP".
You can also use PHP to include or require files based on conditions...
Such as :
<?php
if ($res){
if($result[0] <20){
include 'updated-content.html';
}else{
include 'file.html';
}
}
?>

i can't put the input data into the database

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

PHP/AJAX getting id from ajax

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);

how to turn a php session into a usable variable

i have created a site were i have 2 tables on a database. the first page has 2 links which when clicked sends the name of the link to a php session. it then takes you to a page were its meant to view ether one of the databases based on the data that has been saved In the php session.
what i am trying to achieve is to have those links open up the table inside that file that will open up when the link is clicked. i don't want to make a new .php file for every table since i want to be able to simply add and access those tables on one document but not more then one.
that is my problem. on that document were it sends me to access the table from my database i want to access in variable (code below). the code below will explain what i need to know.
this is the code which i view the data in my table
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM tablenamehere ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>". $row["firstname"]. " " . $row["lastname"] . "</p>";
}
} else {
echo "0 results";
}
$conn->close();
>
the code below is were i want to have the variable that has the name of the link i clicked on the page which gets redirected to this when the link is clicked. the variable that i gather from the php session i want to appear at the tablenamehere text.
$sql = "SELECT id, firstname, lastname FROM tablenamehere ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
the code i have so far which creates the php session but is not connected to links yet are below.
<html>
<body>
Register Now!
</body>
</html>
<?php
session_start();
?>
<?php
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
echo "the veriable is " . $_SESSION['link'] . "<br>";
i only want multiple tables to open up in this one php file. thank you for helping, any questions please message below.
If we can assume you are passing a table name as a parameter ( bit dangerous ) then you can do this
<?php
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
$sql = "SELECT id, firstname, lastname
FROM {$_SESSION['link']}
ORDER BY id
DESC LIMIT 500";
But a better way might be to pass an indicator to the table you want to use. This way you are not passing a real table name around in the ether for people to see
if(isset($_GET['a'])){
$_SESSION['link']=$_GET['a'];
}
switch ($_SESSION['link']) {
case : 'a'
$tbl_name = 'table1';
break;
case : 'b'
$tbl_name = 'table2';
break;
default:
$tbl_name = 'default_table';
}
$sql = "SELECT id, firstname, lastname
FROM $tbl_name
ORDER BY id
DESC LIMIT 500";
My guess: the script that accesses the database is test1.php. The link adds already the call parameter a (=newtable):
Register Now!
The script test1.php could honor this $_GET parameter like you do when setting the $_SESSION parameter. The modification of your code would then look like this:
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get and sanitize table name
$tablename = $conn->real_escape_string($_GET['a']);
$sql = "SELECT id, firstname, lastname FROM $tablename ORDER BY id DESC LIMIT 500";
$result = $conn->query($sql);
// ....
Notes:
In my example I assume that all tables are handled the same way. Of course, you could differentiate code based on the value of $tablename.
You most probably would not need a $_SESSION variable.
If, for any reason you must use a $_SESSION variable $_GET['a'] obviously should be overwritten by $_SESSION['link'] or vice-versa.
For security reasons, do not forget to sanitize the input parameter $_GET['a']!

PHP Mysql Insert Into not working, no error given no data posted to DB, earlier the same page was working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have problem regarding noted above. My code in php is as under:
$con = mysql_connect(xxxx,xxx,xxx) or die(mysql_error());
mysql_select_db(xxx) or die(mysql_error());
if (count($_POST) > 0) echo "form submitted";
if(isset($submit))
{
$name = $_POST['std_name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$user_type = "student";
if(mysql_query("insert into login (user_id, user_pass, User_type) values ('$email','$pass','$user_type'", $con))
{
echo "<p class='success_msg'>Congrats! your registration has successfully been done.</p>";
echo mysql_error();
}
else
{
echo mysql_error();
}
Earlier this code was working well and the values were being entered into database. but suddenly it is not working and not even giving any error. any help in the regard will be highly appreciated, please.
$submit is not set in the code sample
You are missing a closing bracket at the end of your query
Read about 'SQL injection', your code is vulnerable
Here's what might help...
Connect to your MySQL database via PHPMyAdmin or via SSH.
Once connected, type the query manually (so, INSERT INTO login() etc) — if it works, then it's a bug further up your code. If this is the case, you need to show us more.
OK, so I've applied a nice PDO version down below.
$host = "localhost";
$port = 3306;
$dbname = "myDatabase";
$user = "myUser";
$pass = "myPass";
$db = new PDO("mysql:host=" . $host . ";port=" . $port . ";dbname=" . $dbname, $user, $pass);
echo (count($_POST) > 0) ? echo "form submitted" : "";
if(isset($submit))
{
$name = $_POST['std_name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$user_type = "student";
$query = $db->prepare("INSERT INTO login(`user_id`, `user_pass`, `User_type`) VALUES (:email, :pass, :utype");
$binds = array(
":email" => $email,
":pass" => $pass,
":utype" => $user_type
);
if($query->execute($binds))
{
echo "<p class='success_msg'>Congrats! your registration has successfully been done.</p>";
}else{
echo "\nPDO::errorInfo():\n";
print_r($db->errorInfo());
}
}
Read the PDO documentation here.

Categories

Resources