php - Trouble Inserting Value to Mysql database: -


i attempting put value mysql database using php. @ earliest stages, ensure works before applying project. have looked @ different ways implement through other people's questions, , not sure why isn't inserting value.

am supposed assign particular row insert to? right now, trying insert value of 3 yield column of database. have checked ensure proper capitalization of first letter in column name, , proper name of database table being cost_table.

when run this, printed statement, "failed insert.." when check database, still entirely null.

<?php //variables connection info...//    $linkid=mysql_connect("$host","$username","$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select db");    $sql = "insert cost_table('yield') values 3"; $check=mysql_query($sql,$linkid); if (!$check){     die ("failed insert.."); } echo "insert successful!"; ?> 

firstly, you're using wrong identifiers column you're wanting insert into, , you've missing brackets , quotes values.

you may have seen video tutorial somewhere, ticks looked regular quotes; has been case.

faulty code:

insert cost_table('yield') values 3 

which should read as, , using ticks instead of regular single quotes around column name:

$sql = "insert cost_table (`yield`) values ('3')"; 

or, if column indeed int type:

$sql = "insert cost_table (`yield`) values (3)"; 

if you're later going want use $ signs and/or decimals $3.99 need quote values values ('$3.99'), otherwise mysql complain that. type of value require column varchar though; just sidenote. decimal minus dollar sign, require decimal column type.

having used following, have signaled syntax errors:

$check=mysql_query($sql,$linkid) or die(mysql_error()); 

however, you're open sql injection using method , suggest use prepared statements before going further project.

here few examples:

an example of mysqli prepared statement:

$link = mysqli_connect("localhost", "user", "password", "database");  if (mysqli_connect_errno()) {      printf("connect failed: %s\n", mysqli_connect_error());      exit(); }       $variable_1 = "text";     $variable_2 = "more text";      $stmt = $link->prepare("insert table_name                              (column_1, column_2)                              values (?,?)");      $stmt->bind_param('ss', $variable_1, $variable_2);     $stmt->execute(); 
  • sidenote: s strings

an example of pdo prepared statement:

$dbh = new pdo('mysql:host=localhost;dbname=your_db', $user, $pass);  $var_1 = "text"; $var_2 = "more text";  $stmt = $dbh->prepare("insert table_name                         (column_1, column_2)                         values (:var_1,:var_2)");  $stmt->execute(array(':var_1' => $var_1, ':var_2' => $var_2)); 

references:


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -