Wordpress wpdb->query problems with importing data - mysql

My line of code below is supposed to update a NULL value field with (in this case) a pre-defined value. When i execute my wpdb query however the page gives a 500 error.
$wpdb->query( $wpdb->query( "UPDATE ziekbeter SET healthy= '1994-06-04' WHERE person = 5 AND sick IS NOT NULL AND healthy IS NULL") );
Can someone take a look at the line of code and possibly tell me whats wrong?
The code is being executed on a button click.
A screenshot of my wp table is added.
Person ID and the healthy date are going to be dynamic but for now im keeping it static.
profile.php
<?php
$user_ID = get_current_user_id();
echo $user_ID;
global $wpdb;
if ($wpdb->get_results( "SELECT * FROM ziekbeter WHERE person = $user_ID AND healthy IS NULL"))
{
$row = $wpdb->get_results( "SELECT * FROM ziekbeter WHERE person = $user_ID AND healthy IS NULL");
{
?>
<form action="<?php bloginfo('url'); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitBeter" value="Meld mij beter!">
</form>
<?php
}
}
elseif ($wpdb->get_results("SELECT healthy FROM ziekbeter WHERE person = $user_ID AND healthy IS NOT NULL"))
{
$row = $wpdb->get_results( "SELECT * FROM ziekbeter WHERE person = $user_ID AND healthy IS NOT NULL");
{
?>
<form action="<?php bloginfo('url'); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitZiek" value="Meld mij ziek!">
</form>
<?php
}
}
else {
?>
<form action="<?php bloginfo('url'); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitZiek" value="Meld mij ziek!">
</form>
<?php
}
?>
ziekbeter.php
if(isset($_POST['submitZiek']))
{
/* This function will come after i got the submitBeter working */
}
elseif(isset($_POST['submitBeter']))
{
$wpdb->query( $wpdb->query( "UPDATE ziekbeter SET healthy= '1994-06-04' WHERE person = 5 AND sick IS NOT NULL AND healthy IS NULL") );
echo "submitBeter wordt uitgevoerd";
}
Should i replace the wpdb-> query with an echo the code will execute properly and run the echo without any problems.

Try reworking the logic, something like:
profile.php
<?php
global $wpdb;
$user_ID = get_current_user_id();
echo $user_ID;
//First DB query
$row1 = $wpdb->get_results("SELECT * FROM ziekbeter WHERE person = $user_ID AND healthy IS NULL");
//Second DB query
$row2 = $wpdb->get_results("SELECT healthy FROM ziekbeter WHERE person = $user_ID AND healthy IS NOT NULL");
// I.e. greater than zero draw the HTML form
if (count($row1)>0) {
?>
<form action="<?php esc_url(bloginfo('url')); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitBeter" value="Meld mij beter!">
</form>
<?php
}
// Second DB query draw different HTML form
if (count($row2)>0) {
?>
<form action="<?php esc_url(bloginfo('url')); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitZiek" value="Meld mij ziek!">
</form>
<?php
}
// Draw third HTML form otherwise
if (!$row1 || !$row2) {
?>
<form action="<?php esc_url(bloginfo('url')); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitZiek" value="Meld mij ziek!">
</form>
<?php
}
?>
Now, the other file, do not forget to globalize the $wpdb variable:
ziekbeter.php (EDITED):
<?php
global $wpdb;
if(isset($_POST['submitZiek'])) {
/* This function will come after i got the submitBeter working */
}
if(isset($_POST['submitBeter'])) {
$result = $wpdb->query( "UPDATE ziekbeter SET healthy= '1994-06-04' WHERE person = 5 AND sick IS NOT NULL AND healthy IS NULL");
/*Or, use the native WordPress function:
$result = $wpdb->update( $table, $data, $where, $format = null, $where_format = null ); */
if ($result) echo "submitBeter wordt uitgevoerd";
}
?>

If you're trying to access those files directly, i.e. http://example.com/wp-content/themes/stk/profile.php and http://example.com/wp-content/themes/stk/ziekbeter.php, then you need to include WordPress:
<?php
require_once '../../../wp-load.php';
// rest of profile.php
<?php
require_once '../../../wp-load.php';
// rest of ziekbeter.php

Related

Query works when form action is to same page, not when it redirects to another

