How to prevent SQL injection on this code?

Hi, I have some SQL injection vulnerability here and I’m wondering how to solve this problem.

if(isset($_POST['submit'])){

	$sid = $_POST['sid'];
	$token = $_POST['token'];
	$to_number = $_POST['to-number'];
	$from_number = $_POST['from-number'];
	$text = $_POST['message'];
	mysqli_query($con, "DELETE FROM sms_form");
	mysqli_query($con, "DELETE FROM text1");
	mysqli_query($con, "INSERT INTO sms_form SET
		sid='$sid',
		token='$token',
		to_number='$to_number',
		from_number='$from_number'
	");
	$id = mysqli_insert_id($con);
	mysqli_query($con, "INSERT INTO text1 SET s_id=$id, text='$text'");
	header("location:smsform.php");
	exit();
	
}

$result = mysqli_query($con, "SELECT * FROM sms_form ORDER by id DESC");
$row = mysqli_fetch_array($result);

$chk_res = mysqli_query($con, "SELECT * FROM text1");
$chk_row = mysqli_fetch_array($chk_res);

Well :thinking: - It looks to me you have more than just SQL injection.

I would suggest using PDO instead of mysqli and this is a good link - (The only proper) PDO tutorial - Treating PHP Delusions

I even refer to the link from time to time especially when I haven’t coded in PHP in awhile. Anyways, PDO is so much easier to use than mysqli in my opinion.

I found a way to prevent SQL injection and any other type of attack with a small line of code in all my files.
Thanks for your response Strider64

Since there’s not a small one line solution that will protect against sql injection and other attacks, in all contexts for all datatypes, you are mistaken. Whatever you found only appears to work, and can be bypassed. Hackers have huge libraries of values that contain things you haven’t ever thought about that can get through most simple security layers.

The only fool-proof way of preventing sql injection for all datatypes is to use prepared queries.

2 Likes

I love how you understand how everything works under the hood… Wish I can be like you one day

Sponsor our Newsletter | Privacy Policy | Terms of Service