Chrome console error:
POST http://******************** 500 (Internal Server Error)
JS
$.ajax({
method: "POST",
url:"ajax.php",
data: {
x: x,
y: y
},
success:function(data){...}
});
PHP
<?php
date_default_timezone_set('Europe/Madrid');
$link = mysql_connect("*******", "*******", "******");
mysql_select_db("******") or die ("no database");
$name = $_POST['x'];
$score = $_POST['y'];
// Get the current date
$current_date = date('d-m-Y H:i:s');
$sqlCommand = "INSERT INTO hungry_bird (date_played, name, score)
VALUES('$current_date ', '$name', '$score')";
$results = mysql_query($sqlCommand) or die (mysql_error());
mysql_close($link);
?>
Any idea what could be the problem? Thanks.
$link = mysqli_connect("*******", "*******", "******");
mysqli_select_db($link, "******") or die ("no database");
$name = $_POST['x'];
$score = $_POST['y'];
$sqlCommand = "INSERT INTO hungry_bird (date_played, name, score)
VALUES('CURDATE()', '$name', '$score')";
$results = mysqli_query($link, $sqlCommand) or die (mysqli_error($link));
mysqli_close($link);
Related
I need to do the following to finish off my project and as im just learning but need bit of guidance to do the following:
it seems im not populating the department select with the current value in the 'edit employee form', ive been told if i use the getPersonnel.php file it returns the JSON to populate the department select, then all i need to do is set the value of the select to the departmentID value of the employee.
I also know and im going to change my php code to prepared statements to avoid sql injection.
this is my code below:
function updateEditEmployeeModal(employee) {
$.ajax({
url: './php/getPersonnel.php',
type: 'POST',
datatype: 'json',
data: {employeeId: employee.id},
success:function(result){
// console.log(result);
$('#editEmployeeId').html(result.data.personnel[0].id);
$('#editEmployeeFirstNameInput').val(`${result.data.personnel[0].firstName}`);
$('#editEmployeeLastNameInput').val(`${result.data.personnel[0].lastName}`);
$('#editEmployeePositionInput').val(result.data.personnel[0].jobTitle);
$('#editEmployeeEmailInput').val(result.data.personnel[0].email);
$("#editEmployeeDepartmentSelect").val(result.data.personnel[0].departmentId).change();
},
error: function(err){
console.log(err);
}
});
and getPersonnel.php file ::
<?php
// example use from browser
// http://localhost/companydirectory/libs/php/getPersonnel.php?id=1
// remove next two lines for production
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true);
include("config.php");
header('Content-Type: application/json; charset=UTF-8');
$conn = new mysqli($cd_host, $cd_user, $cd_password, $cd_dbname, $cd_port, $cd_socket);
if (mysqli_connect_errno()) {
$output['status']['code'] = "300";
$output['status']['name'] = "failure";
$output['status']['description'] = "database unavailable";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
exit;
}
// first query
$employeeId = $_REQUEST['employeeId'];
$query = $query = "SELECT p.id, p.lastName, p.firstName, p.jobTitle, p.email, p.departmentID as departmentId, d.name as department, l.name as location FROM personnel p LEFT JOIN department d ON (d.id = p.departmentID) LEFT JOIN location l ON (l.id = d.locationID) WHERE p.id = '$employeeId';";
$result = $conn->query($query);
if (!$result) {
$output['status']['code'] = "400";
$output['status']['name'] = "executed";
$output['status']['description'] = "query failed";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
exit;
}
$personnel = [];
while ($row = mysqli_fetch_assoc($result)) {
array_push($personnel, $row);
}
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
$output['data']['personnel'] = $personnel;
mysqli_close($conn);
echo json_encode($output);
?>
I need an AJAX Login Script for my school project.
But it actually won't work because when I try to login, I get kicked to the startpage (login-form) without any message.
That's my backend-script (login2.php):
if(empty($_POST['loginEmail']) || empty($_POST['loginPassword'])) {
$error[] = "Bitte füllen Sie alle Felder aus!";
}
if (!empty($_POST['loginEmail']) && !filter_var($_POST['loginEmail'], FILTER_VALIDATE_EMAIL)) {
$error[] = "Bitte geben Sie eine gültige E-Mail-Adresse an!";
}
if(count($error)>0) {
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email AND `uPassword` = :password";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':email' => $_POST['loginEmail']));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($row)>0) {
if(!password_verify($_POST['loginPassword'],$row[0]['uPassword'])) {
$error[] = "Falsches Passwort!";
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
session_start();
$_SESSION['Email'] = $row[0]['uEmail'];
$resp['redirect'] = "dashboard.php";
$resp['status'] = true;
echo json_encode($resp);
exit;
}
else {
$error[] = "Falsche E-Mail-Adresse!";
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
And this is my JS part of the login form:
$(function() {
$('#login').click(function(e){
let self = $(this);
e.preventDefault();
self.prop('disabled',true);
var data = $('#login-form').serialize();
$.ajax({
url: '/login2.php',
type: "POST",
data: data,
}).done(function(res) {
res = JSON.parse(res);
if(res['status']) {
location.href = "dashboard.php";
} else {
var errorMessage = "";
console.log(res.msg);
$.each(res['msg'],function(index,message) {
errorMessage += '<p>' + message + '</p>';
});
$("#error-msg").html(errorMessage);
$("#error-msg").show();
self.prop('disabled',false);
}
}).fail(function() {
alert("error");
}).always(function(){
self.prop('disabled',false);
});
});
});
When I try to add action="/login2.php" in the form I get a HTTP 500 Error and the message, that it can not process this request at this time.
I'm not sure if this is your main problem, but it's a significant one. You're preparing two parameters:
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email AND `uPassword` = :password";
But you're only binding one:
$stmt->execute(array(':email' => $_POST['loginEmail']));
You don't want to include the password in the select, since you're using password_verify() to validate it later. Change your SQL to this:
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email";
Here is the code:
include_once('class.database.php');
class ManageUsers{
public $link;
function __construct(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link;
}
function registerUsers($password, $ip_address, $date, $time, $username, $email, $uname){
$query = $this->link->prepare("INSERT INTO users (password,ip_address,date,time,username, email, uname) VALUES(?,?,?,?,?,?,?)");
$values = array ($password, $ip_address, $date, $time, $username, $email, $uname);
$query->execute($values);
$count = $query->rowCount();
return $count;
}
function LoginUsers($username, $password){
$query = $this->link->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$rowCount = $query->rowCount();
return $rowCount;
}
function GetUserInfo($username){
$query = $this->link->query("SELECT * FROM users WHERE username = '$username'");
$rowCount = $query->rowCount();
if($rowCount ==1)
{
$result = $query->fetchAll();
return $result;
}
else
{
return $rowCount;
}
}
}
and it is showing me this error
Fatal error: Call to a member function query() on a non-object in
C:\wamp\www\timetable\class.ManageUsers.php on line 22
I want to retrieve images from json in php. Actually I want to get those images sources as json data through php and display using javascript. But I think m doing something wrong please help.
<script type="text/javascript">
function jsonGetImages(name){
var thumbnailbox = document.getElementById("picturebox");
var hr = new XMLHttpRequest();
hr.open("POST", "jsonget.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
picturebox.innerHTML = "";
for(var o in d){
if(d[o].src){
picturebox.innerHTML += '<img src="'+d[o].src+'">';
}
}
}
}
hr.send("name="+name);
picturebox.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="picturebox"></div>
<script type="text/javascript">jsonGetImages('Jason');</script>
</body>
jsonget.php
<?php
header("Content-Type: application/json");
$folder = 'images';
$cn=mysql_connect("localhost","root","");
if(!$cn){
echo "<b>Connection couldn't be established.</b>";
die();
}
$db=mysql_select_db("test",$cn);
if(!$db){
echo "<b>Database doesn't exist.</b>";
}
$dir = $folder."/";
$dirHandle = opendir($dir);
$name=$_POST['name'];
$sql="SELECT * FROM users WHERE name='$name'";
$result=mysql_query($sql);
echo mysql_num_rows($result);
$i=0;
$jsonData = '{';
while($row=mysql_fetch_array($result)){
$name=$row['name'];
$image_name=$row['image'];
$i++;
$file=readdir($dirHandle);
$src = "$dir$image_name";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$name.'" },';
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
Please help. I can't find solution how to get images using json.
You can convert the image to a Base 64 string with php and pass it with JSON
$src = "$dir$image_name";
$type = pathinfo($src, PATHINFO_EXTENSION);
$data = file_get_contents($src);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$myobj = json_encode(array("image"=>$base64));
Then you can simply put that string into the SRC attribue of an image element with javascript.
var obj = JSON.parse(serverResponse);
img.src=obj.image;
$res = mysqli_query($conn,"SELECT * FROM table_name");
while($row = mysqli_fetch_array($res)){
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['al_image']).'" >';
}
I use above code for displaying image. it came in the encrypted format.
after that, you can simply display image through src in JS.
I use this code to return text and image that are saved in the MySQL database. I use PHP to access and the data returned am running on an Android application.
<?php
/*******************************************************
{ }
{ GET IMAGE JSON }
{ }
{ File: GetImageJson.php }
{ Copyright (c) Zicatti Software 2015 }
{ Developer: Osmir Zicatti }
{ }
{ }
{ Used to return the fields in a table }
{ containing image ( BLOB ) using json }
{ }
{*******************************************************}
{*******************************************************}
{ Paramentro necessário: Numero da pagina }
{ Formato de chamada: GetImageJson.php?PAGINA=1 }
{*******************************************************/
$Pagina = #$_GET['PAGINA'];
if (#$_GET['PAGINA'] != '') {
$host="200.200.200.200"; // Host name
$username="BDados"; // Mysql username
$password="password"; // Mysql password
$db_name="DATABASE"; // Database name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
mysql_set_charset('utf8');
// retorna TODOS os campos com as 2 imagens
// $qry = sprintf("SELECT id, pagina, titulo, texto1, texto2, image_thumb, imagem FROM TABELA where pagina = %s",
// Mas vou usar esta para carregar a ListView com o thunmbnail que é menor
$qry = sprintf("SELECT id, pagina, titulo, texto1, texto2, image_thumb FROM TABELA where pagina = %s",
mysql_real_escape_string($Pagina));
$query=mysql_query($qry);
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $qry;
die($message);
}
$return_arr = array();
$row_array = array();
// Verifica se existe algum registro
$num_rows = mysql_num_rows($query);
if ($num_rows > 0) {
while ($r = mysql_fetch_array($query)) {
$row_array['id'] = $r['id'];
$row_array['pagina'] = $r['pagina'];
$row_array['titulo'] = $r['titulo'];
$row_array['texto1'] = $r['texto1'];
$row_array['texto2'] = $r['texto2'];
$row_array['image_thumb'] = base64_encode($r['image_thumb']);
array_push($return_arr,$row_array);
}
}
else { $return_arr['id'] = 'ERRO - Pagina inexistente'; }
echo json_encode($return_arr);
return json_encode($return_arr);
mysql_close();
}
else {
$return_arr['id'] = 'ERRO - Faltou enviar o numero da pagina';
echo json_encode($return_arr);
return json_encode($return_arr);
}
?>
I've made a star rating system, using PHP, and Jquery. After i have stored my votes in a database im trying to print the average rate. The problem is the average value that gets printed its for all the items that im rating, not just the specifik one that im rating
This is my jquery code:
function rate(id, vote) {
console.log(id, vote);
$.post("rated.php",
{ id: id, vote: vote }, function(data){
console.log(data);
$( ".totalrating") .html( data );
});
};
And this is my php:
$sql = "UPDATE images
SET votes = votes+1, tot_rating = tot_rating+$vote
WHERE id ='$id' ";
$result = mysqli_query($conn, $sql) or die("Fel vid SQL query");
$sql2 = "SELECT * from images WHERE id=$id";
$result1 = mysqli_query($conn, $sql2) or die ("Fel vid SQL query");
while($row = mysqli_fetch_array($result1)) {
$votes = $row['votes'];
}
$sql3 = "SELECT * from images WHERE id=$id";
$result2 = mysqli_query($conn, $sql3) or die ("Fel vid SQL query");
while($row = mysqli_fetch_array($result2)) {
$sum = $row['tot_rating'];
}
$avg = $sum / $votes;
$avg1decimals = number_format($avg, 1);
echo $avg1decimals;
} else {
}
Try a single select query:
$sql = "UPDATE images
SET votes = votes+1, tot_rating = tot_rating+$vote
WHERE id ='$id' ";
$result = mysqli_query($conn, $sql) or die("Fel vid SQL query");
$sql2 = "SELECT * from images WHERE id=$id";
$result1 = mysqli_query($conn, $sql2) or die ("Fel vid SQL query");
while($row = mysqli_fetch_array($result1)) {
$avg = $row['tot_rating'] / $row['votes'];
$avg1decimals = number_format($avg, 1);
echo $avg1decimals;
}
Try this one : Make sure ID is primary key in your table
$sql = "UPDATE images
SET votes = votes+1, tot_rating = tot_rating+".$vote."
WHERE id =".$id;
$result = mysqli_query($conn, $sql) or die("Fel vid SQL query");
$sql = "SELECT * from images WHERE id=".$id."Limit 1";
$result = mysqli_query($conn, $sql2) or die ("Fel vid SQL query");
while($row = mysqli_fetch_array($result)) {
$votes = $row['votes'];
$sum = $row['tot_rating'];
}
$avg = $sum / $votes;
$avg1decimals = number_format($avg, 1);
echo $avg1decimals;