I have query that gets data from a form, when the submit button is pressed the data should be stored in a database. When the form's action is action="#" the data is inputted into the database. But when the action is action="otherPage.php" the data is not inserted into the database. Any help ?
Side Note: I know the queries need to be changed to counter SQL injection this is just for testing
Code:
if(isset($_POST['submit']))
{
$name = $_POST['fullName'];
$idNumber = $_POST['idNo'];
$cardNo = $_POST['cardNo'];
$_SESSION['fullName'] = $name;
$_SESSION['id'] = $idNumber;
$checkExists = "SELECT * FROM system.table WHERE idNumber = '$idNumber' ";
$resExists = mysqli_query($connection,$checkExists)
or die("Error in query: ". mysqli_error($connection));
if(mysqli_fetch_assoc($resExists) > 0)
{
$updateCard = "UPDATE system.table SET cardNo = '$cardNo' WHERE idNumber=$idNumber";
$resUpdate= mysqli_query($connection,$updateCard)
or die("Error in query: ". mysqli_error($connection));
}
if(mysqli_fetch_assoc($resExists) < 1)
{
$company = $_POST['company'];
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim(preg_replace('#'.$last_name.'#', '', $name));
$insert = "INSERT INTO system.table (idNumber,name,surname,company,cardNo) VALUES
('$idNumber','$first_name','$last_name','$company','$cardNo')";
$resInsert = mysqli_query($connection,$insert)
or die("Error in query: ". mysqli_error($connection));
}
$connection->close();
}
I do not know if this is the corrext way to go around it, but it works. I included ob_start(); at the beginning of my code, left the action as
<form role="form" method="POST" action="#">
Then included
header('Location:otherPage.php');
so that the page automatically redirects to otherPage.php
If you have two files in the same folder, it should be working:
myFolder
- testForm.php
- testUpload.php
testForm.php:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="testUpload.php">
<fieldset>
<legend>Form</legend>
<label>Name: </label>
<input type="text" name="name">
<input type="submit">
</fieldset>
</form>
</body>
</html>
testUpload.php:
<?php
print($_POST['name']);
exit;
Do you have any Redirection Statements in the config of your Web Server (e.g. Apache httpd.conf)?

How to get data from data table using php

i am learning php nad html and mssql
Hello i dont know anything wrong can someone explain me?
+(everything configured righ in db i guess)
<?php
include('Database\DBconnect.php');
?><?php
$procs = "{call p_bas_sel_DataTest()}";
$paramss = array();
while($getquestionsfromphp=sqlsrv_fetch_object($results)){ ?>
Now HTML
<label class="questlabel">1.blah blah?</label>
<div class="answers" id="ans1" style="margin-left: 2em">
<button ><label ><span ><?php echo $getquestionsfromphp['D_Value'];?></span></label></button>
</div><?php } ?>
<?php
$sql = "SELECT * FROM Data_Test WHERE lang='M'" ;
$query = sqlsrv_query ($conn,$sql);
$arr = array();
while ($row = sqlsrv_fetch_array($query)){
$array[] = $row;
}
?>
I fixed my error coding like this i put data into array from database then used on some text as index numbers

Why cant I create/update new entrie in mySQL?

