Insert ID table one to table two

Hi to all.

I am using two tables in a database kids

in I table (ca_kids) fields are

babyid
bname
fname
mname

babyid primary key

II table (vote table)

id
babyid
vote
ip
date
primary keys are id and ip

ok this is my two table structure and i used voting script i found tutorial from ycscripts.co.cc I tried so many tutorials but this is suitable for my thoughts and also working fine but not storing babyid in table II I tried so many ways. I cannot getting solution for this code.


<?php
$host = "localhost";
$username = "root";
$password = "XXX";
$db = "kids";
$path = "http://localhost/polite/kids/";

$res = mysql_connect($host, $username, $password);
if (!$res) die("Could not connect to the server, mysql error: ".mysql_error($res));
$res = mysql_select_db($db);
if (!$res) die("Could not connect to the database, mysql error: ".mysql_error($res));
$bname = addslashes(strip_tags($_GET['babyid']));

$sql=("SELECT * FROM ca_kids   WHERE bname= '".$babyid."'");

$bname = mysql_escape_string($rows['bname']);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>RATING</title>
<script type="text/javascript">
  if (document.images){
    image1 = new Image
    image2 = new Image
    image1.src = 'http://localhost/polite/kids/images/star_off.png'
    image2.src = 'http://localhost/polite/kids/images/star_on.png'
  }
</script>
<style type="text/css">
	.rating {
		display:inline;
	}
	.rating a{
		float:left;
		width:24px;
		height:24px;
	}
	img {
		border:0;
	}
	.confirm {
		color:green;
	}
	.error {
		color:red;
	}
</style>
</head>
<body>
	<?php
	date_default_timezone_set('Europe/Amsterdam');
	//get ip address
	if (isset($_SERVER['HTTP_X_FORWARD_FOR'])) $ip = $_SERVER['HTTP_X_FORWARD_FOR'];
	else $ip = ip2long($_SERVER['REMOTE_ADDR']);

	//check if user (ip) has already voted for this object
	$query = "SELECT ip FROM vote WHERE ip = '".$ip."' AND babyid = '".$babyid."'";
	$result = mysql_query($query);
	$hasVoted = false;
	if (mysql_num_rows($result) == 1) {
		$hasVoted = true;
	}
	
	//save into the database, after clicking on the star
	if (isset($_GET['value'])) {
		$vote = (int) $_GET['value'];
		$babyid = $_GET['babyid'];
		if ($vote == 0) {
			die("<p class='error'>Invalid vote value!</p>");
		}
		// not voted for this poll
		if ($hasVoted === false) {
			$query = "INSERT INTO vote SET babyid = '".$babyid."', ip = '".$ip."', `date`='".date('Y-m-d H:i:s')."', vote=".$vote;
			if (mysql_query($query)) {
				echo "<p class='confirm'>Your voting has been saved succesfully!</p>";
				echo "<a href='home.php'>Go back to the poll</a>";
				die();
			} else {
				echo "<p class='error'>Can't save the voting, ".mysql_error()."</p>";
			}
		} else {
			echo "<p class='error'>You have already voted for this poll!</p>";
		}
	}
	//get average votes
	$average = 0;

	$rs = mysql_query("SELECT avg(vote) as average FROM vote WHERE babyid = '".$babyid."' GROUP BY babyid");
	if (mysql_num_rows($rs) > 0) {
		$row = mysql_fetch_assoc($rs);
		$average = round($row['average']); //round up to an integer
		$averageDecimal = round($row['average'], 2);
	}
	?>
	<div class="rating">
		<?php
		//show the stars one by one
		for ($j=1; $j<=5; $j++) {
			$onmouseout = "onmouseout='document.mouseover".$j.".src=image1.src'";
			$onmouseover = "onmouseover='document.mouseover".$j.".src=image2.src'";
			if ($j != 1) {
				$onmouseover = "onmouseover='document.mouseover1.src=image2.src;";
				for ($k=$j; $k>1; $k--){
					$onmouseover .= "document.mouseover".$k.".src=image2.src;";
				}
				$onmouseover .= "'";
			}
			$img = "<img src='http://localhost/polite/kids/images/star_off.png' alt='star' name='mouseover".$j."' />";
			
			//turn on the star which is smaller or equal as average, so if you have an average of 3, the 
			//first three stars will be turned on.
			if ($j<=$average) {
				$img = "<img src='http://localhost/polite/kids/images/star_on.png' alt='star' name='mouseover".$j."' />";
				$onmouseout = "onmouseout='document.mouseover".$j.".src=image2.src'";
				$onmouseover = "onmouseover='document.mouseover".$j.".src=image1.src'";
			} else {
				$onmouseout = "onmouseout='";
				for ($l=$j; $l>$average; $l--){
					$onmouseout .= "document.mouseover".$l.".src=image1.src;";
				}
				$onmouseout .= "'";
			}
			$title = array(1=>"Poor",2=>"Nothing special",3=>"Worth watching",4=>"Pretty cool",5=>"Freakin' awesome!");
			//if has not voted then you can vote, otherwise not able to click on the stars to vote
			if ($hasVoted === false) {
				?>
				<a  title="<?php echo $title[$j];?>" <?php echo $onmouseout." ".$onmouseover;?> href='rate_index.php?value=<?php echo $j;?>&<?php echo "babyid=$bname" ;?>'><?php echo $img;?></a> 
				<?php
			} else {
				echo $img;
			}
		}

		$result = mysql_query("SELECT count(vote) as total FROM vote");
		$totalVotes = 0;
		if (mysql_num_rows($result) == 1) {
			$row = mysql_fetch_assoc($result);
			$totalVotes = $row['total'];
		}
		echo "<small> Average: ".$average." (".$averageDecimal.") ".$totalVotes." votes</small>";
		?>
	</div>
