<script>
function testinput(value) {
value = trim(value);
value = stripslashes(value);
value = htmlspecialchars(value);
}
</script>
<?php
$servername ="localhost";
$username = "k";
$password = "password";
$dbname = "password";
$connect1 = new mysqli($servername, $username, $password, $dbname);
if($connect1->connect_error) {
die("Connection failed: " . $connnect1->connect_error);
}
if (isset($_POST['btnreg'])) {
$klantVoornaam = $_POST["txtVoornaam"];
$klantAchternaam = $_POST["txtAchternaam"];
$klantMail = $_POST["txtEmail"];
$klantWachtwoord = $_POST["txtWw"];
(line48)$klantVoornaam = testinput($klantVoornaam);
$klantAchternaam = testinput($klantAchternaam);
$klantMail = testinput($klantMail);
$klantWachtwoord = testinput($klantWachtwoord);
$sql = "INSERT INTO `klanten` (KlantID, Voornaam, Achternaam, Wachtwoord, Email, Klantreg, KlantActief)
VALUES(NULL,'".$klantVoornaam."','".$klantAchternaam."', '".md5($klantWachtwoord)."','".$klantMail."',". regCode() ."','0')";
$qresult = mysql_query($sql);
if($connect1 ->query($qresult)){
echo "Registered successfully!";
echo "Voornaam: " . $klantVoornaam;
echo "Achternaam" . $klantAchternaam;
echo "E-mail" . $klantMail;
echo "Wachtwoord" . $klantWachtwoord;
}
}
?>
Basically says the function testinput() I made above is undefined but I doesn't seem to see the mistake in that.
The script is set in my body as is the rest, using testinput() to strip of any strange characters since it's a username.
You're defining testinput in javascript, you can't call it from PHP. Instead, you should define it in PHP:
<?php
function testinput($value) {
$value = trim($value);
$value = stripslashes($value);
$value = htmlspecialchars($value);
return $value;
}
// Rest of your PHP code
BTW: This function doesn't really test your input, it sanitizes it. You should probably give it a different name to better describe what it does.
Thx alot! Stupid mistake by me, the teacher told me to use these trim/strips so I thought I'd stick with it
Related
I am trying to input data to MySQL using PHP. Don't know what's wrong. The connection succeeds, no errors but at the end there is not data being written to the database.
$dbhost = "localhost";
$dbname = "listings";
$un = $_POST["un"];
$pass = $_POST["pass"];
$name = $_POST["name"];
$des = $_POST["des"];
$quan = $_POST["quantity"];
$specs = $_POST["specs"];
$price = $_POST["price"];
$url1 = ".";
$url2 = ".";
$url3 = ".";
$url4 = ".";
$connection = mysqli_connect($dbhost,$un,$pass,$dbname);
if (!$connection) {
die("Error".mysqli_error);
} else {
echo "Database connection successfull ".$des;
}
$query = "INSERT INTO items
(name,description,quantity,specs,price,url1,url2,url3,url4) VALUES
'$name','$des','$quan','$specs','$price','$url1','$url2','$url3','$url4')
";
echo "Hellos";
$exeute_query = mysqli_query($query,$connection);
if(!execute_query){
die("error ".mysqli_error());
echo "query error";
} else {
echo "Query successfull";
}
mysqli_close($connection);
Any help?
There are several small mistakes in your code:
$query = "INSERT INTO items (name,description,quantity,specs,price,url1,url2,url3,url4) VALUES ('$name','$des','$quan','$specs','$price','$url1','$url2','$url3','$url4')";
echo "Hellos";
**$exeute_query** = mysqli_query($query,$connection); // $execute_query instead of $exeute_query
if(!**execute_query**){ //$execute_query instead of execute_query
die("error ".mysqli_error());
echo "query error";
}
else{echo "Query successfull";}
mysqli_close($connection);
?>
Your code breaks at the if statement because no fucntion with that name is found (if you do not use the dollarsign to show it is a variable, php will interpret it as a function. Also, when initiating your variable you forgot a 'c' so make sure to check if you have the correct variable name or php won't find your variable. Now your query will work or give an error message in case of wrong data formats or bad connection. Use code listed below to debug your php in the future.
error_reporting(E_ALL);
ini_set('display_errors', 'On');
I've been reading and gathering information for 2 days already and I give up. I have no clue why my piece of simple code is not succeeding.
I want to insert data from one form into two tables and YES I know there are exactly same problems described here and there, but as I said I'm familiar with them and also need to ask more questions.
The problem is in my query somewhere, at least this is what I believe it is.
Here it goes:
unset($err);
//Variables
$host = 'my.server.com';
$user = '123';
$pass = 'password';
$dbname = '123';
$err = array();
$error_form = false;
$img = "sth/sth.jpg";
//Connecting to the database using mysqli application programming interface
$con = mysqli_connect($host, $user, $pass, $dbname);
if (!validate()) {
if (!$con) {
echo "Connection failed : <br />" . $new_con->connect_errno . "<br />" . $new_con->connect_error;
exit;
} else {
echo "Connected! <br />";
}
var_dump($name);
echo "<br />";
var_dump($email);
echo "<br />";
var_dump($img);
echo "<br />";
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_query($con,$query));
echo "<br />";
$_POST["name"] = "";
$_POST["email"] = "";
$_POST["story"] = "";
}
//Form validation
function validate() {
global $name, $email, $story, $err, $error_form;
if($_SERVER['REQUEST_METHOD']=="POST") {
if(isset($_POST["name"]) && !empty($_POST["name"])) {
$name = htmlspecialchars($_POST["name"]);
} else {
$err[0] = "Name is missing.";
$error_form = true;
}
if(isset($_POST["email"]) && !empty($_POST["email"])) {
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$email = htmlspecialchars($_POST["email"]);
} else {
$err[1] = "Email was verified as incorrect.";
$error_form = true;
}
} else {
$err[1] = "Email is missing.";
$error_form = true;
}
if(isset($_POST["story"]) && !empty($_POST["story"])) {
$story = htmlspecialchars($_POST["story"]);
} else {
$err[2] = "Your story does not contain any characters, it can't be submited.";
$error_form = true;
}
}
return $error_form;
}
Everything what confuses me happens here:
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_query($con,$query));
I've tried to SELECT the id FROM the table1 table and SET it as a #value instead of LAST_INSERT_ID(). I've tried to run two queries...many different solutions.
I found out when I dump mysqli_query($con,$query) it gives false every time unless I don't use transaction, so just simple queries, but I need them.
Last thing is should I use PDO instead of mysqli? Why?
and
Why to use mysqli object oriented style instead of procedural one?
Every help is appreciated. I would like more to understand than just to achieve the effect here.
Be aware this is my first post here, but not the first visit.
You can only do one query at a time with mysqli_query Look at mysqli_multi_query()
http://www.w3schools.com/php/func_mysqli_multi_query.asp
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_multi_query($con,$query));
I'm working on a filter in which results are filtered right away, I'm wondering if that may be the cause of the problem so I thought I would ask and see if anyone could give me a pointer on how to proceed.
<script>
var services = [
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$url = $row["$url"];
$title = $row["$title"];
$amount = $row["$amount"];
$id = $row["$id"];
$status = $row["$status"];
$nonprofit = $row["$nonprofit"];
echo '{"permalink": "';
echo "{$url}";
echo '",';
echo '"title": "';
echo "{$title}";
echo '",';
echo '"amount":';
echo "{$amount}";
echo ',';
echo '"id": "';
echo "{$id}";
echo '",';
echo '"status": "';
echo "{$status}";
echo '",';
echo '"address": "';
echo "{$address}";
echo '",';
echo '},';
}
}
?>
]
//]]>
</script>
<script id="template" type="text/html">
<a title="{{title}}" href="{{permalink}}">
<div class="fs_box hide-for-small-down">
<div class="fs_left">
<span class="fs_head">{{title}}</span>
<span class="fs_id"><img src="images/{{id}}.jpg" width="75%" height="75%" onError="this.onerror=null;this.src='images/logo.png';"></span>
<span class="fs_status">{{status}}</span>
<span class="fs_disc">{{address}}</span>
</div>
<div class="fs_price">${{amount}}+</div>
<div class="clear"></div>
</div>
</a>
</script>
I'm expecting it to produce a bunch of results that then are filtered criteria which are elsewhere in the page.
When I try it currently just as a php code it outputs fine. However, when I try it in the php file that this should go in it produces nothing. Or does it dislike being in a script?
Thanks for any help!
You can use json_decode and json_encode to turn an array to json and json back to an array.
Also someone will probably mention that you should not be using the mysql_* functions in PHP as they are depreciated.
Something like this:
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
$results = array()
while($row = mysql_fetch_array($result)) {
$results[] = $row;
}
$json = json_encode($results);
}
?>
]
<script>
var services = <?php echo $json; ?>;
</script>
This would give you a json object to use to render in your script.
What extension is the file you are saving?
If it's not .php or an extension set to render php, then you'll just have the code show up as test.
You might want to pull out the "die" statement after the db connect. This looks like you are running php in a .js file so you probably want the entire file to write out rather than stop because you couldn't connect to the database (or at least give 0 results, maybe a warning)
I am creating a login based application and this is what I have so far. I am trying to read each field into a separate textarea. I have tried to bind the data etc. I do get a output in the textarea, but it prints all the fields in one textarea. Please help.
<?php
selectDB();
function selectDB() {
$usertoken = $_POST['usertoken'];
//Database service vars
$databasehost = "localhost";
$databasename = "morerandom";
$databasetable = "random";
$databaseusername = "root";
$databasepassword = "root";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT username, useremail, firstname, lastname FROM $databasetable WHERE usertoken='$usertoken'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count)
{
$rows = array();
while ($row = mysql_fetch_object($result)) {
$rows[] = $row;
}
echo $rows[0]->username . "\n";
echo "\n";
echo $rows[0]->useremail . "\n";
echo $rows[0]->firstname . "\n";
$first = $rows[0]->lastname;
echo $first;
// echo "$lastname;"
}
else
{
echo 'Token not valid';
}
mysql_free_result($result);
mysql_close($con);
}
?>
What you are getting is just one string. There are better way to retrieve this kind of data from the server side(XML or AMF).
If you want to go ahead with your method then split the string using '\n' as a delimiter but check first that the server response is not 'Token not valid'.
So something like this should work:
First remove the echo "\n"; line under the echo $rows[0]->username . "\n";
var responseArray:Array = theStringResult.split('\n');
So now the responseArray stores the username at position 0, useremail at position 1, firstname at position 2 and lastname at position 3.
But again, you are sending data from the server as raw text and this is not the best way to do it. Check this link to see how this can be done using AMFPHP.
I have a newsletter for one of my sites and I can't the email posted to the mysql database.
Here is the html form code:
subscribe
<h2>newsletter</h2>
<br /><input type="text" name="email" value="" id="email" />
<input type="button" name="submit" onclick="submit_it()" value="OK" />
<script type="text/javascript" charset="utf-8">
function submit_it() {
var cate_value = $('#cate').val();
var email_value = $('#email').val();
$.post("subscribe.php", { email: email_value , cate: category_value }, function(response) {
if (response!='') {alert(response)};
alert('ok');
});
}
</script>
</body>
And here is the php processing code:
$host = "localhost";
$user = "some_user";
$password = "some_pass";
$database = "news";
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
function sql_quote($value) {
$value = str_replace('<?','',$value);
$value = str_replace('script','',$value);
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
} else {
if ((string)$value[0] == '0') {
$value = "'" . mysql_real_escape_string($value) . "'";
}}
return $value;
}
$q = "INSERT INTO emails (email,cate) VALUES (".sql_quote($_POST['email']).",".$_POST['cate'].")";
mysql_query($q);
?>
Any help would be much appreciated because I've been fooling with this for the last 5hrs trying to make it work and I just can't figure it out plus I can't look at it anymore. My eyes hurt now. lol Thanks again.
You should definitely rewrite your code as hobodave suggests. I think something is wrong with your db configuration, though. Try this in the meantime, to execute your query:
$result = mysql_query($q);
if( $result ){
echo( 'OK' );
} else {
echo( 'Invalid query: ' . mysql_error() );
}
Your PHP sql_quote function is very naive with it's str_replace() filtering. It is trivial to bypass this and insert unwanted data in your database.
I suggest the following rewrite of your code:
<?php
$host = "localhost";
$user = "some_user";
$password = "some_pass";
$database = "newsletter";
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
function sql_quote($value)
{
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
return mysql_real_escape_string($value);
}
$email = $_POST['email'];
$category = $_POST['category'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)
&& FALSE !== filter_var($category, FILTER_VALIDATE_INT)
) {
$q = sprintf("INSERT INTO emails (email, category) VALUES ('%s', '%s')",
sql_quote($email),
sql_quote($category)
);
// execute query
} else {
// Do what you want with invalid data
}
I'd also suggest the following changes:
Disable magic_quotes_runtime so you don't need to check, thus you can do away with sql_quote entirely
Use mysqli
Edit:
Why are you even using AJAX to process this form submission? I don't see any benefit in it. You're not doing anything special, just submitting a form.
I'd suggest removing the AJAX altogether and just using the submit button as it's intended.
If you insist though, you can at least temporarily remove it to simplify your testing.
You have a syntax error in your query try this
$email = sql_quote($_POST['email']);
$category = $_POST['category'];
$q = "INSERT INTO emails (email,category) VALUES ('$email','$category')";
You have to use data as key for your data.
$.ajax(url: "ajax_subscribe.php",
method : 'POST',
data: { email: email_value , category: category_value },
success: function(response) {
if (response!='') {alert(response)};
alert('Thank You !');
});