简体   繁体   中英

How to compare input from a user php post to a MySQL

I am teaching myself php and MySQL, and right now I have a problem with MySQL.

I want to compare the phone number that the user put in with the phone number in MYSQL, and if it is in MYSQL to not register it again.

My code:

<?php

require_once 'connection/connection.php';

// Variables from HTML to php
$worker_Name = $_POST['workerNameFromHtml']; // worker Name
$worker_City = $_POST['workerCityFromHtml']; // workerCity
$worker_career = $_POST['workerCareerFromHtml']; // worker career
$worker_PhoneNumber = $_POST['workerPhonNumberFromHtml']; // worker Phone Number
$worker_SecondPhoneNumber = $_POST['workerSecondPhoneNumberFromHtml']; // worker Second Phone Number
$submt=$_POST['submitFromHtml'];

if($submt){

  $qry = ( "SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'") or die(mysql_error()); 
  $result = $connect->query($qry);
  $num = $result->num_rows;

  if ($num == 1) {
    $here = "INSERT INTO workersTable VALUES('','$worker_Name','$worker_City','$worker_career','$worker_PhoneNumber','$worker_SecondPhoneNumber')";
    $query = $connect->query($here);
    print "Successfully added!";
  }
  else {print "This number has already been entered Thank you for your cooperation!";}}

$connect->close();

So far I have not found a solution to this problem.

your biggest problem here is that you are trying to include variables inside of a string.

"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'"

If you want to do it this way, you need to concatenate your variables with your string.

"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '".$worker_PhoneNumber."'"

Keep in mind if you do this you will want to sanitize your variables first to prevent SQL injections. Also, when you INSERT variables, you will actually want to use a prepared statement like this:

"INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"

where the 1st set of values are the names of your columns in the database and the second set are your PHP variables you are putting into it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM