im trying to add data to my database but this code seems to just add blank data. Any solutions would be much appreciated. Thanks in advance.
<?php
session_start();
include 'dbh.php';
$start = $_POST['starttime'];
$finish = $_POST['finishtime'];
$dat = $_POST['date'];
$id = $_POST['userid'];
$sql = "INSERT INTO shift (shiftStart, shiftFinish, shiftDate)
VALUES ('$start', '$finish', '$dat')";
$result = mysqli_query($conn, $sql);
if ($result->affected_rows){
$row=$result->fetch_assoc();
echo'<pre>',print_r($row),'</pre>';
}else{
echo"didnt work";
}
//header("Location: index.php");
?>
$sql = "INSERT INTO shift (shiftStart, shiftFinish, shiftDate)
VALUES (".$start.", ".$finish.", ".$dat.")";
$result = mysqli_query($conn, $sql);
Try the above if any are string values you will need to add quotation marks around them single one ('".$start."').
First of all, use var_dump() to check all $_POST variables - do they have values?
If the method of your form is "get" you should use $_GET.
Step 2. After finding the (probably missing) variables please change you SQL query, otherwise you will have big risk of injection.
You should use prepared statements everywhere dealing with database. Check manual - http://php.net/manual/ru/mysqli.quickstart.prepared-statements.php .
And, by the way, you missing execute () function in your code.
Related
I would like to have a page that, when someone clicks a pre-formatted link I've sent, writes a variable in the URL to a MySQL database and just displays "Thank You" or something to the user.
Example:
The user would click a link formatted something like http://www.example.com/click.php?id=12345
When the page loads the 12345 would be written to a table in a MySQL database, it would show a Thank you, and that is it.
Seems like it should be simple enough but I can't find anything on it. I'm probably searching wrong, since this is all new to me.
Your best bet is to utilise $_GET['id'] which will take in the value from your url.
After grabbing the id from your url you will want to use PDO or mysqli prepared statements in order to protect yourself from sql injection.
I hope this helps.
Updated as per Kevin Voorn's comment.
if(isset($_GET['id']) && !empty($_GET['id'])) {
$logged_id = $_GET['id'];
$stmt = $mysqli->prepare("INSERT INTO tableName (`logged_id`) VALUES (?)");
$stmt->bind_param('i', $logged_id);
$stmt->execute();
if($stmt->affected_rows > 0){
echo "Thank You.";
}
$stmt->close();
}
User $_GET to retrive the value and put into your table.
Example:
code inside click.php
<?php
$id=$_GET['id'];
$sql="Insert into table1 VALUES ($id)";
mysqli_query($connect,$sql);
echo "<script>alert('Thank you')</script>";
?>
Thanks for the responses. I ended up finding this page: https://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17 that described the process for using mysqli to connect to my database. I used that page to create the necessary functions in ../db.php and included it in the actual PHP script that would catch the url. My script ended up looking like this:
<?php
require '../db.php';
date_default_timezone_set('UTC');
$date = date("Y-m-d H:i:s T");
$db = new Db();
$db_id = $db -> quote($_GET['id']);
$db_date = $db -> quote($date);
$result = $db -> query("INSERT INTO `table` (`id`,`GUID`,`AccessTime`) VALUES (NULL, " . $db_id . "," . $db_date . ")");
if($result === false) {
exit();
} else {
echo "<html><body><center><br><h1>Thank You!</h1></center></body></html>";
}
?>
For some reason addslashes is NOT adding slashes when inserting data into database. I thought I was using this right, but clearly not... When I submit data that has single or double quotes, it is just sending the exact string right in. Any ideas on how to make this work?
The code
<?php
//include db connect
include ("db_con.php");
//start session
session_start();
//set variable names
$username = $_SESSION['username'];
$entry = addslashes($_POST['entry']);
$uri = $_SERVER['HTTP_REFERER'];
//send chat
$query = mysqli_query($con, "INSERT INTO chat (username, entry) VALUES
('".$username."', '".$entry."')");
if ($query) {
header('Location: '. $uri);
} else {
echo 'Chat entry failed for an unknown reason - Please go back and try again';
}
?>
addslashes() is for escaping the string. If you got code:
$lastname = "O'Bama";
$query = "SELECT name FROM users WHERE lastname='$lastname'";
The query will produce an error because Bama will be treated as SQL statement. To prevent this you can use addslashes() so
echo addslashes($lastname); // returns O\'Bama
Now you can execute your query without any errors because your database will see value as "O'Bama".
Using addslashes() when dealing with databases is very bad practice. Since you're using PHP's mysqli extension, you should escape your data with mysqli_real_escape_string(). The PHP manual page for addslashes() explains why.
I have a problem with this code, it does delete a row but not editing one. I cannot figure out how to make it work.
Here's the script:
<?php
if($_POST['delete']){
$i = 0;
while(list($key, $val) = each($_POST['checkbox'])) {
$sql = "DELETE FROM $tbl_name WHERE id='$val'";
mysql_query($sql);
$i += mysql_affected_rows();
}
// if successful redirect to delete_multiple.php
if($i > 0){
echo '<meta http-equiv="refresh" content="0;URL=data.php">';
}
}
if($Submit){
for($i=0;$i<$count;$i++){
$sql="UPDATE $tbl_name SET naam='$naam[$i]', achternaam='$achternaam[$i]', leeftijd='$leeftijd[$i]', straat='$straat[$i]', postcode='$postcode[$i]', telefoon='$telefoon[$i]', email='$email[$i]', geslacht='$geslacht[$i]', pakket='$pakket[$i]', WHERE id='$id[$i]'";
$result1=mysql_query($sql1);
}
}
mysql_close();
?>
As others have pointed out $Submit isn't defined before the if statement - also $tbl_name isn't defined either so it would bring back an error if the if statement was triggered.
Also in $result1 you used $sql1 - $sql1 has not been defined.
You're vulnerable to SQL injections like Pekka said, so I advise reading up on it, always, ALWAYS validate user inputted data, never trust anyone :)
Also, you don't need to print a meta refresh, you can just use header
header ("Location: data.php");
$Submit is not defined before it is used. So, its value will be null which is a falsy value. Hence if loop will never get executed.
$Submit is not defined (as others already mentioned). Also, if you do define $Submit then $count is still undefined. So you still won't get into the for loop. And if $count is defined, your code still does not update the database. You store your sql query in $sql but pass $sql1 , which has not been set, as query that should be executed.
And your code is wide open for sql injection. You should not want that.
I'm a newcomer to PHP and am trying to do a login/session for a user. I keep getting errors. Any Help would be greatly appreciated.
<?php session_start();
include('./config.php');
$email=$_POST['email'];
$email=htmlspecialchars($email);
$Password=$_POST['password'];
$Password=htmlspecialchars($Password);
$ip=$_SERVER['REMOTE_ADDR'];
$result = mysql_query("SELECT * FROM member WHERE email='$email' AND password='$Password'") or trigger_error(mysql_error());
$count = mysql_num_rows($result);
while($row = mysql_fetch_array($result)){
$logfirstname=$row['firstname'];
$loglastname=$row['lastname'];
$logid=$row['id'];
$logemail=$row['email'];
$logphone=$row['phone'];
$logbiz=$row['biz_id'];
$logdate=$row['date_joined'];
$logaddress=$row['address'];
$logsponsored=$row['sponsored'];
}
if ($count>0){
$_SESSION['auth']=1;
$_SESSION['id']=$logid;
$_SESSION['biz']=$logbiz;
$_SESSION['name']=$logfirstname." ".$loglastname;
$sess=$logfirstname." ".$loglastname;
if ($logsponsored === "1") { $_SESSION['sponsored']=1;}
mysql_query($result);
mysql_close();
session_regenerate_id();
$sid=session_id();
include('./config.php');
$loginr=mysql_query("INSERT INTO login (sessionid, memberid, username, IPAddr, LogInTime, Status, name)
VALUES ('$sid', '$logid', '$email', '$ip', NOW(), 'On', '$sess')");
mysql_query($loginr);
mysql_close();
header("Location: controlpanel.php");
exit();
}else{
header('Location: login.php?fail=1');
exit();
}
?>`
1 - $email=htmlspecialchars($email);
This is not how you sanitize text for SQL queries. This will somewhat prevent XSS attacks, but does NOTHING for SQL injection. Use mysql_real_escape_string() instead.
2 - while($row = mysql_fetch_array($result)){
Presumably only a single row would be returned, so there's no point in doing this within a loop. Just fetch a single row WITHOUT the while loop.
3 - if ($count>0){
wouldn't it be smarter to this BEFORE you try to retrieve a row? You can do the entirety of the fetching/session populating within this if() instead
4 - mysql_query($result);
At the point you execute this, $result is either boolean FALSE (the original query call failed), a mysql query result statement handle. it is NOT a query string, so your query call will fail
5 - mysql_query($loginr);
See #4 - $loginr is either "false", or a statement handle. Why do the query twice?
As you mentoined you are a newbie and I would strongly encourage you against writing your own login/authentication system in PHP because too much things can go wrong(security breach). I would advise you to use lightopenid which is very easy to use instead.
This is my code to update a table. My problem is that after submitting a fresh record I'm unable to update the first time (it shows blank), but the second time it works fine.
One more thing: when I remove the include statement then it is working fine on submessage.php there is no any phpcode. [annakata: I have no idea what this means]
$pid = $_GET['id'];
$title = $_POST['title'];
$summary = $_POST['summary'];
$content = $_POST['content'];
$catid = $_POST['cid'];
$author = $_POST['author'];
$keyword = $_POST['keyword'];
$result1= mysql_query("update listing set catid='$catid',title='$title',
summary='$summary',content='$content', author='$author', keyword='$keyword' where pid='$pid'",$db);
include("submessage.php");
The things that are wrong with that piece of code are hard to enumerate. However, at the very least, you should establish a connection to the database before you can query it.
Why not just redirect to submessage.php rather than inlining it? Redirecting also prevents duplicate db operations when user refreshed the page. Just replace include statement with:
header('Location: submessage.php?id=' . $pid);
die();
Also, before you deploy your application: DO NOT EVER PUT USER INPUT DIRECTLY IN SQL QUERY. You should used bound parameters instead. Otherwise, you could just as well publicly advertise your database admin password. Read more on PDO and prepared statements at http://ie.php.net/pdo
Here's how I would do it:
$pdo = new PDO(....); // some configuration parameters needed
$sql = "
UPDATE listing SET
catid=:catid, title=:title, summary=:summary,
content=:content, author=:author, keyword=:keyword
WHERE pid=:pid
";
$stmt = $pdo->prepare($sql);
$stmt->bindValue('catid', $_POST['catid']);
$stmt->bindValue('title', $_POST['title']);
$stmt->bindValue('summary', $_POST['summary']);
$stmt->bindValue('content', $_POST['content']);
$stmt->bindValue('author', $_POST['author']);
$stmt->bindValue('keyword', $_POST['keyword']);
$stmt->bindValue('pid', $pid = $_GET['id']);
$stmt->execute();
header('Location: submessage.php?id=' . $pid);
die();
Or in fact, I would use some ORM solution to make it look more like that:
$listing = Listing::getById($pid = $_GET['id']);
$listing->populate($_POST);
$listing->save();
header('Location: submessage.php?id=' . $pid);
die();
Other than the usual warnings of SQL injection - very likely given your code and where you're obtaining the query parameters from (sans any kind of validation) - then it's quite possible your problem has nothing to do with the queries, particularly if it's working on subsequent attempts. Are you sure $_GET['id'] is set the first time you call the script?
Just to note, there is absolutely no reason to have to perform several update queries for each field you need to update - just combine them into a single query.