I need to update a database using AJAX so don't have my page be reloaded. I can't find what's wrong and unexpectedly I get a success message back but a database doesn't get updated.
JS:
$('.start-time-class').submit(function() {
var startTime = "11:30";
var projectID = 17;
var userID = 2;
$.ajax({
url:'functions/starttime.php',
data:{startTime:startTime,projectID:projectID,userID:userID}, // pass data
dataType:'json',
success:function(){
// something
}
});
});
PHP:
$con = mysqli_connect('localhost','smt','smt','smt');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$startTime = $_GET['startTime'];
$projectID = $_GET['projectID'];
$userID = $_GET['userID'];
mysqli_select_db($con,"ajax_demo");
$sql = "INSERT INTO 'uc_project_time'('userID', 'projectID', 'startTime') VALUES (". $userID .", ". $projectID .", ". $startTime .")";
$result = mysqli_query($con,$sql);
mysqli_close($con);
Don't use quotes for table or column names
Use:
$sql = "INSERT INTO uc_project_time (userID, projectID, startTime) VALUES ('$userID', '$projectID', '$startTime')";
or
$sql = "INSERT INTO uc_project_time (userID, projectID, startTime) VALUES ('".$userID."', '".$projectID."', '".$startTime."')";
And do sanitize your code:
How can I prevent SQL injection in PHP?
You don't use quotes(single or double) in SQL for table or column names. You could use backticks(`), though not necessary(in your circumstance), it can be required in some situations.
When to use backticks(`)?
Firstly, you'd only use them in MySQL, as SQL Server and T-SQL use square brackets [] to denote identifiers.
If you were using spaces or keywords in your column or table names, you would need backticks. This would instruct the parser to parse the column or table name as a literal string.
To illustrate, if you had a table called 'badly named table'.
This wouldn't work
SELECT FROM badly named table...
This would work
SELECT FROM `badly named table`...
To conclude, backticks are useful if you have a bad table or column naming convention.
SQL Injections
Also, as #Fred -ii- said you're currently vulnerable to SQL Injections. If you're using PHP with PDO enabeled, you could use the following code (with prepared statements) protect against SQL injections and ensure that malicious actions can't be carried out on your database.
$con = new PDO('mysql:host=localhost; dbname= name_of_db', 'name_of_user', 'password_of_user');
$sql = $con->
prepare("
INSERT INTO uc_project_time userID, projectID, startTime VALUES (:userID, :projectID, :startTime)
");
$sql->bindParam(':userID', $userID,':projectID', $projectID,':startTime', $startTime, PDO::PARAM_STR);
$sql->execute();
$rows = $sql->fetchAll(PDO::FETCH_ASSOC);
Or, If you want to continue using MySQLi, you could use their version of prepared statements. That said, I recommend PDO for the reasons illustrated here.
Related
I'm trying to insert into a string all emails retrieved from the database, so I can use javascript to check if the email typed by the user into a form field is already registered. I'm trying to use json_encode().
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
$arrayEmails = mysqli_fetch_array($resultado);
foreach($arrayEmails as $row){
$emails[]=array($row['userEmail']);
}
echo json_encode($emails);
Now, I'm getting this error:
Warning: Illegal string offset 'userEmail' in /home/verificarEmail.php
on line 21
Line 21 is $emails[]=array($row['userEmail']);
What Am I doing wrong?
UPDATE:
I'm also trying:
$resultado = mysqli_query($conectar,$listarCorreos);
$emails = array();
while($row = mysql_fetch_assoc($resultado)) {
$emails[] = $row;
}
echo json_encode($emails);
And I get this error:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
object given in /home/verificarEmail.php on line 18
Line 18: while($row = mysql_fetch_assoc($resultado)) {
Use MYSQLI_ASSOC like below
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
while ( $row = mysqli_fetch_array($resultado, MYSQLI_ASSOC) ) {
$emails[]=array($row['userEmail']);
}
echo json_encode($emails);
There are a few problems there. To get your emails in an array do:
$resultado = mysqli_query($conectar,$listarCorreos);
if(!resultado) die($mysqli_error($conectar));//check for errors
$emails = mysqli_fetch_all($resultado);//fetch all results
echo json_encode($emails);
That should get your code working or show you the error. However, please don't do this.
so I can use javascript to check if the email typed by the user into a
form field is already registered
This is a terrible idea security wise because it will expose all your users' emails to people who are not even registered to your site. You should instead look up the desired username in the DB directly. If it's not there, then it hasn't been registered before. The Javascript side should only get a available or not available response.
The process (pseudo-code):
SELECT userEmail from usarios WHERE userEmail = ? ? is email to look for
execute query and capture $resultado
If $resultado is false, die(mysqli_error($conectar)) to show error
if mysqli_num_rows($resultado) === 0 email is available; else not available
Echo available or not available to Javascript
use the code like below
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
while ( $row = mysqli_fetch_array($resultado) ) {
$emails[]=$row['userEmail'];
}
echo json_encode($emails);
use the code like below
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
while ( $row = mysqli_fetch_array($resultado) ) {
$emails[]=$row['userEmail '];
}
echo json_encode($emails);
I am currently working on creating a Flot JavaScript Time Series Line Graph. The graph analyses the number of users who create an account with against the time that the account was created.
Here is a screenshot of the users table
I have so far been able to retrieve the created_date column in the users table x asis used for the graph. The y axis is then calculated using the COUNT() function in a separate query. My codes are found below.
PHP:
<?php
include "connection/connect2.php";
$datecreated = "SELECT created_date FROM users";
$rundatecreated = mysql_query($datecreated);
$foundnum = mysql_num_rows($rundatecreated);
while ($runrows = mysql_fetch_assoc($rundatecreated)) {
$dataset1[] = $runrows['created_date'];
}
if (is_array($dataset1)){
foreach($dataset1 as $x) {
$query = mysql_query("SELECT created_date, count(created_date) as date FROM users WHERE created_date='$x' ");
while ($runquery = mysql_fetch_assoc($query)){
$y[]= $runquery['created_date'] .",".$runquery['date']."<br>" ;
}
}
$graph=implode(" ", $y);
echo $graph;
} else {
echo "error";
}
?>
I then store the data retrieved using these two queries into an array, as shown below.
I am unsure of how to convert the date data currently retrieved using my PHP codes into JavaScript timestamp format. Is there any way I can do so using PHP codes?
1) You need only one SQL query to achieve this instead of one plus 1 per date. for this use grouping in the query.
2) To get timestamps from your dat values use the getTimestamp() method and multiply by 100 to convert from UNIX timestamps to JavaScript timestamps.
3) Flot need the data for a data series as array of array (data points). This can then be encoded as JSON and printed inside the JavaScript or fetched by AJAX.
Updated code (not tested but should be a good starting point):
<?php
include "connection/connect2.php";
$query = mysql_query("SELECT created_date, count(*) as date FROM users GROUP BY created_date ");
$foundnum = mysql_num_rows(mysql_query($query));
while ($runquery = mysql_fetch_assoc($query)){
$graph[] = array((new DateTime($runquery['created_date']))->getTimestamp() * 1000 , $runquery['date']);
}
if ($foundnum > 0) {
echo json_encode($graph);
} else {
echo "error";
}
?>
Below is the jQuery to passing the attr() value to $_GET[]. When I echo $_GET[] it displays the value. But not when I pass the $_GET into a MySQL statement.
$('.DetailsDisplay').click(function() {
var ix = $(this).attr('id');
$('#Details').load('details.php?regid='+ix);
});
details.php
mysql_select_db($database_host, $host);
$query_list_class = "SELECT * FROM xfi where no='".stid."'";
$list_class = mysql_query($query_list_class, $sshost) or die(mysql_error());
$row_list_class = mysql_fetch_assoc($list_class);
Any idea why?
You've got no $ sign in sql
$query_list_class = "SELECT * FROM xfi where no='".$stid."'";
PS: Also please parse $stid to int
$stid = (int) $_GET['regid'];
you forgot $ sign
also make sure to prevent sql injection
$stid = intval($_GET['regid']);
$query_list_class = "SELECT * FROM xfi where no='".$stid."'";
note : don't use mysql_* functions, they are deprecated, use PDO or mysqli instead
I have a PHP file that encodes Json data and when i view the JSON output when its a single data block i get a valid json code syntax this is an example :
single data block
But when the JSON results in a multiple data block it generates an invalid JSON format like this: multiple data blocks
This is my PHP code:
<?php
header('Content-Type: application/json; charset=utf-8', true,200);
DEFINE('DATABASE_USER', 'xxxxx');
DEFINE('DATABASE_PASSWORD', 'xxxxxx');
DEFINE('DATABASE_HOST', 'xxxxxxxxxxx');
DEFINE('DATABASE_NAME', 'xxxxxxxx');
// Make the connection:
$dbc = #mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
DATABASE_NAME);
$dbc->set_charset("utf8");
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword = trim($_GET['keyword']) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
$query = "select name,franco,alpha,id,url,songkey,chord from song where name like '%$keyword%' or franco like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .
$result = mysqli_query($dbc,$query);//Run the Query
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$data = array();
$data = $row;
echo $_GET[$callback]. ''.json_encode($data).'';
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
}
}
}else {
echo 'Parameter Missing in the URL';//If URL is invalid
}
?>
It is because you are JSON-encoding a single line of the result set at at time. This is not a valid JSON structure if the calling client is expecting such.
Likely, you will want to put each row as an entry in an array, and then JSON-encode and echo the resulting array.
Like this:
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
$array = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$array[] = $row;
}
echo json_encode($array);
}
}
This is the problem I get, for example, when an user inputs <script>top.location.href=’http://www.google.nl’;</script>
I want my application to echo it as plain text. Now, this actually works with
htmlspecialchars()
This example works for me:
$test = "<script>top.location.href=’http://www.google.nl’;</script>";
echo htmlspecialchars($test);
But, when the user submits the form, the data goes to my DB and then returns to a 'dashboard'.
The value is now ''.
Is there a way how I can save the data safe into my DB?
I add the values into the DB for my C# application in this way via SDK:
$onderwerp = htmlspecialchars(stripslashes(trim($_POST['onderwerp'])), ENT_QUOTES,'UTF-8',true);
$omschrijving = htmlspecialchars(stripslashes(trim($_POST['omschrijving'])), ENT_QUOTES,'UTF-8',true);
$im = array('description' => mysql_real_escape_string($onderwerp),
'message' => mysql_real_escape_string($omschrijving) ,
'relation' => $_SESSION['username'],
'messageType' => 70,
'documentName' => $_FILES["file"]["name"],
'documentData' => base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
$imresponse = $wcfclient->CreateInboundMessage($im);
echo $imresponse->CreateInboundMessageResult;
And then call them at my dashboard in this way:
$roc = array('relation' => $_SESSION['username']);
$rocresponse = $wcfclient->ReadOpenCalls($roc);
foreach ($rocresponse->ReadOpenCallsResult as $key => $calls){
echo $calls->Description;
}
can you please check mysql-real-escape-string
mysql_real_escape_string() :
The mysql_real_escape_string() function escapes special characters in a string for use in an SQL statement
Also CHeck SQL Inject :SQL Injection
Example
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?>
Ouput :
Escaped string: Zak\'s and Derick\'s Laptop
Yes, read about mysqli_real_escape_string.