I'm adding new data to database table with jQuery. Then i'm getting all content from that table. Problem is i'm getting wrong array size every odd time.If i refresh the page it's getting right array size but when i'm clicking button with jQuery function it's all messed up.
I figure out that
$n = mysqli_num_rows($result);
already return wrong num of rows
Here is the script:
$(document).ready(function(){
$.getallentries = function(){
$.getJSON("entries.php",{action : "getall"},function(data) {
var content_array = $.map(data, function(e) { return e;});
console.log(content_array.length); // to check array size
});
$.addstatic = function(){
$.post("entries.php",{action : "addstatic"});
};
};
$("#adds").on("click",function(){
$.addstatic();
$.getallentries();
});
$.getallentries();
And here is entries.php:
function getall(){
$link = db_connect();
$query= "SELECT * FROM jq";
$result = mysqli_query($link,$query, MYSQLI_STORE_RESULT);// Smart people said MYSQLI_STORE_RESULT should help but it didn't
$n = mysqli_num_rows($result);
for($i = 0 ;$i<$n;$i++)
{
$row=mysqli_fetch_assoc($result);
$b[]=$row;
}
echo json_encode(array($b));
}
function addstatic(){
$link = db_connect();
$statin_Entry = "Static Entry";
$query = "INSERT INTO jq (Entry) VALUES ('$statin_Entry')";
$result = mysqli_query($link,$query);
}
if(isset($_GET['action']) && !empty($_GET['action'])) {
$action = $_GET['action'];
switch($action) {
case 'getall' : getall(); break;
}
}
else {
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'addstatic' : addstatic();break;
case 'removelast' : removelast();break;
// ...etc...
}
}
}
This is log of array length
So the problem again, same array size 143,146,151 and where is 156??
You should call $.getallentries in the callback function of the $.addstatic AJAX call, so that it runs after $.addstatic has finished updating the database.
$.addstatic = function(){
$.post("entries.php",{action : "addstatic"}, $.getallentries);
};
There's no need to use mysqli_num_rows before fetching the rows. You should use a loop like this:
while ($row = mysqli_fetch_assoc($result)) {
$b[] = $row;
}
Also, you're wrapping your array in another array. Just do:
echo json_encode($b);
The way you've written it, console.log(content_array.length) should always log 1, I don't understand how you're getting higher numbers. Are you sure you posted the actual code?
There's no point in use $.map, all it's doing is making a copy of the data array. Just use data itself.
And in your PHP, you don't need to test both isset() and !empty(), because empty() checks if the variable is set first.
You don't need to use MYSQLI_STORE_RESULT, it's the default for that option.
Related
While writing a pdo statement, is it possible to repeat the value of a variable? I mean:
$query = "UPDATE users SET firstname = :name WHERE firstname = :name";
$stmt = $dbh -> prepare($query);
$stmt -> execute(array(":name" => "Jackie"));
Please note that I repeat the ":name" nameholder whereas I provide the value only once. How can I make this work?
The simple answer is: You can't. PDO uses an abstraction for prepared statements which has some limitations. Unfortunately this is one, you have to work-around using something like
$query = "UPDATE users SET firstname = :name1 WHERE firstname = :name2";
$stmt = $dbh -> prepare($query);
$stmt -> execute(array(":name1" => "Jackie", ":name2" => "Jackie"));
In certain cases, such as emulated prepared statements with some versions of the PDO/MySQL driver, repeated named parameters are supported; however, this shouldn't be relied upon, as it's brittle (it can make upgrades require more work, for example).
If you want to support multiple appearances of a named parameter, you can always extend PDO and PDOStatement (by classical inheritance or by composition), or just PDOStatement and set your class as the statement class by setting the PDO::ATTR_STATEMENT_CLASS attribute. The extended PDOStatement (or PDO::prepare) could extract the named parameters, look for repeats and automatically generate replacements. It would also record these duplicates. The bind and execute methods, when passed a named parameter, would test whether the parameter is repeated and bind the value to each replacement parameter.
Note: the following example is untested and likely has bugs (some related to statement parsing are noted in code comments).
class PDO_multiNamed extends PDO {
function prepare($stmt) {
$params = array_count_values($this->_extractNamedParams());
# get just named parameters that are repeated
$repeated = array_filter($params, function ($count) { return $count > 1; });
# start suffixes at 0
$suffixes = array_map(function ($x) {return 0;}, $repeated);
/* Replace repeated named parameters. Doesn't properly parse statement,
* so may replacement portions of the string that it shouldn't. Proper
* implementation left as an exercise for the reader.
*
* $param only contains identifier characters, so no need to escape it
*/
$stmt = preg_replace_callback(
'/(?:' . implode('|', array_keys($repeated)) . ')(?=\W)/',
function ($matches) use (&$suffixes) {
return $matches[0] . '_' . $suffixes[$matches[0]]++;
}, $stmt);
$this->prepare($stmt,
array(
PDO::ATTR_STATEMENT_CLASS => array('PDOStatement_multiNamed', array($repeated)))
);
}
protected function _extractNamedParams() {
/* Not actually sufficient to parse named parameters, but it's a start.
* Proper implementation left as an exercise.
*/
preg_match_all('/:\w+/', $stmt, $params);
return $params[0];
}
}
class PDOStatement_multiNamed extends PDOStatement {
protected $_namedRepeats;
function __construct($repeated) {
# PDOStatement::__construct doesn't like to be called.
//parent::__construct();
$this->_namedRepeats = $repeated;
}
/* 0 may not be an appropriate default for $length, but an examination of
* ext/pdo/pdo_stmt.c suggests it should work. Alternatively, leave off the
* last two arguments and rely on PHP's implicit variadic function feature.
*/
function bindParam($param, &$var, $data_type=PDO::PARAM_STR, $length=0, $driver_options=array()) {
return $this->_bind(__FUNCTION__, $param, func_get_args());
}
function bindValue($param, $var, $data_type=PDO::PARAM_STR) {
return $this->_bind(__FUNCTION__, $param, func_get_args());
}
function execute($input_parameters=NULL) {
if ($input_parameters) {
$params = array();
# could be replaced by array_map_concat, if it existed
foreach ($input_parameters as $name => $val) {
if (isset($this->_namedRepeats[$param])) {
for ($i=0; $i < $this->_namedRepeats[$param], ++$i) {
$params["{$name}_{$i}"] = $val;
}
} else {
$params[$name] = $val;
}
}
return parent::execute($params);
} else {
return parent::execute();
}
}
protected function _bind($method, $param, $args) {
if (isset($this->_namedRepeats[$param])) {
$result = TRUE;
for ($i=0; $i < $this->_namedRepeats[$param], ++$i) {
$args[0] = "{$param}_{$i}";
# should this return early if the call fails?
$result &= call_user_func_array("parent::$method", $args);
}
return $result;
} else {
return call_user_func_array("parent::$method", $args);
}
}
}
In my case this error appeared when I switched from dblib freedts to sqlsrv PDO driver. Dblib driver handled duplicate parameters names with no errors. I have quite complicated dynamic queries with lots of unions and a lot of duplicated params so I used following helper as a workaround:
function prepareMsSqlQueryParams($query, $params): array
{
$paramsCount = [];
$newParams = [];
$pattern = '/(:' . implode('|:', array_keys($params)) . ')/';
$query = preg_replace_callback($pattern, function ($matches) use ($params, &$newParams, &$paramsCount) {
$key = ltrim($matches[0], ':');
if (isset($paramsCount[$key])) {
$paramsCount[$key]++;
$newParams[$key . $paramsCount[$key]] = $params[$key];
return $matches[0] . $paramsCount[$key];
} else {
$newParams[$key] = $params[$key];
$paramsCount[$key] = 0;
return $matches[0];
}
}, $query);
return [$query, $newParams];
}
Then you can use it this way:
$query = "UPDATE users SET firstname = :name WHERE firstname = :name";
$params = [":name" => "Jackie"];
// It will return "UPDATE users SET firstname = :name WHERE firstname = :name1"; with appropriate parameters array
list($query, $params) = prepareMsSqlQueryParams($query, $params);
$stmt = $dbh->prepare($query);
$stmt->execute(params);
Good Afternoon,
I am currently in the process of creating a website using HTML, PHP and JavaScript, and I have run into an issue when trying to check for duplicate usernames in a database. Currently, I have a form which uses the following code to call two javascript functions on submit.
<form onsubmit="return (checkValid() && usernameCheck())" action="create.php" method="post" id="registerForm">
The javascript code is then present at the bottom of the body tag, within script tags, and is the following.
<script>
var pass = document.getElementById('passVal').value;
var confPass = document.getElementById('confPassVal').value;
var error = document.getElementById('errorMsg');
var result = true;
function checkValid(){
if(pass !== confPass)
{
error.type = "text";
error.value = "Passwords do not match!";
error.style.backgroundColor = "#E34234";
document.getElementById('passVal').style.borderColor = "#E34234";
document.getElementById('confPassVal').style.borderColor = "#E34234";
result = false;
}
return result;
}
function usernameCheck()
{
var username = document.getElementById('userName').value;
var j = checkName(username);
console.log(j);
if ( j == "taken" ) {
error.type = "text";
error.value = "Username Already Exists, Please choose an alternative.";
error.style.backgroundColor = "#E34234";
document.getElementById('userName').style.borderColor = "#E34234";
console.log(j);
result = false;
}
if ( j == "available" ) {
console.log(j);
result = true;
}
return result;
}
function checkName(uname) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var httpURL = "checkUserName.php?n=" + uname;
xhttp.open("GET",httpURL,false);
xhttp.send();
return xhttp.responseText;
}
</script>
The issue I am having is that the second JavaScript function is not executing, even though it is being called in the onsubmit function. Because of this, the third function is also not executing, as this function is called within the second function. The second function submits a GET value with the username input in the HTML form to a PHP script. The PHP script then checks the database to see if this user exists, and returns a value based on if this is true or not. The code below shows the PHP script.
<?php
session_start();
require 'sql.php';
header('Content-type: text/plain');
$userName = $_GET['n'];
$query = "SELECT username FROM users where username='$username'";
$checkun = $conn->query($query);
while ($row = $checkun->fetch_assoc()) {
if ($row > 0)
{
exit('taken');
} else
{
exit('available');
}
}
?>
The first JavaScript function successfully executes, which is used to check if the password fields match. This function either returns a false value if the password fields do not match (hence the second function will not execute), or a true value if they do. Even if the first function returns true, the next function does not execute, and the form submits without running this second function.
I would be grateful if someone more experienced than me (I have only been practising web development for a few months) could highlight if there are any errors in my method, and possibly help me with a solution.
Thank you for taking the time to read this!
When you say "the second function does not run" - do you mean that you get no response in the JS? I would imagine that to be true as you will NEVER have a match in your MySQL query - and, you don't have your 'catchall' in the right place.
This looks like a first learning experience for you to get data from a database, so I won't harp on the fact that you are WIDE OPEN for SQL injection attacks, though I will say that you must NOT use this code on any open system where there are real users (you need to learn how to protect against those attacks - there's loads of data on that on SO)!
So, your first step in at least getting the 'second function' to 'work'.....
<?php
session_start();
require 'sql.php';
header('Content-type: text/plain');
// $userName = $_GET['n']; // <<<==== here you use with a capital
$username = $_GET['n']; // let's change it to be the same
$query = "SELECT username FROM users where username='$username'"; // now, we have a chance...
$checkun = $conn->query($query);
while ($row = $checkun->fetch_assoc()) {
if ($row > 0)
{
exit('taken');
}
}
// Here is where to put your 'catchall' in case you don't get anything from the query (what you have won't ever give 'available')
exit('available');
?>
I'm facing some output trouble at the second part of my codes.
function getSiteContent($url)
{
$html = cache()->rememberForever($url, function () use ($url) {
return file_get_contents($url);
});
$parser = new \DOMDocument();
#$parser->loadHTML($html);
return $parser;
}
libxml_use_internal_errors(true);
$url = 'https://sumai.tokyu-land.co.jp/osaka';
$parser = getSiteContent($url);
$allDivs =[];
$allDivs = $parser->getElementsByTagName('div');
foreach ($allDivs as $div) {
if ($div->getAttribute('class') == 'p-articlelist-content-right') {
$allLinks = $div->getElementsByTagName('a');
foreach ($allLinks as $a) {
$getlinks[] = $a->getAttribute('href');
}
}
}
var_dump($getlinks);
At this var_dump I can see links that I scraped. No problem 'till here. And one more time. I want to go into those links. That's why I wrote the codes right below.
getSiteContent($getlinks);
$link = [];
$siteler = [];
foreach ($siteler as $site) {
if($site == 'https://sumai.tokyu-land.co.jp'){
$site = $getlinks->getElementsByTagName('div');
foreach ($site as $links) {
if($links->getAttribute('class') == 'pc_hnavi'){
$linker = $links->getElementsByTagName('a');
foreach ($linker as $a) {
$link = $a->getAttribute('href');
}
}
}
}
}
var_dump($link);
When I var_dump it. It says Array 0
I didn't understand why it doesn't go in those links with foreach
My codes are wrong? What am I missing here? Any idea for this?
Thank you helping me out.
As I said in the comments $siteler is empty when you try to loop through it, but there are a couple more problems:
First your code will only trigger once at most, when the link is exactly 'https://sumai.tokyu-land.co.jp' and I'm not sure that's what you want.
You are calling DOM functions on an array.
Only seem to care about links inside 'div' tags.
You redefine the $link variable on each loop, so the final result will be just one link.
This is the fixed code:
$link = [];
foreach ($getlinks as $site) {
// Any link in the domain, not just the homepage
if(strpos($site, 'https://sumai.tokyu-land.co.jp') === 0) {
$dom = getSiteContent($site);
$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
// Can have more than one class
$attrs = explode(' ', $div->getAttribute('class'));
if(in_array('pc_hnavi', $attrs)) {
$linker = $div->getElementsByTagName('a');
foreach ($linker as $a) {
// Add to the array
$link[] = $a->getAttribute('href');
}
}
}
}
}
However this doesn't check if the link already exists in the array and has the potential to process the same links over and over. I'd strongly suggest to use an existing crawler.
From the comments, turns out that pc_hnavi is an id and not a class and you are interested in the first link only. You can access that element directly without iterating the elements:
foreach ($getlinks as $site) {
// Any link in the domain, not just the homepage
if(strpos($site, 'https://sumai.tokyu-land.co.jp') === 0) {
$dom = getSiteContent($site);
$div = $dom->getElementById('pc_hnavi');
if ($div != null) {
$links = $div->getElementsByTagName('a');
if ($links->length > 0) {
$a = $links->item(0);
$link[] = $a->getAttribute('href');
}
}
}
}
It looks like your problem is here:
...
$siteler = []; // $siteler is set to an empty array ...
foreach ($siteler as $site) { // then you loop through the empty array which does nothing ...
...
}
...
Fixing that should get you started.
Now there are plenty of people with the same issue and their resolutions have not worked.
Problem
I have a list of Times coming back from a REST call. They are created exactly as they should, except I want them to be stored into a JavaScript Array.
PHP
function getOpenAppts()
{
global $wpdb;
$final_array = "";
$td = date('m/d/Y');
$datetime = new DateTime('tomorrow');
$tm = $datetime->format('Y-m-d');
$startDate = $td;
$endDate = $tm;
$apptTypeID = "23";
$get_loc = $wpdb->get_results('SELECT provid,id FROM location');
foreach($get_loc as $val){
// call to Athena to get open appointments
$res = getOpenAppointments($val->id, $val->provid, $startDate, $endDate, $apptTypeID);
//print_r($res);
// if we got some appointments back strip any that started before now
if (array_key_exists('totalcount', $res) && $res['appointments'] > 0)
{
$tzStr = "America/Los_Angeles";
$tzObject = new DateTimeZone($tzStr);
$nowDT = new DateTime();
$nowDT->setTimezone($tzObject);
//print_r($nowDT);
//print_r("\n");
$appts = array();
for ($i = 0; $i < count($res['appointments']); $i++)
{
$apptDT = new DateTime($res['appointments'][$i]['date']." ".$res['appointments'][$i]['starttime'], $tzObject);
//print_r($apptDT);
//print_r("\n");
if ($nowDT < $apptDT)
$appts[] = $res['appointments'][$i];
}
}
if (count($appts) > 0)
foreach($appts as $data) {
$final_array[] = $data;
}
else
$res; // something went wrong. return error message
}
echo json_encode($final_array);
}
Header.php
<script>
var times = <?php getOpenAppts(); ?>;
console.log(times); //Will display properly
</script>
That is exactly how it should come back!
But.. When I run a console on the variable times (which is in the header making it a global variable. I get this.
It should give me the exact same list that the console.log gave me.
What I Have tried
I ran:
PARSE.json(times);
No effect...
I did in PHP:
json_encode(json_decode($appts),true);
No effect...
What part of this process is incorrect?
You are using time as a global variable.
Since the console.log right after the declaration prints everything fine, you are probably overriding its value somewhere after.
Avoid the most you can global variables, they're evil :)
I dont know where my mistake is but i want to store an oracle query inside a function and return that function inside an array.
JobDrop.php
class JobDrop {
private $jobSql = "SELECT VMI.PROJECT_NO JOB FROM VW_MTO_INFO VMI ORDER BY VMI.PROJECT_NO ASC";
function _construct($jobSql){
$this->jobSql = $jobSql;
}
function JobDropdown($conn){
$jobParse = oci_parse($conn, $this->jobSql);
$jobExcErr = oci_execute($jobParse);
if (!$jobExcErr){
$e = oci_error($jobParse);
print htmlentities($e['message']);
print "\n<pre>\n";
print htmlentities($e['sqltext']);
printf("\n%".($e['offset']+1)."s", "^");
print "\n</pre>\n";
} else {
$res = array();
while ($row = oci_fetch_assoc($jobParse)){
$res[] = $row;
}
$listVendor = json_encode($res, JSON_PRETTY_PRINT);
return $listVendor;
}
}
}
and in test.php
include './job_drop.php';
require_once('../../lib/dbinfo.inc.php');
$conn = oci_connect(ORA_CON_UN, ORA_CON_PW, ORA_CON_DB);
$jobdrop = new JobDrop();
$jobdrop->JobDropdown($conn);
var_dump($jobdrop);
but it doesnt show the array inside the browser. it shows the query string instead,
object(JobDrop)#1 (1) { ["jobSql":"JobDrop":private]=> string(74) "SELECT VMI.PROJECT_NO JOB FROM VW_MTO_INFO VMI ORDER BY VMI.PROJECT_NO ASC" }
Please help me where I am doing wrong here
If you want to see the array, do:
$res = $jobdrop->JobDropdown($conn);
var_dump($res);