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.

5 Likes

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.

EDIT

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 */
$stmt->execute();
1 Like
:::::::::::::::::::::::::::::::::::::database.php:::::::::::::::::::::::::::::
<?php
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 )
       {      
        try 
        {
          self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);  
        }
        catch(PDOException $e) 
        {
          die($e->getMessage());  
        }
       } 
       return self::$cont;
	}
	
	public static function disconnect()
	{
		self::$cont = null;
	}
}
?>


::::::::::::::::::::::add_row.php::::::::::::::::::::::::::::
<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;
				//alert(newcell.childNodes);
				switch(newcell.childNodes[0].type) {
					case "text":
							newcell.childNodes[0].value = "";
							break;
					case "checkbox":
							newcell.childNodes[0].checked = false;
							break;
					case "select-one":
							newcell.childNodes[0].selectedIndex = 0;
							break;
				}
			}
		}
		
		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.");
						break;
					}
					table.deleteRow(i);
					rowCount--;
					i--;
				}


			}
			}catch(e) {
				alert(e);
			}
		}
			
	</SCRIPT>
	

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

	<?php require 'add_row.php';?>
</head>
<body>			<form  action="action.php" method="post">
					<table><thead>
					<td>Title</td><td>Sponsor</td>
					</thead>
					<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>
					  </tr></tbody></table>
					<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')" />
					</form>
		<table class="table table-striped table-bordered" id="example"><thead><tr>
		<th>Title</th><th>Sponsor</th>
		</tr></thead><tbody>
					     <?php 
					   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>';
					   }
					   Database::disconnect();
					  ?>
				      </tbody>
	            </table>
					 
  </body>
</html>

::::::::::::::::::::::::::action.php::::::::::::::::::::::::::::::::::
<?php
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');
}
header('location:entry_history.php');

?>

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.

2 Likes

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:::::::::::::::::::::::::::::

<?php 
	include '../database/database.php';
	if ( !empty($_POST)) {
		$titleError = null;
		$sponsorError = null;
			$pdo = Database::connect();
			$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			 $i=0;
			 foreach($_POST['title'] as $key => $val)
    {	
		  $title  = $val;
    $sponsor = $_POST['sponsor'][$key];
			$sql = "INSERT INTO entry_history (title,sponsor) values(?,?)";
			$q = $pdo->prepare($sql);
			$q->execute(array($title,$sponsor));
			Database::disconnect();
			$i++;
		}}
	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.