Jump to content

check data type and value


mtvaran

Recommended Posts

Hmm well as I said, just requires a basic query:

 

if (!preg_match('/^[0-9]{5}$/', $id))
{
    // invalid format
}

$sql = "SELECT id FROM table_name WHERE id =" . $id;
$query = mysql_query($sql) or trigger_error('MySQL error: ' . mysql_error());

if (mysql_num_rows($query) > 0)
{
    // already taken
}

 

You'll need to handle the errors of course.

Link to comment
Share on other sites

Adam, i cudn't correcr errors. this is my code..... can you pls have a look....

 

<?php

$con = mysql_connect("localhost","root","");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

mysql_select_db("uni", $con);

 

$sql="INSERT INTO Student (StudentID,StudentName)

VALUES ('$_POST[sid]','$_POST[sname]')";

 

if(!mysql_query($sql,$con))

  {

  die('Error: ' . mysql_error());

  }

 

if (!preg_match('/^[0-9]{7}$/', $_POST['sid']))

{

  echo"existing id ......... "; // invalid

}

 

$sql = "SELECT StudentID FROM student WHERE StudentID =" . $sid;

$query = mysql_query($sql); or trigger_error('MySQL error: ' . mysql_error());

 

if (mysql_num_rows($query) > 0)

{

    echo"id  already taken......";// already taken

}

 

mysql_close($con)

?>

 

Link to comment
Share on other sites

Adding to what Anti-Moronic posted, you also need to handle the errors. Echoing out an error message will simply just print the message and the script will move on to the insert (once it's been moved) - you need to handle the errors.

 

There's about a million ways to handle errors, so here's a very simple example using exceptions (a "try..catch" block):

 

try
{
    if (!preg_match('/^[0-9]{7}$/', $_POST['sid']))
    {
        throw new Exception('Invalid ID format');
    }

    $sql   = "SELECT StudentID FROM student WHERE StudentID =" . $_POST['sid'];
    $query = mysql_query($sql) or trigger_error('MySQL error: ' . mysql_error());

    if (mysql_num_rows($query) > 0)
    {
        throw new Exception('ID already taken');
    }

    $sql="
        INSERT INTO Student (StudentID, StudentName)
        VALUES (
            '" . $_POST['sid'] . "'
          , '" . mysql_real_escape_string($_POST['sname']) . "'
        )
    ";

    $insert = mysql_query($sql) or trigger_error('MySQL error: ' . mysql_error());

    echo 'Success';
}
catch (Exception $e)
{
    echo $e->getMessage();
}

 

Within the try block, if an  exception is thrown the catch block will handle it and nothing else within the try block will be executed. This is useful for situations like you have, where you don't want to continue execution of a certain part of the script if there's an error.

 

I've left the MySQL errors using trigger_error() still though, as they're not strictly application errors, but fatal errors that should be fixed during development; on a production website you'd hide PHP errors so the end-user never seems them using: ini_set('display_errors', 0);

 

Hope this helps.

Link to comment
Share on other sites

Hi Adam, i have posted this before but i cudn't get the proper answer jet. if you can pls hava a look. i have already displayed data from database. one is drop-down list another one multi select list, now i need to select one data from drop-down list and one or more data from multi select list then send to another table. hope i have made this clear understand for you. so cud you plss help me if you can ...

 

 

// coding for displaying drop-down list
<?php

$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
  mysql_select_db("uni", $con);
  
  
$result  = mysql_query("SELECT * FROM student");

echo "<select>";

while($row = mysql_fetch_array($result))
{

echo "<option>";
echo $row['StudentID'];
echo " - ";
echo $row['StudentName'];
  echo "</option>";
} 
echo "</select>";
mysql_close($con);

?>

// this is coding for multi select list

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
  mysql_select_db("uni", $con);
  
  
$result  = mysql_query("SELECT * FROM course");

echo "<select multiple='multiple' size = '10'>";

while($row = mysql_fetch_array($result))
{
echo "<option value=''>";
echo $row['CourseID'];
echo "-";
echo $row['CourseName'];
  echo "</option>";
   
} 
echo "</select>";
mysql_close($con);

?>

 

 

MOD EDIT:

 . . . 

[/nobc] tags added . . .

Link to comment
Share on other sites

Sorry I'm not sure I follow 100%. The way you've posted these they look like two separate files, yeah? You want to select 1 student and multiple courses, from the same page, then enter the selected data into another table? If so, what table? What's the table structure like?

Link to comment
Share on other sites

well let me explain, i have two table in my database which are student (st_id, st_name)& course(course_id, course_name). i have displayed the field st_id from student (drop-down list) & course_id from course (multi select list). now i need to insert into another table called take which contain the feild st_id and course_id. so i have to select one st_id and one or more course_id then submit. hope you get my point and not too difficult to do this for you. :)

Link to comment
Share on other sites

This should handle updating the database:

 

if (!empty($_POST['studentID']) && !empty($_POST['courseIDs']))
{
    $student = mysql_real_escape_string($_POST['studentID']);
    $sql = "INSERT INTO take (st_id, course_id) VALUES";

    foreach ($_POST['courseIDs'] as $key => $course)
    {
        $sql .= ($key != 0) ? ", " : " ";
        $sql .= "('" . $student . "', '" . mysql_real_escape_string($course) . "')";
    }

    $query = mysql_query($sql) or trigger_error('MySQL error: ' . mysql_error());

    if (mysql_affected_rows($query) > 0)
    {
        echo 'Success';
    }
}

 

