When moving data from on table to another I get Error in query: Duplicate entry '0' for key 'PRIMARY'
I dont care to copy the primary key I would like each table to have its own primary key- this table will just hold data to be processed,checked and released by person them moved to a final table that will contain all processed data.
<basefont face="Arial">
<title>QA-1160 Search</title>
</head>
<body>
<?php
// include the page Header
include('header.php');
?>
<?php
//retrieve session data
echo $_SESSION['mnumber'];
echo "<P>";
$mnumber=$_SESSION['mnumber'];
$amnumber=$mnumber;
$mnumber=" '".$mnumber."' ";
// set database server access variables:
$host = "localhost";
$user = "test";
$pass = "test";
$db = "test";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database :)!");
// create query
$query = "insert into testingqa1160 (material, test, sample, frequency, stp, rtr, notes, usl, lsl) SELECT material, test, sample, frequency, stp, rtr, notes, usl, lsl FROM qa1160 WHERE material=";
$query=$query.$mnumber;
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// mysql_free_result($result);
// close connection
mysql_close($connection);
// clear session
session_unset();
session_destroy();
// load test data
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database :)!");
// create query
$query = "SELECT * FROM testingqa1160";
// $query=$query.$mnumber;
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<center><table cellpadding=5 border=1>";
echo "<tr>";
echo "<center>";
echo "<td>"."ID"."</td>";
echo "<td>"."Material"."</td>";
echo "<td>"."Test"."</td>";
echo "<td>"."Sample"."</td>";
echo "<td>"."Frequency"."</td>";
echo "<td>"."STP"."</td>";
echo "<td>"."Release"."</td>";
echo "<td>"."Notes"."</td>";
echo "<td>"."LSL"."</td>";
echo "<td>"."USL"."</td>";
echo "</center></tr>";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "<td>".$row[3]."</td>";
echo "<td>".$row[4]."</td>";
echo "<td>".$row[5]."</td>";
echo "<td>".$row[6]."</td>";
echo "<td>".$row[7]."</td>";
echo "<td>".$row[9]."</td>";
echo "<td>".$row[8]."</td>";
echo "</tr>";
}
echo "</table></center>";
echo "</center>";
}
else {
// no
// print status message
echo "<center><FONT SIZE=18>";
echo $_GET["mnumber"];
echo " Materail is not found! </font>";
echo "</center>";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
<td>Testing</td>
<?php
// include the page footer
include('footer.php');
?>
</body>
</html>
1.- Don't use mysql_* functions, they are deprecated, use mysqli or PDO
2.- Your table testingqa1160 need to have the auto-increment attribute to the id column
Related
I wan to insert data to mysql table from another database which is connected via ODBC.But I cannot enter into the while loop, here is my code -
N.B: For security I dont provide db name, user and pass.
ODBC connection declared as 'connStr'
<?php
$connStr = odbc_connect("database","user","pass");
$conn = mysqli_connect("server","user","pass","database");
//$result_set=mysqli_query($conn,$datequery);
//$row=mysqli_fetch_array($result_set);
echo "<br>";
echo "<br>";
$query="select cardnumber, peoplename, creditlimit, ROUND(cbalance,2) as cbalance, minpay from IVR_CardMember_Info
where cardnumber not like '5127%'" ;
$rs=odbc_exec($connStr,$query);
$i = 1;
while(odbc_fetch_row($rs))
{ //echo "Test while";
$cardnumber=odbc_result($rs, "cardnumber");
$peoplename=odbc_result($rs, "peoplename");
$creditlimit=odbc_result($rs, "creditlimit");
$cbalance=odbc_result($rs, "cbalance");
$minpay=odbc_result($rs, "minpay");
$conn = mysqli_connect("server","user","pass","database");
$sql= "INSERT INTO test_data(cardnumber, peoplename, creditlimit, cbalance, minpay) VALUES ('cardnumber', 'peoplename', 'creditlimit', 'cbalance', 'minpay') ";
if(!(mysqli_query($conn,$sql))){
//echo "Data Not Found";
echo "<br>";
}
else{
echo "Data Inserted";
echo "<br>";
}
echo $i++ ;
}
echo "<br>";
odbc_close($connStr);
?>
How can I solve this?
If you really want to understand why you can't enter while() {...}, you need to consider the following.
First, your call to odbc_connect(), which expects database source name, username and password for first, second and third parameter. It should be something like this (DSN-less connection):
<?php
...
$connStr = odbc_connect("Driver={MySQL ODBC 8.0 Driver};Server=server;Database=database;", "user", "pass");
if (!$connStr) {
echo 'Connection error';
exit;
}
...
?>
Second, check for errors after odbc_exec():
<?php
...
$rs = odbc_exec($connStr, $query);
if (!$rs) {
echo 'Exec error';
exit;
}
...
?>
you can do it with just SQL check it here, like:
INSERT INTO test_data(cardnumber, peoplename, creditlimit, cbalance, minpay)
SELECT cardnumber, peoplename, creditlimit,
ROUND(cbalance,2) as cbalance, minpay from IVR_CardMember_Info
where cardnumber not like '5127%'
I need to display every new row in bold that will be stored in database in php and and then display it. Only the new row should be bold. Here's what I did
<?php
//connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "resultdb"; //my database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$name=$_POST['name'];
$roll=$_POST['roll'];
$m1=$_POST['m1'];
$m2=$_POST['m2'];
$m3=$_POST['m3'];
//ISNERT DATA INTO TADABASE
$sql="INSERT INTO markstb(name,rollno,sub1,sub2,sub3) VALUES('$name','$roll','$m1','$m2','$m3')";
if($conn->query($sql)===true)
{
//ketp id column in DB to auto_increment
$last_id=mysqli_insert_id($conn);
echo " NEW RECORD INSERTED"."<br>";
if($last_id>0)
{
$sql3="SELECT * FROM markstb WHERE id='$last_id'";
$result = $conn->query($sql3);
echo "<table border='2' bordercolor='black' ";
echo"<tr><td>NAME</td><td>ROLLNO</td><td>SUB1</td><td>SUB2</td><td>SUB3</td></tr>";
while($row=$result->fetch_assoc())
{
echo"<tr><td><b>".$row['name']."</td><td><b>".$row['rollno']."</td><td><b>".$row['sub1']."</td>"
."<td><b>".$row['sub2']."</td><td><b>".$row['sub3']."</td>";
}
echo "</table>";
}
else
{
echo"check last_id";
}
echo "<br><br><br><br>";
}
else
{
echo "ERROR".$sql."<br>".$conn->error;
}
//RETRIVE DATA FROM DATABASE
$sql2="SELECT * FROM markstb ORDER BY name";
//$result=$conn->query($sq2);
$result = $conn->query($sql2);
echo "<table border='2' bordercolor='black' ";
if($result->num_rows > 0)
{
echo"<tr><td>NAME</td><td>ROLLNO</td><td>SUB1</td><td>SUB2</td><td>SUB3</td></tr>";
while($row=$result->fetch_assoc())
{
echo"<tr><td>".$row['name']."</td><td>".$row['rollno']."</td><td>".$row['sub1']."</td>"
."<td>".$row['sub2']."</td><td>".$row['sub3']."</td>";
}
echo "</table>";
}
else
{
echo" 0 rows";
}
$conn->close();
?>
In above program I have ony fetched the row which is new and made it bold
but I have to show all data that is in database and make only row bold which is new, which is entered by the user.
In your last while loop you could try:
if($row['id'] == $last_id){
//echo "your row that is
//bold
}else{
// echo you regular row
}
When you are printing out the data, you can do this type of thing inside of the echo statement:
echo "<tr" . $last_id === (int) $row['id] ? . ' class="bold"' : null; . "><td>...";
So that means, when you are printing the tag, you are checking if the row id matches the last id, if so you are additionally printing a html class of "bold".
Of course, it's up to you to use css to target this selector and actually make it bold.
That is called the 'ternary if'. It looks like this:
condition ? do this if true : do this if false;
I have got a code that should get all of the user's Favourites from favourites and then it should use that information to get the info from menus to display them as pictures.
All it should do is display the user's Favourites but at the moment it will only display one picture when there are many in their Favourites.
<?php
$con=mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id=$_SESSION['user']['id'];
$result = mysqli_query($con,"SELECT * FROM favourites WHERE user='$id'");
while($row = mysqli_fetch_array($result)) {
$code=$row['gamecode'];
$con=mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM menus WHERE code='$code'");
while($row = mysqli_fetch_array($result)) {
?>
<a href="<?php echo $row['link']; ?>">
<img src="<?php echo $row['picture']; ?>" alt="<?php echo $row['game']; ?>" height="120" width="150" class="fade"></a>
<?php
}
mysqli_close($con);
}
mysqli_close($con);
?>
You're killing your query by reconnecting to the DB inside your loop
$con = mysqli_connect(...) // connection #1
$result = mysqli_query(...);
while($row = mysqli_fetch($result)) {
$con = mysqli_connect(...); // connection #2
When you connect again, you kill the original connection, which kills your query.
Unless you need to connect twice with different credentials, there is NO need for a second connection. One single connection can handle multiple queries.
Incidentally, if you'd used a different connection handle variable, e.g.
$con = mysqli_connect(...);
$othercon = mysqli_connect(...);
you wouldn't have had the problem. You CAN have multiple connections, but not using the same single variable.
You have two MySQL connections with the same variable names of $con as well as $result & $row. So I just change the variable names on the inside loop so they don’t conflict & all should work; $con_inside, $result_inside & $row_inside.
I also added or die(mysqli_error()); to your mysqli_query lines so errors can be returned if your query dies.
<?php
$con = mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_SESSION['user']['id'];
$result = mysqli_query($con, "SELECT * FROM favourites WHERE user='$id'") or die(mysqli_error());
while ($row = mysqli_fetch_array($result)) {
$code = $row['gamecode'];
$con_inside = mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result_inside = mysqli_query($con_inside, "SELECT * FROM menus WHERE code='$code'") or die(mysqli_error());
while($row_inside = mysqli_fetch_array($result_inside)) {
?>
<a href="<?php echo $row_inside['link']; ?>">
<img src="<?php echo $row_inside['picture']; ?>" alt="<?php echo $row_inside['game']; ?>" height="120" width="150" class="fade"></a>
<?php
}
mysqli_close($con_inside);
}
mysqli_close($con);
Also, here is a slightly reworked version of your code that should work better. I removed the inside DB connection from the loop & set it at the top of the script. The connection does not have to be reset on each loop. Also, I added lines using mysqli_stmt_bind_param which is a preferred way of using mysqli_* queries instead of setting strings. Also using mysqli_free_result to free up query memory on each loop. These are small things but they add up to better code.
<?php
// Main DB connection.
$con = mysqli_connect("localhost","UN","PW","DB") or die(mysqli_connect_error());
// Inside DB connection.
$con_inside = mysqli_connect("localhost","UN","PW","DB") or die(mysqli_connect_error());
// Set the $id variable.
$id = $_SESSION['user']['id'];
// Set the query string.
$query = "SELECT * FROM favourites WHERE user='$id'";
// Bind the values to the query.
mysqli_stmt_bind_param($query, 's', $id);
// Get the result.
$result = mysqli_query($con, $query) or die(mysqli_error());
// Roll through the results.
while ($row = mysqli_fetch_array($result)) {
// Set the $code variable.
$code = $row['gamecode'];
// Set the query string.
$query_inside = "SELECT * FROM menus WHERE code='$code'";
// Bind the values to the query.
mysqli_stmt_bind_param($query_inside, 's', $code);
// Get the result.
$result_inside = mysqli_query($con_inside, $query_inside) or die(mysqli_error());
// Roll through the results.
while($row_inside = mysqli_fetch_array($result_inside)) {
?>
<a href="<?php echo $row_inside['link']; ?>">
<img src="<?php echo $row_inside['picture']; ?>" alt="<?php echo $row_inside['game']; ?>" height="120" width="150" class="fade"></a>
<?php
}
// Free the result set.
mysqli_free_result($result_inside);
// Close the connection.
mysqli_close($con_inside);
}
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
See if it works using different result variables and only one DB connection.
<?php
$con=mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$id = $_SESSION['user']['id'];
$result1 = mysqli_query($con,"SELECT * FROM favourites WHERE user='$id'");
while($row = mysqli_fetch_array($result1)) {
$result2 = mysqli_query($con,"SELECT * FROM menus WHERE code='".$row['gamecode']."");
while($row2 = mysqli_fetch_array($result2)) { ?>
<a href="<?php echo $row2['link']; ?>">
<img src="<?php echo $row2['picture']; ?>" alt="<?php echo $row2['game']; ?>" height="120" width="150" class="fade"></a>
<?php }
}
mysqli_close($con);
?>
I am trying to display news headers with date of postage beside them. For some reason, the date for each one of them is the same; I didn't post all of them on the same day as the date in the database is different for each.
Here is my code:
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'root', 'olearyinternational');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Query for a list of all existing files
$sql = 'SELECT * FROM `posts` order by created desc limit 8';
$result = $dbLink->query($sql);
$date = date('jS F Y', $d);
// Check if it was successfull
if($result) {
// Make sure there are some files in there
if($result->num_rows == 0) {
echo '<p>There are no files in the database</p>';
}
else {
while($row = $result->fetch_assoc()) {
?>
<li class="good-font"><?php echo $row['title'] ?><span id = "post_date"><?php echo $date; ?></li>
<?php
}
// Close table
echo '</table>';
// Free the result
$result->free();
}
}
else {
echo 'Error! SQL query failed:';
echo "<pre>{$dbLink->error}</pre>";
}
// Close the mysql connection
$dbLink->close();
?>
Your $date is initialized once, up where you do your query. You'll need to echo the postdate in each row instead of $date. Check your schema, it'll probably be something like $row['date'] or $row['post_date']. If you need to change the formatting, do it within the while loop.
Does anyone know why debugger shows an empty value for $result and $mysqli in that script?
<?php
// show SELECT result as HTML table
function show_table($result) {
if(!$result) {
echo "<p>No valid query result.</p>\n";
return;
}
if($result->num_rows>0 && $result->field_count>0) {
echo "<table>";
// column headings
echo "<tr>";
foreach($result->fetch_fields() as $meta)
printf("<th>%s</th>", htmlspecialchars($meta->name));
echo "</tr>\n";
// content
// row fetch row
while($row = $result->fetch_row()) {
echo "<tr>";
foreach($row as $col)
printf("<td>%s</td>", htmlspecialchars($col));
echo "</tr>\n";
}
echo "</table>\n";
}
}
require_once 'password.php';
// connect to MySQL
$mysqli = new mysqli($mysqlhost, $mysqluser, $mysqlpasswd, $mysqldb);
if(mysqli_connect_errno()) {
echo "<p>Sorry, no connection! ", mysqli_connect_error(), "</p>\n";
exit();
}
// show SELECT result with show_table
if($result = $mysqli->query("SELECT * FROM titles")) {
show_table($result);
$result->close();
}
// disconnect
$mysqli->close();
?>
</body></html>
<?php
?>
hey DOD i think you $mysqldb is null because when its null you never revise any error or warning
i test it in other case such as without user name or password.
$mysqli = new mysqli($mysqlhost, $mysqluser, $mysqlpasswd, $mysqldb);