Why cant I create/update new entrie in mySQL? - 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.).

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

Pull Random Data from mySQL

I am trying to pull a random question from one of my tables and display it in HTML. The point is to have the user put in their info in a form, answer the random question that appears, and submit the form that will store the users info along with the question they were asked and their answer. I can't seem to get the question to show up in my HTML and I'm not sure how to fix this. Still new to mySQL.
Code:
<?php
define('DB_NAME', 'db');
define('DB_USER', 'admin');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db', $link);
$db_selected = mysql_query("SELECT Question FROM QuestionDB ORDER BY RAND() LIMIT 1");
if (!$db_selected) {
die('Cant use ' . DB_NAME . ': ' . mysql_error());
}
if(isSet($_POST['submit'])) {
$fname = $row['f_name'];
$lname = $row['l_name'];
$email = $row['email'];
$question = $row['question'];
$answer = $row['answer'];
$sql = "INSERT INTO StudentDB VALUE ( NULL,'$fname','$lname','$email','$question','$answer')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
echo 'Thank you, your information has been sent';
}
else{
echo'
<!DOCTYPE HTML>
<html lang="en">
<head>
</head>
<body>
<form id = "myForm" method="POST">
<div class="col-sm-6" >
<h5><b>First Name: </b><br/><input type="text" name="f_name" size="70" required></h5> <br/>
<h5><b> Last Name: </b><br/><input type="text" name="l_name" size="70" required></h5> <br/>
</div>
<div class="col-sm-6" >
<h5><b>Email: </b><br/><input type="text" name="email" required></h5><br/>
</div>
<div class="col-sm-12" >
<br/><br/> Question: ' .$row["Question"]. '
</div>
<div class="col-sm-12" >
<br/><br/>
<h3><b>Answer:</b></h3>
<textarea maxlength="500" name="comment" id="comment"></textarea><br/>
</div>
<div class="col-sm-6" >
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>';
}
?>
On a side note running ORDER BY RAND() is not a good idea. It works to generate a random result, but it adds a lot of overhead which translates into long load times. If you start getting past 100 records you can see this really slow down MySQL queries and lead to long time to first byte wait times by the server. See here: http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/

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

Wordpress wpdb->query problems with importing data

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

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

I'm having a problem regarding Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING. I tried every solution in available online but still I got the same error over and over again.
So the problem is: Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in C:\wamp\www\RedCross\load.php on line 25
load.php
<?php
include_once('connect.php');
$EventNum = $_POST['ename'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT Price FROM events WHERE EventID = '".$EventNum."' ";
$result = mysql_query($query) or die('Fn another_php_file.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = "
<div class='control-group'>
<label class='control-label' for='price'>Price </label>
<div class='controls'>
";
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_array($result)) {
$r = $r . "<input type='text' name='price' id='price' class='input-xlarge' value = " . $row['Price'] . " readonly>";
}
$r = $r . "<center>
<button type='submit' class='btn btn-large btn- danger' name='submit' id='submit'>Join!</button>
</center>";
//The response echoed below will be inserted into the
echo $r;
} else {
$r = '<p>sorry there is no available staff for this</p>';
// $r = $r . '</select><input type="submit" name ="go" value="press me">';
$r = $r . '</div></div>';
//The response echoed below will be inserted into the
echo $r;
}
//Add this extra button for fun
?>
Line 25 is this code:
Even though I put spaces before it making this line not in line 25 still the error is in line 25.
Please help.
Change the code in line 25 to line below and test:
$r = $r . '<input type="text" name="price" id="price" class="input-xlarge" value = ' . $row["Price"] . ' readonly>';