Very rushed as I'm leaving soon. Just remember to add the correct input names ('studentID', 'courseIDs' in my code) to your form. Also for multiple select fields you need to add "[]" to the end of the name (e.g. name="courseIDs[]"), in order to submit the data as an array; otherwise only the last selected option will be sent.

Link to comment
Share on other sites

Hi Adam, i wrote the coding as you said but when i run it  doesn't say any error massage only says Apache server stop working! so cud you pls check the code if i have made any mistake?

 

<?php

 

$con = mysql_connect("localhost","root","");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

  mysql_select_db("uni", $con);

 

$result  = mysql_query("SELECT * FROM course");

 

echo "<select name ='"cid[]"' multiple='multiple' size = '10'>";

 

while($row = mysql_fetch_array($result))

{

echo "<option value=''>";

echo $row['CourseID'];

 

  echo "</option>";

 

}

echo "</select>";

mysql_close($con);

 

?>

--------------------------------------------------------------

 

<?php

 

$con = mysql_connect("localhost","root","");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

  mysql_select_db("uni", $con);

 

$result  = mysql_query("SELECT * FROM student");

 

echo "<select name = '"sid[]"'>";

 

while($row = mysql_fetch_array($result))

{

 

echo "<option value=''>";

echo $row['StudentID'];

 

  echo "</option>";

 

}

echo "</select>";

mysql_close($con);

 

?>

 

------------------------------------------------

<?php

$con = mysql_connect("localhost","root","");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

 

  mysql_select_db("uni", $con);

if (!empty($_POST['sid']) && !empty($_POST['cid']))

{

    $student = mysql_real_escape_string($_POST['sid']);

    $sql = "INSERT INTO take (StudentID, CourseID) VALUES";

 

    foreach ($_POST['cid'] as $key => $course)

    {

        $sql .= ($key != 0) ? ", " : " ";

        $sql .= "('" . $student . "', '" . mysql_real_escape_string($course) . "')";

    }

 

    $query = mysql_query($sql) or trigger_error('MySQL error: ' . mysql_error());

 

    if (mysql_affected_rows($query) > 0)

    {

        echo 'Success';

    }

}

 

mysql_close();

?>

Link to comment
Share on other sites

Okay, first of all you don't need to connect and close the connection for each query. You'd be better off taking the connection code and storing within a separate file, so that at the top of any code requiring a connection you can just include it.

 

global "connection.php" file:

<?php

$con = mysql_connect("localhost","root","");
mysql_select_db("uni", $con) or trigger_error('MySQL error: ' . mysql_error());

?>

 

code for this file:

<?php

// include connection
require_once 'path/to/connection.php';

$result  = mysql_query("SELECT * FROM course") or trigger_error('MySQL error: ' . mysql_error());

// notice below I've used single quotes for strings as it's easier to write HTML
echo '<select name ="cid[]" multiple="multiple" size="10">';

while($row = mysql_fetch_array($result))
{
    // previously you hadn't set the value of the option
    echo '<option value="' . $row['CourseID'] . '">' . $row['CourseName'] . '</option>';     
}

echo '</select>';

// ----------------

$result  = mysql_query("SELECT * FROM student") or trigger_error('MySQL error: ' . mysql_error());

// you don't want to pass the student ID as an array so remove the block brackets
echo '<select name="sid">';

while($row = mysql_fetch_array($result))
{
    // same problem as before
    echo '<option value="' . $row['StudentID'] . '">' . $row['StudentName'] . '</option>';   
}

echo '</select>';

// ----------------

if (!empty($_POST['sid']) && !empty($_POST['cid']))
{
    $student = mysql_real_escape_string($_POST['sid']);
    $sql = "INSERT INTO take (StudentID, CourseID) VALUES";

    foreach ($_POST['cid'] as $key => $course)
    {
        $sql .= ($key != 0) ? ", " : " ";
        $sql .= "('" . $student . "', '" . mysql_real_escape_string($course) . "')";
    }

    $query = mysql_query($sql) or trigger_error('MySQL error: ' . mysql_error());

    if (mysql_affected_rows($query) > 0)
    {
        echo mysql_affected_rows($query) . ' rows added.';
    }
}

?>

 

Tidied up the code and fixed a couple of bugs which I've put comments next to. Unfortunately though it sounds like you're having a server problem, as opposed to the code - although I'm not familiar with that error message. Could you send a screen shot of the error to make things easier?

 

Edit:

 

Of course you'll need a way to submit the form, don't forget.

Link to comment
Share on other sites

could  anyone pls check this coding? i need to display the data from database into the text field  for editing then submit to the existing database.

 

 

mysql_select_db("uni", $con);

 

$sql=mysql_query("select * from student");

 

$res=0;

 

while($row=mysql_fetch_array($sql))

{

if($row['StudentID']==$_POST["sid"])

 

{

?>

<form id="form2" name="form2" method="post" action="update.php">

 

  <h2><p><?php echo "StudentID :" ?> <input type="text" name="sid" id="sid" value="<?php echo"".$row['StudentID'] ?>" />

 

  <p><?php echo "StudentName :" ?> <input type="text" name="stname" id="stname" value="<?php echo"".$row['StudentName'] ?>" /> </p>

 

 

<?php

  $res=1;

}

 

}?> <h2> <?php

 

 

if($res==0)

{

echo "Please enter the Correct ID. ";

}

 

 

 

 

 

update.php

 

mysql_select_db("uni", $con);

 

mysql_query("UPDATE student SET StudentID = .$row['StudentID']

WHERE student.StudentID = '.$row['StudentID']'");

 

mysql_query("UPDATE student SET StudentName = .$row['StudentName']

WHERE student.StudentID = '.$row['StudentID']'");

 

echo "Successfully Edited";

 

//submit button

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.