Can you give a column a standard value? - php

I need to put the value '0' in the database without having to fill in a text field.
Is there any way to give a column the value '0', when i save a form in the database?
This is the form:
<form action="<?php echo $base_url; ?>" method="post" enctype="multipart/form-data">
<table class="sug" width="300">
<tr><td><input type="text" name="naam" placeholder="Naam" required></td>
<td><input type="text" name="level" placeholder="Level"></td></tr>
<tr><td colspan="2"><textarea placeholder="Beschrijving" name="beschrijving" maxlength="200"></textarea></td></tr>
<tr><td><input type="file" name="afbeelding" required id="afbeelding"></td></tr>
<tr><td><input type="submit" name="add" value="Toevoegen"/>
</td></tr>
</table>
</form>
The save function:
if (!empty($post_array)) {
// Check the add form:
$add = FALSE;
if (isset($post_array['add'])) {
// Save images
$check = getimagesize($_FILES["afbeelding"]["tmp_name"]);
if ($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Upload afbeelding
$projecten->upload($_FILES['afbeelding']);
// Save project
$result = $projecten->save($post_array);
if ($result) {
// Save was succesfull
$add = TRUE;
} else {
// Indicate error
$error = TRUE;
}
}
}
public function save($input_array) {
global $wpdb;
// Insert query
$wpdb->query($wpdb->prepare("INSERT INTO `" . $wpdb->prefix . "ivs_canvas_tabel`
( `naam`, `level`, `beschrijving`, `afbeelding`)" .
" VALUES ( '%s', '%s', '%s', '%s');", $input_array['naam'], $input_array['level'], $input_array['beschrijving'], $_FILES['afbeelding']['name']));
// Error ? It's in there:
if (!empty($wpdb->last_error)) {
$this->last_error = $wpdb->last_error;
return FALSE;
}
return TRUE;
}
I have no idea how to add the field, i hope someone can help me out!
Yours sincerely

You can do this using input with hidden attribute in form:
<input type=“hidden” name=“colom” value=“0” />

You can put default value in your database:
alter table `table_name`
modify column `column_name` int default 0;

Related

Not Able to save data to Mysql database

I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. However, I am having a problem with saving the data to the database. when i click on "submit attendance" the data won't be submitted to the database. i use register.php to register students but take the attendance in different file.
Below is the code i use to submit. Can someone help me? Thanks.
sorry the file i shared was supposed to save data to mysql database. Below is the file which takes the data and am still having the problem for saving it.
this is the teacher file to take the attendance
teacher.php
<?php
$pageTitle = 'Take Attendance';
include('header.php');
require("db-connect.php");
if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
echo 'Only teachers can create new teachers and students.';
$conn->close();
include('footer.php');
exit;
}
//get session count
$query = "SELECT * FROM attendance";
$result = $conn->query($query);
$sessionCount=0;
setcookie('sessionCount', ++$sessionCount);
if(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
$sessionCount = $row['session'];
setcookie('sessionCount', ++$sessionCount);
}
}
if(isset($_GET['class']) && !empty($_GET['class'])){
$whichClass = $_GET['class'];
$whichClassSQL = "AND class='" . $_GET['class'] . "'";
} else {
$whichClass = '';
$whichClassSQL = 'ORDER BY class';
}
echo '
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
<span class="input-group-btn">
<input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
</span>
</div>
</div>
<div class="col-md-8">
<form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
<select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
';
// Generate list of classes.
$query = "SELECT DISTINCT class FROM user ORDER BY class;";
$classes = $classes = mysqli_query($conn, $query);
if($classes && mysqli_num_rows($classes)){
// Get list of available classes.
echo ' <option value="">Filter: Select a class</option>';
echo ' <option value="?class=">All classes</option>';
while($class = $classes->fetch_assoc()){
echo ' <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
}
} else {
echo ' <option value="?class=" disabled>No classes defined.</option>';
}
echo '
</select>
</form>
</div>
</div>
';
$query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
$result = $conn->query($query);
?>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<form method="post" action="save-attendance.php" id="attendanceForm">
<?php
if(mysqli_num_rows($result) > 0){
$i=0;
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
<td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
<td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
</tr>
<?php $i++;
}
}
?>
</form>
</tbody>
</table>
<script>
$("#submitAttendance").click(function(){
if($("#session").val().length==0){
alert("session is required");
} else {
$.cookie("sessionVal", $("#session").val());
var data = $('form#attendanceForm').serialize();
$.ajax({
url: 'save-attendance.php',
method: 'post',
data: {formData: data},
success: function (data) {
console.log(data);
if (data != null && data.success) {
alert('Success');
} else {
alert(data.status);
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
<?php
$conn->close();
include('footer.php');
save-attendance.
<?php
//include ("nav.php");
require("db-connect.php");
$query = "SELECT * FROM user WHERE role='student'";
$result = $conn->query($query);
$nameArray = Array();
$count = mysqli_num_rows($result);
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
}
//save record to db
if(isset($_POST['formData'])) {
//increment the session count
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
setcookie('sessionCount', ++$sessionCount);
}
parse_str($_POST['formData'], $searcharray);
//print_r($searcharray);die;
//print_r($_POST);
for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
// setcookie("checkloop", $i);;
$name = $searcharray['name'][$i];
$email= $searcharray['email'][$i];
$class = $searcharray['class'][$i];
$present= $searcharray['present'][$i];
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
//get class id
$class_query = "SELECT * FROM class WHERE name='".$class."'";
$class_id = mysqli_query($conn, $class_query);
if($class_id){
echo "I am here";
while($class_id1 = $class_id->fetch_assoc()){
$class_id_fin = $class_id1['id'];
echo $class_id['id'];
}
}
else{
echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
}
//get student id
$student_query = "SELECT * FROM user WHERE email='".$email."'";
$student_id = $conn->query($student_query);
if($student_id) {
while ($student_id1 = $student_id->fetch_assoc()) {
$student_id_fin = $student_id1['id'];
}
}
//insert or update the record
$query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
ON DUPLICATE KEY UPDATE isPresent='".$present."'";
print_r($query);
if(mysqli_query($conn, $query)){
echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
} else{
echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
}
}
$conn->close();
}
You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined.
if $_COOKIE['sessionVal'] is not set, try:
1- print_r($_COOKIE) and check if [sessionVal] is set;
2- Try to add a fallback to:
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
else {
$sessionVal = 0;
}
or
$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;
Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set.

Ajax Call Returning Empty

i have a form as follows:
<div class="any_reg">
<div class="mail_area">
<form name="any_reg" id="any_reg" method="POST" action="" class="mail_area">
<table>
<tr>
<td><input type="text" name="email" id="mail" placeholder="Enter Your Email"></td>
<input type="hidden" name="id" value="<?php echo $auction ?>">
<td><input type="submit" name="submitmail" id="submitmail" value="Submit"></td>
</tr>
</table>
</form>
</div>
</div>
i have an ajax call as follows:
i have given the url as $ajaxUrl= $dir."/watchemailajax.php";
if(tre == true){
$.ajax({url: '<?php echo $ajaxUrl; ?>',method:'POST',
data:$('#any_reg').serialize()
,success: function(result){
alert(result);
if (result== "Success"){
alert("SUCCESS");
}else
{
alert("Failed");
}
Which Goes to a page with the following code:
<?php
if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['submitmail'])){
check_ajax_referer( "WPA-nonce" );
$auction_id = $_POST['auction_id'];
$watch_email = strip_tags(stripslashes($_POST['email']));
$tablename = $wpdb->prefix . "wp_wpa_watchlist";
$sql = "INSERT INTO ".$tablename." (auction_id, watch_email) VALUES (".$auction_id.", '".$watch_email."' );";
$result = $wpdb->query($sql);
if ($result){
echo "Success";
// _e("You will be notified of any changes to this auction",'wpauctions');
}
else {
echo "Failed";
}
}
The call is returning empty data and nothing else. I am kinda newbie when it comes to Ajax and anything related to it. please help me. Wht is my mistake
You might be failing to meet the requirements for this if statement if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['submitmail'])){ thus causing it to skip execution of the script. Add an else statement to the first if statement and add a message so you can see when it fails like so:
if (strstr($_SERVER['PHP_SELF'],WPA_PLUGIN_NAME) && isset($_GET['submitmail'])){
check_ajax_referer( "WPA-nonce" );
$auction_id = $_POST['auction_id'];
$watch_email = strip_tags(stripslashes($_POST['email']));
$tablename = $wpdb->prefix . "wp_wpa_watchlist";
$sql = "INSERT INTO ".$tablename." (auction_id, watch_email) VALUES (".$auction_id.", '".$watch_email."' );";
$result = $wpdb->query($sql);
if ($result){
echo "Success";
// _e("You will be notified of any changes to this auction",'wpauctions');
}
else {
echo "Failed";
}
}
else {
echo "Failed if statement";
}

php uploading files

I have problem with uploading files. Here is my form:
<form enctype="multipart/form-data" action="transact.php" method="POST">
<table>
<tr>
<td>Nadpis:</td>
<td><input type="text" id="title" name="title" value="<?php echo htmlspecialchars($title); ?>" /></td></tr>
<tr>
<td>Text článku:</td>
<td><textarea id="text" name="text" cols="55" rows="20"><?php if(!empty($a_text)) { echo htmlspecialchars($a_text); } ?></textarea></td>
</tr><tr>
<td>Obrázok k článku:</td>
<td><input type="file" name="uploadfile" /></td></tr>
<tr><td> </td>
<td>
<?php
if ($_SESSION['access_level'] < 2) {
echo '<input type="hidden" name="user_id" value="'. $user_id. '"/>';
}
if(empty($article_id)) {
echo '<input type="submit" name="action" value="Odoslat" />';
} else {
echo '<input type="hidden" name="article_id" value="' .$article_id. '"/>';
echo '<input type="submit" name="action" value="Ulozit" />';
}
?>
</td>
</tr>
</table>
</form>
when I run script transact.php I get error: Notice: Undefined index: uploadfile in E:\xampp\htdocs\capitals\transact.php on line 138
and when I type print_r($_FILES) i get just Array()
value of max upload size in php.ini file is set to 128 MB
my transact script:
case 'Odoslat':
session_start();
$text = (isset($_POST['text']))? $_POST['text']: '';
$nadpis = (isset($_POST['title']))? $_POST['title']: '';
$image = (isset($_FILES['uploadfile']))? imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']): '';
print_r($_FILES); // it writes Array()
if(isset($_SESSION['id']) && !empty($nadpis) && !empty($text) && $_FILES['uploadfile']['error'] == UPLOAD_ERR_OK) //here it indicates error
{
$ext = '.jpg';
$query = 'INSERT INTO articles (article_id, user_id, a_text, title, submit_date)
VALUES(NULL, '. $_SESSION['id']. ', "'. mysql_real_escape_string($text, $db). '", "'.
mysql_real_escape_string($nadpis, $db). '", "' . date('Y-m-d H:i:s'). '")';
mysql_query($query, $db) or die(mysql_error($db));
$clanok_id = mysql_insert_id($db);
$query = 'INSERT INTO foto (foto_id, article_id)
VALUES (NULL, '. $clanok_id. ')';
mysql_query($query, $db) or die(mysql_error($db));
if(!empty($image))
{
$last_id = mysql_insert_id($db);
$image_name = $last_id. $ext;
imagejpeg($image, $dir. '/'. $image_name, 100);
}
else
{
$last_id = mysql_insert_id($db);
$image_name = 'caps.jpg';
}
$priecinok = 'images/';
$place = $priecinok. $image_name;
$query = 'UPDATE foto
SET foto_path = "'. $place. '" WHERE foto_id = '. $last_id;
mysql_query($query, $db) or die(mysql_error($db));
$query = 'UPDATE articles
SET foto_id = '. $last_id. ' WHERE article_id = '. $clanok_id;
mysql_query($query, $db) or die(mysql_error($db));
$redirect = 'index.php';
}
else
{
$chyba = 'Nepodarilo sa nahrat clanok!';
$redirect = 'index.php?chyba='. $chyba;
}
break;
Please how can I repare it? I will be very grateful if somebody help me...
There are 4 things you should check in your php.ini file to make sure file uploads will work :
file_uploads : should be set to 1
upload_max_filesize : should be set to a value big enough for what you plan on uploading. You said it's set to 128 MB. Make sure it is written as '128M'.
post_max_size : should be set to a value higher than upload_max_filesize since it includes the files and the other post data
max_file_uploads : less important, but it limits the number of files you can upload at once
One of the most important apasrt from php.ini setting is ,please check whether you have permission to write in that particular folder where you are uploading the image.
Try add this in your form:
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
this value set maximum file to 100KB.

update statement with image

I have a php page with form for updating records and image I don’t know what is wrong with the update statement ,,, the values of fields are taken and I can see them on url through the GET method ... But when I run the page and update record information is not changing and nothing appear on the page ,,, since none of fields r taking the update I think my update statement having problem ,,,here is the code:
<?php
// Connect to the database
require("includes/conn.php");
// Script Variables
$target_dir = 'images/';
$file_given = false;
$inputs_given = false;
$id_given = false;
if(isset($_POST['serialid']) && $_POST['serialid'] != "")
{
$serialid = $_POST['serialid'];
$id_given = true;
}
// You only need to catch input from a create or modify action, so start by checking for ALL the REQUIRED inputs
if(isset($_POST['name']) && $_POST['name'] != "" && isset($_POST['description']) && $_POST['description'] != "" && isset($_POST['price']) && $_POST['price'] != "")
{
$name = $_POST['name'];
$paragraph = $_POST['description'];
$price = $_POST['price'];
if(isset($_POST['picture']) && $_POST['picture'] != "")
{
$picture = basename($_FILES['picture']['name']);
$file_given = true;
}
// Just some verification (not really much, but you can write your own functions and slot them in
$name_safe = true;
$description_safe = true;
$price_safe = true;
$picture_safe = false;
if($_FILES["picture"]["type"] == "image/gif" || $_FILES["picture"]["type"] == "image/jpg" || $_FILES["picture"]["type"] == "image/png" || $_FILES["picture"]["type"] == "image/bmp")
$picture_safe = true;
if($name_safe && $description_safe && $price_safe && $picture_safe)
$inputs_given = true;
}
if($id_given && $inputs_given)
{
// Search for the record and see if it exists
$get_record = mysql_query("SELECT serial, picture FROM products WHERE serial='$serialid'");
$record_exists = mysql_num_rows($get_record);
if($record_exists == 1)
{
if($file_given)
{
$update_image = ", picture='$picture'";
// Now we need to remove the old image from the file system and upload our new one in it's place
$previous_image = mysql_result($get_record,'0','picture');
unlink($target_dir . $previous_image);
//Now that the previous image has been removed, we need to upload our new image
$new_image = $target_dir . $picture ;
move_uploaded_file($_FILES['picture']['tmp_name'], $new_image);
}
else
$update_image = "";
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price', " . $update_image . " WHERE serial='$serialid'"))
$action_output = "Record successfully modified.";
else
$action_output = "Record modification unsuccessful.";
}
else
$action_output = "The record id you specified does not exist.";
}
?>
<html>
<head>
<title>Manage Records</title>
</head>
<body>
<?php echo $action_output; ?>
</body>
</html>
<?php
// Disconnect from the database
?>
Here is the url when I click the modify
http://localhost/Shopping/update.php?name=View+Sonic+LCD&description=LCD&price=250&picture=C%3A%5CDocuments+and+Settings%5Ce2565%5CMy+Documents%5CTwasul%5Ctlogo%5Cicon%5Cpic1.jpg&serialid=1
My Modify Form is this
<?php
// Connect to the database
require("includes/conn.php");
$id_given = false;
if(isset($_POST['serialid']) && $_POST['serialid'] != "")
{
$serialid = $_POST['serialid'];
$id_given = true;
}
if($id_given)
{
$get_record = mysql_query("SELECT * FROM products WHERE serial='$serialid'");
$record = mysql_fetch_array($get_record);
$output = '<form method="POST" enctype="multipart/form-data" action="update.php?serialid=' . $record['serialid'] . '&action=modify">
<table>
<tr>
<td>Name:</td>
<td><input name="name" type="text" value="' . $record['name'] . '"/></td>
</tr>
<tr>
<td>Description :</td>
<td><textarea name="description" cols="45" rows="5">' . $record['description'] . '</textarea></td>
</tr>
<tr>
<td>Price:</td>
<td><input name="price" type="text" value="' . $record['price'] . '"/></td>
</tr>
<td colspan="2"><img height="50" width="50" src="../images/' . $record['picture'] . '"/><br/>' . $record['picture'] . '</td>
</tr>
<tr>
<td>Modify Image:</td>
<td><input name="picture" type="file" value="" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Modify Record"/>
</td>
</tr>
</table>
</form>';
}
else
$output = 'No record id was specified.';
?>
<html>
<head>
<title>Modify Record</title>
</head>
<body>
<?php echo $output; ?>
</body>
</html>
<?php
// Disconnect from the database
?>
First, you have an extra comma in this line, before the WHERE :
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price', " . $update_image . " WHERE serial='$serialid'"))
The correct syntax is :
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price' " . $update_image . " WHERE serial='$serialid'"))
Then, you said
I can see them on url through the GET method
But in your script you are using $_POST variable to get values, use $_GET instead or change the method of your form to post.
If you want to upload a picture you have to use post method, the file will be available in the $_FILES variable.
In your example, you pass parameters by URL so, with the get method, and the "picture" is just the path to the picture in your PC, and it's not uploaded on the server.
EDIT :
Add "<input type='hidden' name='serialid' value='".$record['serialid']."' />" AND "<input type='hidden' name='action' value='modify' />" in your form instead of add this parameters to the action url of it, and it should work
you have added comma in $update_image = ", picture='$picture'"; as well as in
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price', " . $update_image . " WHERE serial='$serialid'"))
either remove the comma in $update_image = " picture='$picture'"; or remove in this
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price' " . $update_image . " WHERE serial='$serialid'"))'

PHP trouble using $_POST in a loop

edit - I solved my "add friend" button issue, now I'm trying to get the userid from the loop below. I want to be able to get the userid of the name that the user looks up (the name that gets submitted to findUsers function, $friend). So basically I want to be able to use result['userid'] and be able to submit that into a database.
I commented in the code where I'm having trouble getting the value for the userid to set.
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
Is there a certain way to use hidden inputs, or is the value just not being set correctly?
<?php
include_once 'config.php';
class Friends{
function addFriend($userId) {
return $userId; //this is supposed to return the value of the user's id selected in the loop below via the if statements towards the bottom.
}
function findUsers($friend){
$search = mysql_query("SELECT * from users where username='$friend'");
if (mysql_num_rows($search) > 0){
// $this->addFriend($friend);
$userLocation = mysql_query("select * from userinfo where username='$friend'");
$locationResult = mysql_fetch_array($userLocation);
$locationResultArray = $locationResult['userlocation'];
$locationExplode = explode("~","$locationResultArray");
if (mysql_num_rows($search)) {
// Table column names
echo '<table><tr><td>Username</td><td>Location</td></tr>';
while($result = mysql_fetch_array($search)) {
echo '<tr>
<td>'. $result['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>';
}
}
}
}
}
$friends = new Friends();
if (isset($_POST['userId'], $_POST['addFriend'])) {
echo "friend button pressed"; //this message is displayed
if ($friends->addFriend($_POST['userId'])) {
echo "userID set"; //this message is displayed
echo $_POST['userID']; //this is not displayed
} else {
// some error code here
}
}
// Edit this to test here
// $friends->findUsers('<username>');
?>
That way to add friend is incorrect way, because when you click the "Add friend" button, that will send a $_POST['addFriend'] and then in the loop the check are going to add all users as friend.
The correct code is here:
<?php
function addFriend($userId){
// check is 'userId' exist, if not, then return 0;
}
if (isset($_POST['userId'], $_POST['addFriend'])) {
if (addFriend($_POST['userId'])) {
// some display code here
} else {
// some error code here
}
}
while($result = mysql_fetch_array($search)) {
?>
<tr><td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="<?php echo $result['userid']; ?>" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>
<?php } ?>
EDIT1:
You can't use the code above into a function. I fixed a lot of bug that I can see in your code, but still look strange.
I don't get what you want to do with your code, but I made this:
<?php
function addFriend($userId) {
return 1; //using 1 for testing purposes
}
function findUsers($friend) {
$search = mysql_query('SELECT `userid`, `username`, `userlocation` FROM `users` JOIN `userinfo` ON `users`.`username` = `userinfo`.`username` WHERE `user`.`username` = ' . $friend);
if (mysql_num_rows($search)) {
// Table column names
echo '<table><tr><td>Username</td><td>Location</td></tr>';
while($result = mysql_fetch_array($search)) {
$locationExplode = explode('~', $result['userlocation']);
echo '<tr>
<td>'. $result['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>';
}
}
}
if (isset($_POST['userId'], $_POST['addFriend'])) {
if (addFriend($_POST['userId'])) {
echo "test"; //I'm simply trying to get the input to work, can't get it to post. Just using this for a test.
} else {
// some error code here
}
}
// Edit this to test here
// findUsers('<username>');
?>
EDIT2:
Well, you just need to put my functions code into the class and then use the other code outside the class, like this:
<?php
include_once 'config.php';
class Friends{
function addFriend($userId) {
return 1; //using 1 for testing purposes
}
function findUsers($friend) {
$search = mysql_query('SELECT `userid`, `username`, `userlocation` FROM `users` JOIN `userinfo` ON `users`.`username` = `userinfo`.`username` WHERE `user`.`username` = ' . $friend);
if (mysql_num_rows($search)) {
// Table column names
echo '<table><tr><td>Username</td><td>Location</td></tr>';
while($result = mysql_fetch_array($search)) {
$locationExplode = explode('~', $result['userlocation']);
echo '<tr>
<td>'. $result['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>';
}
}
}
}
$friends = new Friends();
if (isset($_POST['userId'], $_POST['addFriend'])) {
if ($friends->addFriend($_POST['userId'])) {
echo "test";
} else {
// some error code here
}
}
// Edit this to test here
// $friends->findUsers('<username>');
?>
EDIT3:
That's because the function addFriend is incorrect... You need to pass the user ID value as argument and then display it like this:
function addFriend($userId) {
return $userId; //this is supposed to return the value of the user's id selected in the loop below via the if statements towards the bottom.
}

Categories