I'm having some trouble where I'm pulling values from both a session and a form - for a ticketing system - and when someone uses an apostrophe, it breaks the code.
See below where I receive the data:
$name = $_POST["name"];
$topic = $_POST["topic"];
$urgency = $_POST["urgency"];
$subject = $_POST["subject"];
$details = $_POST["details"];
$username = $_SESSION["username"];
$imgloc = $_SESSION["imgloc"];
$isit = $_SESSION["isit"];
I later insert it into my MSQL database here:
$sql = "INSERT INTO tickets (id, ticketname, urgency, topic, submitted, subject, details, isticketimage, imgloc) VALUES ('', '$name', '$urgency', '$topic', '$userno', '$subject', '$details', '$isit', '$imgloc')";
How would I amend this code to avoid apostrophe's breaking my mysql command?
You can use PDO from php, it will avoid sql injections.
You can do something like this
$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$sql = "INSERT INTO tickets (ticketname, urgency, topic, submitted, subject, details, isticketimage, imgloc) VALUES (?,?,?,?,?,?,?,?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$name, $urgency, $topic, $userno, $subject, $details, $isit, $imgloc]);
More info : https://www.php.net/manual/en/pdo.prepared-statements.php
mysqli_real_escape_string($dbConnection, $variable)
should do the trick.
Related
I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.
I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.
So I'm doing a register page for teams. So the user who creates a team will be inserted into a database table called alcs_teams. That's not the problem. Then I'd like to insert them into another table called alcs_member_teams. That keeps track of the members on each team.
So I do an insert query into the alcs_teams which works fine. Then I try to select the team id from the data that was just inserted a few lines below. Does this work? I can't get it to work, it just puts 0 in that field in the database.
$member = mysql_query("Select * from members where id=$_SESSION[tid]");
$member = mysql_fetch_array($member);
mysql_query("INSERT into alcs_team (teamid, name, leader, email) VALUES('', $_POST[name]', '$member[name]','$member[email]')");
$teamid = ("Select * from alcs_team where leader=$member[name]");
$row = mysql_fetch_array($teamid);
mysql_query("INSERT into alcs_member_teams (id, alcs_teamid, alcs_memberid, member_name) VALUES ('', '".$row[teamid]."' , '".$member[id]."', '".$member[name]."')");
You should look into using parametrized queries whenever possible
Example:
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$params = array($name, $email);
$sql = 'INSERT INTO CustomerTable (Name, Email) VALUES (?, ?)';
$stmt = sqlsrv_query($conn, $tsql, $params);
This prevents SQL Injection, which can cause a lot of trouble on your site.
I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.
$author = $_SESSION['username'];
$subject = $_POST['subject'];
$body = $_POST['body'];
$branched = $_POST['branched'];
$time = time();
$branchedFrom = $_POST['parent'];
$id = $_POST['parent'];
$next = 0;
$previous = 0;
$branchedTo = 0;
mysql_query(
"INSERT INTO offtopic
VALUES(
'',
'$author',
'$subject',
'$body',
'$time',
'$next',
'$previous',
'$branchedFrom',
'$branchedTo'
");
I've tried it lots of times, even tried changing some stuff, but it doesn't save the info into the database.
The blank space at the begining is where the index is in the database.
The SESSION and POST stuff I'm pretty sure gets passed properly.
"INSERT INTO offtopic VALUES('', '$author', '$subject', '$body', '$time', '$next', '$previous', '$branchedFrom', '$branchedTo'"
Missing closing ‘)’ inside the string. Pick up the error message using mysql_error() and simple syntax errors like this should be obvious.
Also you have SQL injection security holes you could drive a bus through. You need to be calling mysql_real_escape_string() over each string value you concatenate into the string, or use mysqli parameterised queries.
Maybe it is because that your query missing which fields to insert
"INSERT INTO offtopic(field1, field2, etc....) VALUES('', '$author', '$subject', '$body', '$time', '$next', '$previous', '$branchedFrom', '$branchedTo'");