Why can't insert data into the database?

add.zip (22.7 KB)

Post the code here, and give us a proper description of how far the code gets, where it fails, whether it gets an error message (and if so, what does it say) and what steps you have taken to try to diagnose the problem. Describe the structure of the database tables as well, please.

I’m happy to try to help to the limit of my abilities, but I’m not downloading random zip files from unknown sources to try to do so.


I don’t know because i see only image here :smiley:

As @droopsnoot said post code and your database table structure they you can get some help.

1 Like

Give a screenshot of your code then i will try to give an solution to your problem :slight_smile:

1 Like

First stop mixing mysql with PDO and stop using mysql function is deprecated.

Second use error_reporting(E_ALL); to see actual errors.

Third post your code and actual error you get.


Instead of yours code try to use it like this

// connection
$conn = new PDO('mysql:host=hostname;dbname=databasename;charset=utf8', 'username', 'password');

// mysql_query("INSERT INTO entry_history(  title, sponsor) VALUES ('$?','$?')");

/* Prepare an insert statement */
$stmt = $conn->prepare("INSERT INTO entry_history (title, sponsor) VALUES (?, ?)");
$stmt->bindParam('ss', $title, $sponsor);

/* Execute the statement */
1 Like
class Database 
	private static $dbName = 'tv_news' ; 
	private static $dbHost = 'localhost' ;
	private static $dbUsername = 'root';
	private static $dbUserPassword = '';
	private static $cont  = null;
	public function __construct() {
		exit('Init function is not allowed');
	public static function connect()
	   // One connection through whole application
       if ( null == self::$cont )
          self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);  
        catch(PDOException $e) 
       return self::$cont;
	public static function disconnect()
		self::$cont = null;

<SCRIPT language="javascript">
		function addRow(tableID) {
			var table = document.getElementById(tableID);
			var rowCount = table.rows.length;
			var row = table.insertRow(rowCount);
			var colCount = table.rows[0].cells.length;
			for(var i=0; i<colCount; i++) {
				var newcell	= row.insertCell(i);
				newcell.innerHTML = table.rows[0].cells[i].innerHTML;
				switch(newcell.childNodes[0].type) {
					case "text":
							newcell.childNodes[0].value = "";
					case "checkbox":
							newcell.childNodes[0].checked = false;
					case "select-one":
							newcell.childNodes[0].selectedIndex = 0;
		function deleteRow(tableID) {
			try {
			var table = document.getElementById(tableID);
			var rowCount = table.rows.length;

			for(var i=0; i<rowCount; i++) {
				var row = table.rows[i];
				var chkbox = row.cells[0].childNodes[0];
				if(null != chkbox && true == chkbox.checked) {
					if(rowCount <= 1) {
						alert("Cannot delete all the rows.");

			}catch(e) {

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <link   href="../css/bootstrap.min.css" rel="stylesheet">

	<?php require 'add_row.php';?>
<body>			<form  action="action.php" method="post">
					<tbody id="dataTable" ><tr>
					  <td><input name="title[]" type="text"  placeholder="Title" class="input-medium"   ></td>
					  <td><input name="sponsor[]" type="text"  placeholder="sponsor" class="input-medium"   ></td>
					<INPUT type="button" class="btn btn-primary" value="Add Row" onClick="addRow('dataTable')" />
					<INPUT type="submit" class="btn btn-success" value="Save"/>
					<INPUT type="button"  class="btn btn-danger" value="Delete Row" onClick="deleteRow('dataTable')" />
		<table class="table table-striped table-bordered" id="example"><thead><tr>
					   include '../database/database.php';
					   $pdo = Database::connect();
					   $sql = 'SELECT  *  FROM entry_history order by id desc';
	 				   foreach ($pdo->query($sql) as $row) {
						   		echo '<tr>';
								echo '<td>'. $row['title'] . '</td>';
							   	echo '<td>'. $row['sponsor'] . '</td>';
								echo '</tr>';

include '../database/database.php';

if (
   !empty($_POST['title']) && !empty($_POST['sponsor'])&& 
   is_array($_POST['title']) && is_array($_POST['sponsor'])
      count($_POST['title']) === count($_POST['sponsor']) )  
    $title_array = $_POST['title'];
	$sponsor_array = $_POST['sponsor'];
    for ($i = 0; $i < count($title_array); $i++) {
        $title = mysql_real_escape_string($title_array[$i]);
		 $sponsor = mysql_real_escape_string($sponsor_array[$i]);
 mysql_query("INSERT INTO entry_history(  title, sponsor) VALUES ('$?','$?')");
 else {
    exit('No values entered');


What are you expecting this line of code to do?

mysql_query("INSERT INTO entry_history( title, sponsor) VALUES ('$?','$?')");

You don’t put any variable names into the query, so at best it will try to insert two strings, both “$?”, into the database table.

You need to change that line of code so that it actually uses the variables that you have extracted and escaped in the previous lines of code.

If that doesn’t help, then you need to run the code and figure out which line of code is not running the way you expect it to, and post that bit so someone can help further.


You can’t use this with PDO man :smiley:

And as @droopsnoot said You don’t put any variable names into the query, so at best it will try to insert two strings, both “$?”, into the database table.

1 Like

Can i get the code.?

1 Like

If i change my action.php page code like this then save only single Array or single value, but i want to insert add rows values.

<?php require '../database/database.php'; if ( !empty($_POST)) { $titleeError = null; $spoonsorError = null; $title = $_POST['title']; $sponsor = $_POST['sponsor']; $valid = true; if (empty($title)) { $titleError = 'Please enter title Name'; $valid = false; } $valid = true; if (empty($sponsor)) { $sponsorError = 'Please enter sponsor Name'; $valid = false; } if ($valid) { $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO entry_history (title,sponsor) values(?, ?)"; $q = $pdo->prepare($sql); $q->execute(array($title,$sponsor)); Database::disconnect(); header("Location: entry_history.php"); } } ?>

Well, the part where you handle inserting the new rows is better, but you’ve removed the section where you deal with the inputs being an array, that you had in the first piece of code. Now you just do this:

$title = $_POST['title'];
$sponsor = $_POST['sponsor'];

but then you don’t take into account that the above might be an array.

1 Like

Where can i change in my ‘action.php’ page to insert AddRows values into database?

Have a look at the code you posted for that section in post #6 above - that uses the arrays and runs through them to post multiple rows. Then in your code in post #10, you’ve reverted to only posting one entry.

The older code uses $title_array and $sponsor_array, and runs through each of them with a foreach() loop. So you just need to do that in your new code.

1 Like

::::::::::::::::::::::::::its Ok:::::::::::::::::::::::::::::

	include '../database/database.php';
	if ( !empty($_POST)) {
		$titleError = null;
		$sponsorError = null;
			$pdo = Database::connect();
			 foreach($_POST['title'] as $key => $val)
		  $title  = $val;
    $sponsor = $_POST['sponsor'][$key];
			$sql = "INSERT INTO entry_history (title,sponsor) values(?,?)";
			$q = $pdo->prepare($sql);
	header("Location: entry_history.php");

Did you intend to call the database disconnect() function inside the loop? Doesn’t that mean that you’ll only ever write the first row and then when you try to write the second, you’ll get an error? I don’t recall what code is in the disconnect() function, but if it’s named sensibly then it’s fair to assume that’s what it does.

Once you have this working, move the prepare() to before the loop opens - one of the nice things about using a prepared statement with several values is that you can call prepare once, then just execute it with the difference values each time, without preparing again.

Now I want to search using keywords and export to excel.
How can i do this?

There’s a link in this thread:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.