</body>
</html>

Please any one help me.

On your line 14


$sql=("SELECT * FROM ca_kids   WHERE bname= '".$babyid."'");

add


echo $sql;

beneath it and make sure that the string echoed onto your page contains what you expect, paste the resulting text into your database management tool, make sure you have some matching data in your database.

Do that beneath all of your sql statements one by one until you find the error.

I saw some room for improvement within the script and fixed some things that weren’t correct, see how the below code works for you.

<?php

// Set the default timezone
date_default_timezone_set('Europe/Amsterdam');

$hasVoted = false;
$pass = false;

$host = "localhost";
$username = "root";
$password = "XXX";
$db = "kids";
$path = "http://localhost/polite/kids/";

// Create a new database connection
if (!$con = mysql_connect($host, $username, $password)) {
    die('Could not connect to the server, mysql error: ' . mysql_error());
}

if (!mysql_select_db($db, $con)) {
    die('Could not connect to the database, mysql error: ' . mysql_error());
}

// Set the baby id
if (isset($_GET['babyid'])) {
    $bname = addslashes(strip_tags($_GET['babyid']));
} else {
    die('A baby id is required to use this page');
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rating</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
//<![CDATA[
    if (document.images){
        var image = [], images = ['images/star_off.png', 'images/star_on.png'];
        
        for(var i = 0; i < images.length; i++) {
            image[i] = new Image();
            image[i].src = '<?php echo $path ?>' + images[i];
        }
    }
//]]>
</script>
<style type="text/css">
<!--
    img {
        border: 0;
    }
    .rating {
        display: inline;
    }
    .rating a {
        float: left;
        width: 24px; 
        height: 24px;
    }
    .confirm {
        color: green;
    }
    .error {
        color: red;
    }
-->
</style>
</head>
<body>

    <?php
    // Get ip address
    $ip = isset($_SERVER['HTTP_X_FORWARD_FOR']) ? $_SERVER['HTTP_X_FORWARD_FOR'] : ip2long($_SERVER['REMOTE_ADDR']);

    // Check if user (ip) has already voted for this object
    $sql = "SELECT ip FROM vote WHERE ip = '" . $ip . "' AND babyid = '" . $bname . "'";
    
    if (!$result = mysql_query($sql)) {
        die('An error occurred while running the MySQL query!<br /><br />' . mysql_error());
    }
    
    if (mysql_num_rows($result) == 1) {
        $hasVoted = true;
    }
    
    mysql_free_result($result);

    // Save into the database, after clicking on the star
    if (isset($_GET['value']) && !empty($_GET['value'])) {
        $vote = (int)$_GET['value'];
        
        if ($vote < 1) {
            die('<p class="error">Invalid vote value, must be between 1 and 5!</p>');
        }
        
        // Not voted for this poll
        if (!$hasVoted) {
            $sql = "INSERT INTO vote SET babyid = '" . $bname . "', ip = '" . $ip . "', `date`='" . date('Y-m-d H:i:s') . "', vote='" . $vote . "'";
            
            if ($result = mysql_query($sql)) {
                header('refresh: 3; url=home.php');
                echo '<p class="confirm">Your voting has been saved succesfully!</p>';
                echo '<a href="home.php">Go back to the poll</a>';
                $pass = true;
            } else {
                echo '<p class="error">Can\\'t save the voting, ' . mysql_error() . '</p>';
            }
            
            mysql_free_result($result);
        } else {
            echo '<p class="error">You have already voted for this poll!</p>';
        }
    }
    
    // Only continue if $pass is == to false
    if (!$pass) {
        // Get average votes
        $average = 0;

        $sql = "SELECT avg(vote) as average FROM vote WHERE babyid = '" . $bname . "' GROUP BY babyid";
            
        if (!$result = mysql_query($sql)) {
            die('An error occurred while running the MySQL query!<br /><br />' . mysql_error());
        }
        
        if (mysql_num_rows($result) > 0) {
            $row = mysql_fetch_assoc($result);
            $average = round($row['average']); // Round up to an integer
            $averageDecimal = round($row['average'], 2);
        }
        
        mysql_free_result($result);
        
        echo '<div class="rating">';
            // Show the stars one by one
            for ($i = 1; $i <= 5; $i++) {
                $onmouseout = "onmouseout='document.mouseover" . $i . ".src = image[0].src'";
                $onmouseover = "onmouseover='document.mouseover" . $i . ".src = image[1].src'";
                
                if ($i != 1) {
                    $onmouseover = "onmouseover='document.mouseover1.src = image[1].src;";
                    
                    for ($k = $i; $k > 1; $k--){
                        $onmouseover .= "document.mouseover" . $k . ".src = image[1].src;";
                    }
                    
                    $onmouseover .= "'";
                }
                
                $img = '<img src="' . $path . '"images/star_off.png" alt="star" name="mouseover' . $i . '" />';
                
                // Turn on the star which is smaller or equal as average, so if you have an average of 3, the 
                // first three stars will be turned on.
                if ($i <= $average) {
                    $img = '<img src="' . $path . 'images/star_on.png" alt="star" name="mouseover' . $i . '" />';
                    $onmouseout = "onmouseout='document.mouseover" . $i . ".src = image[1].src'";
                    $onmouseover = "onmouseover='document.mouseover" . $i . ".src = image[0].src'";
                } else {
                    $onmouseout = "onmouseout='";
                    
                    for ($l = $i; $l > $average; $l--){
                        $onmouseout .= "document.mouseover" . $l . ".src = image[0].src;";
                    }
                    
                    $onmouseout .= "'";
                }
                
                $title = array( 1 => 'Poor', 2 => 'Nothing special', 3 => 'Worth watching', 4 => 'Pretty cool', 5 => 'Freakin\\' awesome!');
                
                // If has not voted then you can vote, otherwise not able to click on the stars to vote
                if (!$hasVoted && isset($bname)) {
                    echo '<a title="' . $title[$i] . '" ' . $onmouseout . ' ' . $onmouseover . ' href="rate_index.php?value=' . $i . '&babyid=' . $bname . '">' . $img . '</a>';
                } else {
                    echo $img;
                }
            }

            $totalVotes = 0;
            $sql = "SELECT count(vote) as total FROM vote";
            
            if (!$result = mysql_query($sql)) {
                die('An error occurred while running the MySQL query!<br /><br />' . mysql_error());
            }
            
            if (mysql_num_rows($result) == 1) {
                $row = mysql_fetch_assoc($result);
                $totalVotes = $row['total'];
            }
            
            mysql_free_result($result);
            
            echo ' <small>Average: ' . $average . ' (' . $averageDecimal . ') ' . $totalVotes . ' votes</small>';
        echo '</div>';
    }
    ?>

</body>
</html>

i would guess that the problem starts right here –


WHERE bname= '".$babyid."'"

shouldn’t that be –


WHERE [COLOR="Blue"]babyid [/COLOR]= ".$babyid 

Thanks for all replay here.

Actually I used rate_index.php in my child_list.php page. Is it problem for getting babyid and bname

I am posting my Child_list.php code


<?php 
$babyid = addslashes(strip_tags($_GET['babyid'])); 
$host="localhost"; // Host name 
$username="xxxx"; // Mysql username 
$password="xxxx"; // Mysql password 
$db_name="kids"; // Database name 
$tbl_name="ca_kids"; // Table name 

// Connect to server and select database. 
mysql_connect("$host", "$username", "$password")or die("cannot connect to server "); 
mysql_select_db("$db_name")or die("cannot select DB"); 
$bname = addslashes(strip_tags($_GET['babyid'])); 
$sql=("SELECT * FROM $tbl_name   WHERE bname = '".$babyid."'"); 
$result= mysql_query($sql); 
$rows=mysql_fetch_array($result); 
$count=$rows['count']; 
$bname = mysql_escape_string($rows['bname']); 
$fname = mysql_escape_string($rows['fname']); 
$mname = mysql_escape_string($rows['mname']); 
$age = mysql_escape_string($rows{'age'}); 

// if have no counter value set counter = 1 

$result1=mysql_query($sql1); 

//display child name and Hits (page hits) 
echo  '<tr>  </tr> 
<table  width="100%" border="0" cellpadding="0" cellspacing="0"> 
  <tbody> 
    <tr> 
      <td colspan="2" class="secondtableheadtd" style="color: rgb(255, 255, 255);" align="center" background="../images/tab-bg.png" height="20"><font size="3" color="white">'.$rows['bname'].' || Hits:'.$rows['count'].'</font> 
      </td> 
    </tr> 
</tbody> 
</table> 

'; 

//Display child image and information 
echo'<table align="left" cellspacing="5" cellpadding="5" bgcolor="#ECF1EF" width="100%" border="0"> 
<tr><td rowspan=9 bgcolor="" align="left"><img src="http://localhost/polite/kids/images/' . $rows['image'] . '" alt="No Image" width="370" height="250" border="2px" bordercolor="white"></td></tr> 
</table> 



<table align="center" cellspacing="5" cellpadding="5" bgcolor="#ECF1EF" width="100%" border="0"> 
<tr> 
      <th colspan="2" bgcolor="#2F4F4F" align="left"><font size="2" color="white">Child Information</font></th> 
    </tr> 
<tr><th align="left" width="90px" bgcolor="#FFFFFE">Child Name</th> <td>'.$bname.'</td></tr> 

<tr><th align="left" width="90px" bgcolor="#FFFFFE">Father Name</th> <td>'.$fname.'</td></tr> 

<tr><th align="left" width="90px" bgcolor="#FFFFFE">Mother Name</th> <td>'.$mname.'</td></tr> 

<tr><th align="left" width="90px" bgcolor="#FFFFFE">Age</th> <td>'.$age.'</td></tr> '; 


// count more value (Hits count) 
$addcounter=$count+1; 
$sql2="update $tbl_name set count='$addcounter' WHERE bname = '".$babyid."'"; 
$result2=mysql_query($sql2); 
  
mysql_close(); 

?> 

//rating area

<?php require 'rate_index.php';?>


SgtLegend… I used, you are suggested code that’s not working mainly doesn’t storing babyid.

once again thank for all. Please check my all code.

post #1

finally I got solution for insert babyid.

But I found one more problem in my page

when I add same names of the two bnames it showing first bname rating to the second bname

ex: bname babyid
munna 1
munna 2

how can i improve my code any idea?