Ive been trying all day to create a new entry in my table. Sorry for all the text in spanish. I hope it is not a problem.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$nueva_tienda = $_POST['nueva_tienda'];
if(!empty($nueva_tienda)){
echo "not empty";
include('connection.php');
mysqli_query($dbc, "INSERT INTO tiendas (nombre) VALUES ('$nueva_tienda')");
}
else{
echo "Porfavor llena todos los campos";
}
}
else{
echo "No form has been submitted";
}
?>
<h1>Nueva tienda</h1>
<form action="processing2.php" method="post">
<p>Nombre de la nueva tienda: <input type="text" name="nueva_tienda" maxlength="50"/></p>
<p><input type="submit" name="submit" value="Submit"/></p>
</form>
EDIT:
Added connection include file from comments:
<?php $hostname = "localhost";
$username = "root";
$password1 = "";
$dbname = "inventario_collares"; //making the connection to mysql
$dbc = mysqli_connect($hostname, $username, $password1, $dbname) OR die("could not connect to database, ERROR: ".mysqli_connect_error());
//set encoding
mysqli_set_charset($dbc, "utf8");
?>
Create an object of your connection class.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$nueva_tienda = $_POST['nueva_tienda'];
if(!empty($nueva_tienda)){
echo "not empty";
include('connection.php');
//create an object for your connection class
$dbc=new connection();
mysqli_query($dbc, "INSERT INTO tiendas (nombre) VALUES ('$nueva_tienda')");
}else{
echo "Porfavor llena todos los campos";
}
}else{
echo "No form has been submitted";
}
?>
<h1>Nueva tienda</h1>
<form action="processing2.php" method="post">
<p>Nombre de la nueva tienda: <input type="text" name="nueva_tienda" maxlength="50"/></p>
<p><input type="submit" name="submit" value="Submit"/></p>
</form>
1) Turn on PHP error outputting at the top of your script:
ini_set('display_errors', 1);
error_reporting(E_ALL);
2) set this line:
mysqli_query($dbc, "INSERT INTO tiendas (nombre)
VALUES ('$nueva_tienda')")
or die("Error MySQL Line ".__LINE__." :".mysqli_Error($dbc));
This will output any problems if the MySQL insert query fails.
If you do both of these things and still get no error, then the problem is elsewhere (such as is your file called processing2.php? etc.).

Populating Drop Down List from Previous Drop Down - using AJAX, PDO, jQuery

I'm brand new to using PHP and mySQL so I'm fully aware I've probably made some very 'noob' errors. However, I'm really stuck when it comes to populating my second drop down list from mySQL, when an option has been selected from a previous drop down list.
I've tried all the forums and have tried example scripts, but each time, I continue to get errors despite trying different examples on the internet. Thus hoping why I wish someone could help me out.
I'm trying to build a small film website, whereby someone can select a film, and then select a date & time and etc. I'm using mySQL to populate the drop down lists but get stuck when I want to populate the second dropdown, with it being dependent on the first option select.
I've tried using AJAX but to no avail. Appreciate I'm probably made some very rookie errors here (possible confusion around variables) but if someone could shed some light on where I'm wrong, I would be really grateful.
You have small mistake on getDates.php
<?php
require("Connect.php");
$name = (!empty($_REQUEST["name"])) ? trim($_REQUEST["name"]) : "");
if (!empty($name)) {
$sql = "SELECT Dates FROM Cinema WHERE name = $name";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue("tn", trim($name));
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo($ex->getMessage());
}
if (count($results) > 0) {
?>
<label>Dates:
<select name="Dates">
<?php foreach ($results as $rs) { ?>
<option value="<?php echo $rs["Dates"]; ?></option>
<?php } ?>
</select>
</label>
<?php
}
}
?>
Try it please and feedback
index.php
<?php
require Connect.php;
?>
<!DOCTYPE html>
<html>
<head>
<title>Films for Family!!</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function Datesforfilms(sel) {
var name = sel.options[sel.selectedIndex].value;
$("#output1").html("");
$.ajax({
type: "POST",
url: "getDates.php",
data: "name=" + name,
cache: false,
success: function(html) {
$("#output1").html(html);;
}
});
}
</script>
</head>
<body>
<div class="welcome">
<h1>Films for Family</h1>
</div>
<div class="SelectFilm">
<h3> Step 1: </h3>
<p> *Select a film*</p>
<form name="Filmform" method="get">
<select name="Select a Film" onChange="Datesforfilms(this);">
<option value="0">Select a Film</option>
<?php
$sql = "SELECT name FROM company";
$handle = $conn->prepare($sql);
$handle->execute(array($sql));
$res = $handle->fetchAll();
foreach($res as $movie) { ?>
<option value="<?=$movie['name']?>"><?=$movie['name']?></option>
<?php } ?>
</select>
<div id="output1"></div>
</form>
</div>
</body>
</html>
getDates.php
<?php
require("Connect.php");
$name = (!empty($_POST["name"]) ? trim($_POST["name"]) : "");
if (!empty($name)) {
$sql = "SELECT Dates FROM Cinema WHERE name = $name";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue("tn", trim($name));
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo($ex->getMessage());
}
if (count($results) > 0) {
?>
<label>Dates:
<select name="Dates">
<?php foreach ($results as $rs) { ?>
<option value="<?php echo $rs["Dates"]; ?>"><?php echo $rs["Dates"]; ?></option>
<?php } ?>
</select>
</label>
<? } ?>
<? } ?>

Cannot submit form with the enter key

I hate to submit this question but I have been unable to find a solution for almost a week now.
<div class="scanform">
<form action="scanform.php" method="post" id="scanform">
<p> <label for="Order Number">Order Number:</label>
<input name="OrderNumber" id="OrderNumber" autofocus="" type="text"><span class="error">*<?php echo $ONErr;?>
</span></p>
<input name="submit" value="Submit" type="submit"></form>
</div>
The form works well when I click on the submit button but if I type in the text field and hit enter, the form just reloads.
I cannot figure out what I am doing wrong.
The PHP code:
<?php date_default_timezone_set('America/Toronto');
$ONErr = "";
if (isset($_POST['submit']))
{
$link = mysqli_connect("localhost", "username", "password", "ordertracking");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
if (empty($_POST['OrderNumber'])) {
$ONErr = "OrderNumber is required";
} else {
$OrderNumber = mysqli_real_escape_string($link, $_POST['OrderNumber']);
// Attempt insert query execution
$query = "SELECT * FROM Orders WHERE OrderNumber LIKE '%$OrderNumber' ORDER BY TimeStamp DESC LIMIT 1";
$result = mysqli_query($link, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);
}
// Close connection
mysqli_close($link);
}
?>