I'm trying to write a code that will upload a document directly to phpMyAdmin using PHP. I tried this code and It looks like it works and there are no errors, but the data was not uploaded to the database..
Can someone please help point out the problem?
<?php
$host="localhost";
$username = "root";
$password = "";
$database= "schoolydb";
$connect = new mysqli($host,$username,$password,$database);
$connect ->set_charset("utf8");
$message = '';
if(isset($_POST["upload"]))
{
if($_FILES['product_file']['name'])
{
$filename = explode(".", $_FILES['product_file']['name']);
if(end($filename) == "csv")
{
$handle = fopen($_FILES['product_file']['tmp_name'], "r");
while($data = fgetcsv($handle))
{
$student_id = mysqli_real_escape_string($connect, $data[0]);
$student_login = mysqli_real_escape_string($connect, $data[1]);
$student_password = mysqli_real_escape_string($connect, $data[2]);
$student_first_name = mysqli_real_escape_string($connect, $data[3]);
$student_last_name = mysqli_real_escape_string($connect, $data[4]);
$student_phone_number = mysqli_real_escape_string($connect, $data[5]);
$student_gender = mysqli_real_escape_string($connect, $data[6]);
$original_back_school = mysqli_real_escape_string($connect, $data[7]);
$original_end_time = mysqli_real_escape_string($connect, $data[8]);
$original_class = mysqli_real_escape_string($connect, $data[9]);
$class_Halom= mysqli_real_escape_string($connect, $data[10]);
$parent_id = mysqli_real_escape_string($connect, $data[11]);
$teacher_id = mysqli_real_escape_string($connect, $data[12]);
$query = "INSERT INTO `student`(`student_id`, `student_login`, `student_password`, `student_first_name`, `student_last_name`, `student_phone_number`, `student_gender`, `original_back_school`, `original_end_time`, `original_class`, `class_Halom`, `parent_id`, `teacher_id`) VALUES ($student_id, '$student_login','$student_password','$student_first_name','$student_last_name', '$student_phone_number','$student_gender','$original_back_school',' $original_end_time','$original_class','$class_Halom','$parent_id','$teacher_id') ";
mysqli_query($connect, $query);
}
fclose($handle);
header("location: index.php?updation=1");
}
else
{
$message = '<label class="text-danger">Please Select CSV File only</label>';
}
}
else
{
$message = '<label class="text-danger">Please Select File</label>';
}
}
if(isset($_GET["updation"]))
{
$message = '<label class="text-success">Updation Done</label>';
}
$query = "SELECT * FROM student";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload Mysql Database through Upload CSV File using PHP</title>
<script src="../jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="../bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h2 align="center">Update Mysql Database through Upload CSV File using PHP</h2>
<br />
<form method="post" enctype='multipart/form-data'>
<p><label>Please Select File(Only CSV Formate)</label>
<input type="file" name="product_file" /></p>
<br />
<input type="submit" name="upload" class="btn btn-info" value="Upload" />
</form>
<br />
<?php echo $message; ?>
<h3 align="center">Student table</h3>
<br />
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tr>
<th>student_id</th>
<th>student_login</th>
<th>student_password</th>
<th>student_first_name</th>
<th>student_last_name</th>
<th>student_phone_number</th>
<th>student_gender</th>
<th>original_back_school</th>
<th>original_end_time</th>
<th>original_class</th>
<th>class_Halom</th>
<th>parent_id</th>
<th>teacher_id</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td>'.$row["student_id"].'</td>
<td>'.$row["student_login"].'</td>
<td>'.$row["student_password"].'</td>
<td>'.$row["student_first_name"].'</td>
<td>'.$row["student_last_name"].'</td>
<td>'.$row["student_phone_number"].'</td>
<td>'.$row["student_gender"].'</td>
<td>'.$row["original_back_school"].'</td>
<td>'.$row["original_end_time"].'</td>
<td>'.$row["original_class"].'</td>
<td>'.$row["student_login"].'</td>
<td>'.$row["class_Halom"].'</td>
<td>'.$row["parent_id"].'</td>
<td>'.$row["teacher_id"].'</td>
</tr>
';
}
?>
</table>
</div>
</div>
</body>
</html>
and this is the student table from my database
..............
There is an error in the line
$query = "INSERT INTO `student`(`student_id`, `student_login`, `student_password`, `student_first_name`, `student_last_name`, `student_phone_number`, `student_gender`, `original_back_school`, `original_end_time`, `original_class`, `class_Halom`, `parent_id`, `teacher_id`) VALUES ($student_id, '$student_login','$student_password','$student_first_name','$student_last_name', '$student_phone_number','$student_gender','$original_back_school',' $original_end_time','$original_class','$class_Halom','$parent_id','$teacher_id') ";
$student_id is not written within ' '
It should be like '$student_id'
So actual code will be
$query = "INSERT INTO `student`(`student_id`, `student_login`, `student_password`, `student_first_name`, `student_last_name`, `student_phone_number`, `student_gender`, `original_back_school`, `original_end_time`, `original_class`, `class_Halom`, `parent_id`, `teacher_id`) VALUES ('$student_id', '$student_login','$student_password','$student_first_name','$student_last_name', '$student_phone_number','$student_gender','$original_back_school',' $original_end_time','$original_class','$class_Halom','$parent_id','$teacher_id') ";
This will solve your issue.
Since you're using .csv files, you can tell PHP that your separator is a semicolon.
<?php
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
?>
To search each value of your file, you can use a strategy like this:
<?php
$row = 0;
if (($handle = fopen("c:\\temp\\test.csv", "r")) !== FALSE)
{
//Searching line by line of the file
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
$num = count($data);
$row++;
//Searching column by column of the current line
for ($col = 0; $col < $num; $col++)
{
//Here you can use the desired values
switch ($col) {
case 0:
$student_id = mysqli_real_escape_string($connect,$data[$col]);
break;
case 1:
$student_login = mysqli_real_escape_string($connect,$data[$col]);
break;
case 2:
$student_password = mysqli_real_escape_string($connect,$data[$col]);
break;
case 3:
$student_first_name = mysqli_real_escape_string($connect,$data[$col]);
break;
case 4:
$student_last_name = mysqli_real_escape_string($connect,$data[$col]);
break;
case 5:
$student_phone_number = mysqli_real_escape_string($connect,$data[$col]);
break;
case 6:
$student_gender = mysqli_real_escape_string($connect,$data[$col]);
break;
case 7:
$original_back_school = mysqli_real_escape_string($connect,$data[$col]);
break;
case 8:
$original_end_time = mysqli_real_escape_string($connect,$data[$col]);
break;
case 9:
$original_class = mysqli_real_escape_string($connect,$data[$col]);
break;
case 10:
$class_Halom = mysqli_real_escape_string($connect,$data[$col]);
break;
case 11:
$parent_id = mysqli_real_escape_string($connect,$data[$col]);
break;
case 12:
$teacher_id = mysqli_real_escape_string($connect,$data[$col]);
break;
}//end switch
}//endfor (columns of each line)
//If your file has a header and you wish to skip it, you can do something like this:
//if ($row > 1) { //create your query and execute it... }
$query = "INSERT INTO `student`(`student_id`, `student_login`, `student_password`, `student_first_name`, `student_last_name`, `student_phone_number`, `student_gender`, `original_back_school`, `original_end_time`, `original_class`, `class_Halom`, `parent_id`,`teacher_id`) VALUES ";
$query.= "($student_id, '$student_login','$student_password','$student_first_name','$student_last_name','$student_phone_number','$student_gender','$original_back_school','$original_end_time','$original_class','$class_Halom', $parent_id, $teacher_id) ";
mysqli_query($connect, $query);
//}
}
fclose($handle);
}
?>
Update : I found out that the $event_start_date = strtotime($row['event_start_date'])); and $event_end_date = strtotime($row['event_end_date'])); is giving the error.
I'm currently creating an event management website for my assignment. and I get a this localhost is currently unable to handle this request. HTTP ERROR 500 whenever with this piece of code. When I remove it runs perfectly. But strange thing is when i run it in Mozila, it just shows a white blank page, when in chrome it gives me this error. BTW i'm using Uniserver as the localhost.
<?php
$query = "SELECT * FROM events ;";
$db_name = "em";
$db_host = "127.0.0.1";
$db_username = "root";
$db_password = "root";
if( !($database_connection = mysql_connect($db_host, $db_username, $db_password)))
{
die ("Error : Could not connect to database.");
}
if( !mysql_select_db($db_name, $database_connection))
{
die ("Error : Could not open the database.");
}
if ( !($result = mysql_query( $query, $database_connection)) )
{
print("Error : Could not execute query.");
die(mysql_error());
} else
{
$count = mysql_num_rows($result);
while($row = mysql_fetch_array($result)) {
$event_id = $row['event_id'];
$event_name= $row['event_name'];
$event_description=$row['event_description'];
$event_venue = $row['event_venue'];
$event_start_date = strtotime($row['event_start_date']));
$event_end_date = strtotime($row['event_end_date']));
//$ticket_type = $row['event_ticket_type'];
$event_price = $row['event_ticket_price'];
$event_account = $row['event_account'];
$event_image = $row['event_image'];
$event_bank = $row['event_bank'];
echo ' <div class="eventbox">
<div class="eventimage">
<img src="'.$event_image.'" href="" class="eventimagefill">
</div>
<div class="eventcontent">
<h6 style="margin:0px; padding: 0px;color:#303A40;">'.date("F j, Y, g:i A", $event_start_date).'</h6>
<h3 style="margin: 0px; padding: 0px; margin-top:5px;color:#303A40;">'.$event_name.'</h3>
<h5 style="float:right;margin-top:-25px; margin-right:30px;padding: 0px;color:#fe8c00;font-size:1.2em;">';
if($event_price == "0.00")
{
echo "FREE";
} else
{
echo 'RM '.$event_price;
}
echo '</h5>
</div>
</div>';
}
}
mysql_close($database_connection);
?>
$event_start_date = strtotime($row['event_start_date']));
$event_end_date = strtotime($row['event_end_date']));
i think you have give here two brackets
$event_start_date = strtotime($row['event_start_date']);
$event_end_date = strtotime($row['event_end_date']);
I have a index.php page Picture : http://i.imgur.com/UBorPdE.png
Website : http://www.vestigedayz.com/sala/clienti/index.php (User: Test123, pass: test)
<?php include("auth.php"); //include auth.php file on all secure pages )
$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pass';
$conn = mysql_connect("host", "user", "pass");
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("vestiged_sala")) {
echo "Unable to select vestiged_sala: " . mysql_error();
exit;
}
mysql_select_db("vestiged_sala");
$result = mysql_query("select * from users");
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["Antrenor"];
echo $row["PrimulContract"];
echo $row["ExpiraContract"];
}
mysql_free_result($result);
?>
ok, after that it comes HTML codes. I have this code
<h4>Bun venit, <?php echo $_SESSION['username']; ?> !
<hr>
Abonamentul tau expira pe data de: <?php echo $row["ExpiraContract"]; ?>
<hr>
Primul tau contract a fost facut pe data de : <?php echo $row["PrimulContract"]; ?>
<hr>
Pe data de <?php echo $row["antrenor"]; ?> va trebui sa platesti instructorul !
</h4>
But php won't show those rows. Only [user] row. The others it appears to be blank. When I add while ($row = mysql_fetch_assoc($result)) above of "Abonamentul tau" it gives me errors. What is the solution to my problem ? Because I know is something easy but I'm beginner and I can't figure it out.
in place of this line
$result = mysql_query("select * from users");
put these lines
$result = mysql_query("SELECT * FROM users WHERE username='$user' LIMIT 1");
while($row = mysql_fetch_array($result)){
$expire = $row['ExpiraContract'];
$primul = $row['PrimulContract'];
$antrenor = $row['Antrenor'];
}
But remember you have to declare empty variables before these line
$user = $_SESSION['username'];
$expire = '';
$primul = '';
$antrenor = '';
So, your full code is like this
//First define empty variables
$user = $_SESSION['username'];
$expire = '';
$primul = '';
$antrenor = '';
// add these lines in place of $result query
$result = mysql_query("SELECT * FROM users WHERE username='$user' LIMIT 1");
while($row = mysql_fetch_array($result)){
$expire = $row['ExpiraContract'];
$primul = $row['PrimulContract'];
$antrenor = $row['Antrenor'];
}
This is you html now
Abonamentul tau expira pe data de: <?php echo $expire; ?>
<hr>
Primul tau contract a fost facut pe data de : <?php echo $primul; ?>
<hr>
Pe data de <?php echo $antrenor; ?> va trebui sa platesti instructorul !
</h4>
Try this. If you have any problem then comment it. :)
Remove these lines if you try this first
while ($row = mysql_fetch_assoc($result)) {
echo $row["Antrenor"];
echo $row["PrimulContract"];
echo $row["ExpiraContract"];
}
Im messing around, trying to see if i can make one of those clickable pet sites that were all the rage a couple years ago and i run into a problem with trying to use if, else, elseif stuff in PHP.
Heres what I have:
<?php
include_once "mysql_connect.php";
$newip = $_SERVER['REMOTE_ADDR'];
$oldip = mysql_query("SELECT lastip FROM sitefunctions WHERE name='index'");
if ($newip == $oldip) {
$message = "You were the last one to click this pet, please wait until someone else has clicked it before trying again.";
}
else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='index'");
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='index'");
$tempclicks = mysql_query("SELECT `clicks` FROM sitefunctions WHERE name='index'");
$message = "You gave this pet a click!";
};
if ($tempclicks == 150) {
mysql_query("UPDATE sitefunctions SET `level` = 2 WHERE name='index'");
$message = "Your click leveled the pet up!";
}
elseif ($tempclicks == 600) {
mysql_query("UPDATE sitefunctions SET `level` = 3 WHERE name='index'");
$message = "Your click leveled the pet up!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='index'");
while($row = mysql_fetch_array($sql)){
$clicks = $row["clicks"];
$level = $row["level"];
$name = $row["name"];
$image1 = $row["image1"];
$image2 = $row["image2"];
$image3 = $row["image3"];
};
if ($level == 1) {
$imageu = $image1;
}
elseif ($level == 2) {
$imageu = $image2;
}
elseif ($level == 3) {
$imageu = $image3;
}
?>
<html>
<head>
</head>
<body>
<p>
<?php print $oldip; ?> <br>
<?php print $newip; ?> <br>
Name: <?php print $name; ?> <br>
<img src=<?php print $imageu; ?> /> <br>
Clicks: <?php print $clicks; ?> <br>
Level: <?php print $level; ?> <br>
<?php print $message; ?>
</p>
</body>
</html>
Now the first problem i'm having is with comparing the users ip with the last ip that was on the page.
$newip = $_SERVER['REMOTE_ADDR'];
$oldip = mysql_query("SELECT lastip FROM sitefunctions WHERE name='index'");
if ($newip == $oldip) {
$message = "You were the last one to click this pet, please wait until someone else has clicked it before trying again.";
}
else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='index'");
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='index'");
$tempclicks = mysql_query("SELECT `clicks` FROM sitefunctions WHERE name='index'");
$message = "You gave this pet a click!";
};
No matter what i have tried it doesnt really compare the values. If i put a "=" it says theyre the same no matter what and if i do "==" it says theyre different even though they shouldn't be.
I dont even know where to start with this, no errors come up and i'm fairly new to PHP and MYSQL. Nothing else can be really tested until this, but im sure that the rest of the comparisons dont work either.
im using 000webhost for my site, if thats known to have problems lol
This is what my code looks like now, it works too so im done here:
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
$name = $_POST['name'];
if (empty($name) == true){
$name = "index";
};
include_once "mysql_connect.php";
$newip = $_SERVER['REMOTE_ADDR'];
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$lastip = $row["lastip"];
}
if ($lastip == $newip) {
$message = "You were the last one to click this pet! You have to wait until someone else clicks it!";
} else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='$name'") or die(mysql_error());
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='$name'") or die(mysql_error());
$message = "You clicked the pet!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$clicks = $row["clicks"];
$level = $row["level"];
}
if ($clicks > 50*$level) {
mysql_query("UPDATE sitefunctions SET `level` = `level`+1 WHERE name='$name'") or die(mysql_error());
$message = "Your click leveled up the pet!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$clicks = $row["clicks"];
$level = $row["level"];
$name = $row["name"];
$image1 = $row["image1"];
$image2 = $row["image2"];
$image3 = $row["image3"];
$lastip = $row["lastip"];
};
if ($level > 35) {
$imageu = $image3;
} elseif ($level > 15) {
$imageu = $image2;
} elseif ($level > 0) {
$imageu = $image1;
};
?>
<html>
<head>
</head>
<body>
<center>
<p>
Name: <?php print $name; ?> <br>
<img src=<?php print $imageu; ?> /> <br>
Clicks: <?php print $clicks; ?> <br>
Level: <?php print $level; ?> <br>
Last User: <?php print $lastip; ?> <br>
<?php print $message; ?>
</p>
</center>
</body>
</html>
I am making online examination.. the data are passing from page to examination page. but the value of radio button is not passing from examination page to result page. I have checked that the course name and subject names are passing. I have added the timer section. Which is working good. The value of radio button inside the while is not passing to result..
EXAM CODE
<html>
<head>
<title>EXAM</title>
</head>
<body>
<?PHP
//$i=1;
$j=1;
$user_name = "root";
$password = "";
$database = "online_exam";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
if ($db_found)
{ session_start();
$i=$_SESSION['$i'];
$sub = $_SESSION['$sub'];
/*if(isset($_POST['b_subject']))
{
$selected_button=$_POST['subject'];
if($selected_button=='subject1')
$_SESSION['$sub']= "GK";
else if($selected_button=='subject2')
$_SESSION['$sub']="math";
else
print "error";
}*/
if(isset($_POST['subject'])){
$selected_button=$_POST['subject'];
}
else
{
$selected_button="default button";
}
while($j<$i)
{
if($selected_button=='subject'.$j)
$s= $sub[$j];
$j++;
}
//print $_SESSION['$sub'];
//print $selected_button;
//print $_SESSION['$cour'];
//print
// //assign $_SESSION['array'] to $array
//print $sub[1];
/* foreach($sub as $value) {
print $value; //print $array contents
}*/
$c = $_SESSION['$cour'];
//$s = $_SESSION['$sub'];
$SQL = "SELECT ques FROM ques_ans WHERE course='$c' AND subj='$s'";
$result = mysql_query($SQL);
echo '<FORM name ="form1" method ="post" action="result_a.php" >';
while ( $db_field = mysql_fetch_assoc($result) )
{
print $db_field['ques']."<BR>";
?>
<Input type = 'Radio' Name ='ques<?PHP echo $i;?>' value= '1'>YES
<Input type = 'Radio' Name ='ques<?PHP echo $i;?>' value= '0'>NO
<br>
<?PHP
$i++;
}
$_SESSION['$i']= $i;
//$_SESSION['ques'] = $que;
$_SESSION['$sub'] = $s;
echo '<input type="submit" name="submit" id="submit" value="SUBMIT"/></FORM>';
mysql_close($db_handle);
}
$targetDate = time()+(330*60) + (1*30);
$actualDate = time()+(330*60);
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
?>
<h1>Time Left</h1>
<script type="text/javascript">
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown ()
{
seconds--;
if (seconds < 0){
minutes--;
seconds = 59
}
if (minutes < 0){
hours--;
minutes = 59
}
if (hours < 0){
days--;
hours = 23
}
document.getElementById("remain").innerHTML = hours+" hours : "+minutes+" minutes : "+seconds+" seconds";
SD=window.setTimeout( "setCountDown()", 1000 );
if (minutes == '00' && seconds == '00') { seconds = "00"; window.clearTimeout(SD);
window.alert("Time is up. Press OK to continue.");
window.location = "http://localhost/result_a.php"
}
}
</script>
<body onload="setCountDown();">
<div id="remain"><?php echo "$remainingHour hours, $remainingMinutes minutes, $remainingSeconds seconds";?></div>
</body>
</html>
Inside the result the line " $selected_radio = $_POST['ques'.$i];" is showing error that "Undefined index: ques1" , "Undefined index: ques2", ... so on....
RESULT CODE
<html>
<head>
<title>RESULT</title>
<body>
<?PHP
$i=1;
$count=0;
$ans= "";
session_start();
//$i=$_SESSION['$i'];
$s=$_SESSION['$sub'];
$c=$_SESSION['$cour'];
//$que[]=$_SESSION['ques'];
//print $c.$s;
$user_name = "root";
$password = "";
$database = "online_exam";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database,$db_handle);
$SQL = "SELECT ans FROM ques_ans WHERE course='$c' AND subj='$s'";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_array($result) )
{
$selected_radio = $_POST['ques'.$i];
if ($selected_radio == '1')
{
$ans='1';
}
else if ($selected_radio == '0')
{
$ans='0';
}
if($ans==$db_field['ans'])
$count++;
$i++;
}
print $count;
?>
</body>
</html>
</head>
you never define $i = anything before you attempt to perform $i++;, you cannot autoincrement an integer without declaring it's starting value.
Therefore your fields are all actually just
name="ques"
Without any integer appended to them. Define $i = 1; or $i = 0; depending on your desire, and this will be resolved.