How can I connect my php code to MySQL database? - sql

How can I connect my php code to MySQL database?
I have tried many times and it cannot access the database.
These are the codes in my php file:
<html>
<head>
<title>Brandon's Search Engine - Results</title>
</head>
<body>
<h2>Brandon's Search Engine</h2>
<form action='./search.php' method='get'>
<input type='text' name='k' size='80' value='<?php echo $_GET['k']; ?>' />
<input type='submit' value='Search' >
</form>
<hr />
<?php
$k = $_GET['k'];
$terms = explode(" ", $k);
$query = "SELECT * FROM search WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
// connect
mysql_connect("sql102.freezoy.com", "frzoy_13854016", "xxxx");
mysql_select_db("frzoy_13854016_search");
$query = mysql_query($query);
$numrows = $query->num_rows;
if ($numrows > 0){
while ($row = mysql_fetch_assoc($query)){
$id = $row('id');
$title = $row('title');
$description = $row('description');
$keywords = $row('keywords');
$link = $row('link');
echo "<h2><a href='$link'>$title</a></h2>
$description<br /><br />";
}
}
else
echo"No results found for \"<b>$k</b>\"";
// disconnect
mysql_close();
?>
</body>
</html>
I have insert some data into the database.
Please help. Thanks in advance.

Related

Converting Pdo OOP To Mysqli Procedural

Folks, :)
My 3+ pages are all in mysqli procedural. I cannot just switch to pdo and oop and throw 6 mnths of work down the drain! And so, let's try converting the following code suggestion by another to mysqli procedural.
I really need the following code converted to mysqli procedural from pdo oop. Once that is done, my 7 months project will come to an end. And, I can move-on to learning pdo. Right now, can't afford to jump into pdo without finishing my current project.
So, who will help me convert ? Other newbies would learn from your conversion.
Thanks!
[code]
/*
ERROR HANDLING
*/
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include 'config.php';
// check if user is already logged in
if (is_logged() === true)
{
//Redirect user to homepage page after 5 seconds.
header("refresh:2;url=home.php");
exit; //
}
if (
array_key_exists('login_username_or_email', $_POST) &&
array_key_exists('login_password' , $_POST)
) {
$usernameoremail = trim($_POST["login_username_or_email"]); //
$password = $_POST["login_password"];
// don't bother trimming, they can't enter it right, don't let them log
in!
$stmt = $conn->prepare('SELECT ids, usernames, passwords, emails,
accounts_activations_statuses
FROM users WHERE ' . (
strpos($usernameoremail, '#') === false) ? 'usernames' : 'emails'
) . ' = ?
');
$stmt->bind_param('s', $_POST['login_username_or_email']);
$stmt->execute();
$stmt->bind_result(
$db_id, $db_username, $db_password, $db_email,
$db_account_activation_status
);
if (
$stmt->fetch() &&
password_verify($_POST['login_password'], $db_password)
) {
echo '
<p>Login Successful</p>
<dl>
<dt>User Id</dt>
<dd>', $db_id, '</dd>
<dt>E-Mail</dt>
<dd>', $db_email, '</dd>
<dt>Username</dt>
<dd>', $db_username, '</dd>
<dt>Activation Stats</dt>
<dd>', $db_account_activation_status, '</dd>
</dl>
';
} else echo '<p>Invalid username or password</p>';
$stmt->close();
} else echo '<p>Missing username or password</p>';
?>
<!DOCTYPE html>
<html>
<head>
<title><?php $site_name?> Member Login Page</title>
<meta charset="utf-8">
</head>
<body>
<div class = "container">
<form method="post" action="">
<h3><?= $site_name ?> Member Login Form</h3>
<fieldset>
<label for="login_name">Username/Email:</label>
<input type="text" name="login_username_or_email" id="login_name">
<br>
<label for="login_pass">Password:</label>
<input type="password" name="login_password" id="login_pass">
</fieldset>
<div class="submitsAndHiddens">
<button type="submit">Login</button><br>
Forgot your Password?<br>
Register New Account
</div>
</form>
</div>
</body>
[/code]

Variable changable

Hello guys I have a query that need a variable to be executed but that variable is returned by a select on a form
$obtermaxcampo = "SELECT P$pagina as maxcampo FROM slider_settings where ID = $ID";
if I define $pagina = 1 it only query me the P1 and I have 12 P's.
My question is if theres any way to start the variable in 1 but after submit delete that definition and give him a $pagina = $_POST['selectedPagina'];
here is the selected form
<form action="" method="POST" name="carregarinfo">
<label>Pagina</label>
<select name ="selectedPagina" id="selected" >
<?php for ($k = 1; $k <= $result['max']; $k++){?>
<option value ="<?php echo $k;?>" <?php if($_POST['selectedPagina'] == $k){echo "selected='$k'"; }?>><?php echo $k;?></option>
<?php
}
?>
</select>
<label>Campo</label>
<select name ="selectedCampo" id="selected" >
<?php for ($z = 1; $z <= $resultmaxcampo['maxcampo']; $z++){?>
<option value ="<?php echo $z;?>"><?php echo $z;?></option>
<?php
}
?>
</select>
<input type="submit" name="carregar" id="carregar" value="Carregar">
</form>
if(isset($_POST['carregar'])){
$sql = "SELECT tituloP$pagina as titulopag, Butao, Titulo, Texto FROM slider_settings, slider_config where slider_settings.ID = $ID and slider_config.P_NUM = $pagina and slider_config.Campo = $campo and slider_config.ID = $ID";
$sqlconnect = $connect->query($sql);
$sqlresult = $sqlconnect->fetch_assoc();
$pagina = $_POST['selectedPagina'];
$obtermaxcampo = "SELECT P$pagina as maxcampo FROM slider_settings where ID = $ID";
$connectionmaxcampo = $connect->query($obtermaxcampo);
$resultmaxcampo = $connectionmaxcampo ->fetch_assoc();
}

Joomla 3.3 MVC file/pdf upload in custom component backend

I want to upload a pdf from a custom component from backend in the edit mode.
the state now is,
1.- either the pdf is uploaded correctly but the file name is not written in the database,
2.- or the file name is written in the data base, but the pdf is not seen by JFactory::getApplication()->input;
I found out is has with enctype="multipart/form-data" to do.
In case 1.- enctype="multipart/form-data" is in and the pdf is uploaded
in case 2.- the pdf file name is written in the data base.
What to do know ? I need both, of course.
Here so code, it is a little component com_job with MVC structure under Joomla! 3.3:
here just the part file administrator/components/com_job/views/tmpl/edit.php
with the enctype="multipart/form-data"
<form method="post" action="<?php echo JRoute::_('index.php?option=com_job&layout=edit&id='.(int) $this->item->id); ?>" id="adminForm" name="adminForm" enctype="multipart/form-data">
<fieldset class="adminform">
<legend><?php echo JText::_( 'Details' ); ?></legend>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('title'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('title'); ?>
</div>
</div>
....
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('upload_pdf'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('upload_pdf'); ?>
</div>
</div>
........
here a part of the xml file administrator/components/com_job/models/forms/job.xml
<?xml version="1.0" encoding="utf-8"?>
...
<field
id="title"
name="title"
type="text"
required="true"
label="Title"
description="title_Desc"
class="inputbox"
size="40"/>
<field
id="upload_pdf"
name="upload_pdf"
type="file"
required="false"
label="Upload_pdf"
description="upload_pdf_Desc"
class="inputbox"
size="40"
accept="application/pdf"/>
.....
here the controller administrator/components/com_job/controllers/job.php
jimport('joomla.application.component.controlleradmin');
jimport('joomla.application.component.controllerform');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
class JobControllerJob extends JControllerForm
{
public function save()
{
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform', null);
$files['upload_pdf']['name'] = JFile::makeSafe($files['upload_pdf']['name']);
if (!empty($files['upload_pdf']['name'])) {
$pdf_path = JPATH_ROOT . '/images/upload_pdf';
if (!JFolder::exists($pdf_path)) {
$status = JFolder::create($pdf_path);
if (!$status) {
JError::raiseWarning(100, JText::_('could not create directory pdf'), '');
}
}
$file_path = JPath::clean($pdf_path . '/' . strtolower($files['upload_pdf']['name']));
$status = JFile::upload($files['upload_pdf']['tmp_name'], $file_path);
if (!$status) {
JError::raiseWarning(100, JText::_('could not copy pdf'), '');
}
}
return parent::save();
}
}
where is the error ? I tried to put enctype="multipart/form-data" in the form in job.xml (models), but it didn't work.
I found a temporally solution, in the save function in the controller, I add this code:
//$jform = $jinput->get(jform, null);
$pdf_filename = JFile::makeSafe($files['upload_pdf']['name']);
$jform = $_POST['jform'];
$tmp_pdf_filename = array('upload_pdf' => $pdf_filename);
$merged_jform = array_merge($jform,$tmp_pdf_filename);
$jinput->post->set('jform',$merged_jform);
the first line with $jinput didn't work. I tried many ways with $jinput, but nothing worked. So finally I used directly $_POST. Of course, it is not the right way, but at least it works.
here the full function save:
public function save()
{
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform', null);
$pdf_filename = JFile::makeSafe($files['upload_pdf']['name']);
if (!empty($pdf_filename)) {
$pdf_path = JPATH_ROOT . '/images/upload_pdf';
if (!JFolder::exists($pdf_path)) {
$status = JFolder::create($pdf_path);
if (!$status) {
JError::raiseWarning(100, JText::_('could not create directory pdf'), '');
}
}
$file_path = JPath::clean($pdf_path . '/' . strtolower($files['upload_pdf']['name']));
$status = JFile::upload($files['upload_pdf']['tmp_name'], $file_path);
if ($status) {
//$jform = $jinput->get(jform, null);
$jform = $_POST['jform'];
$tmp_pdf_filename = array('upload_pdf' => $pdf_filename);
$merged_jform = array_merge($jform,$tmp_pdf_filename);
$jinput->post->set('jform',$merged_jform);
} else {
JError::raiseWarning(100, JText::_('could not copy pdf'), '');
}
}
return parent::save();
}
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform');
$file = $files['upload_pdf'];
Try this...it is true method!!!
That should do the trick. The $file array then holds the following keys:
error
name
size
tmp_name
type

Get Drop Down Menu, PHP SQL HTML

I am a student and also working in my university. I am not studying computer science.
I mainly do support stuff, but now I should take care of our internship database.
Task: Create a drop down menu from a town which a student choses, then show all internships in this town.
I have an existing SQL database, can create a drop down menu from it, but have NO idea how I can use the selected value. A submit button would be fine, any solution which works is fine.
How can I put the chosen value from drop down menu to a PHP variable?
<?php
$dbanfrage = "SELECT DISTINCT Stadt FROM $tabelle WHERE Land = 'China' OR Land = 'Taiwan' OR Land = 'VR China' ORDER BY STADT ";
$result = mysql_db_query ($dbname, $dbanfrage, $dbverbindung);
if (!$result)
{
$message = 'Ungültige Abfrage: ' . mysql_error() . "\n";
$message .= 'Gesamte Abfrage: ' . $dbanfrage;
die($message);
}
echo "<select>";
echo "<option>Stadt auswählen</option>"; // printing the list box select command
while($nt = mysql_fetch_array($result)) //Array or records stored in $nt
{
echo "<option value = $nt[id]>$nt[Stadt]</option>"; /* Option values are added by looping through the array */
}
echo "</select>"; // Closing of list box
mysql_close ($dbverbindung);
?>
Just suggesting how you can do it --
<select name="country" id="country" onChange="showState();" >
<option value="">Select Country</option>
<option value="1">India</option>
<option value="2">Nepal</option>
</select>
Your Script--
<script type="text/javascript">
function showState( )
{
var value = document.getElementById('country').value;
var url = '<?php echo base_url ?>showstate.php';
$.ajax({
type: "GET",
url: url,
data:{'country':value},
success:function(results)
{
$('#div_state').html(results);
}
});
}
</script>
Your showstate.php php page --
//INCLUDE CONNECTION file to for db query
$type = $_GET['country'];
//Your DB QUERIES
This will load the content in your #div_state div. You can also use Jquery For this..i think this will help you :) an d let me know if you have any query.
<select name="name">
<option value="select">select</option>
<?php
$dbanfragee=mysql_query("SELECT DISTINCT Stadt FROM $tabelle WHERE Land = 'China' OR Land = 'Taiwan' OR Land = 'VR China' ORDER BY STADT ");
while($row=mysql_fetch_array($$dbanfrage)){?>
<option value="<?=$row['id']?>"><?=$row['stadt']?></option>
<?php }?>
</select>

How to get include preg_match_all results in header location?

I have the following function written in function.php in a wordpress theme
function get_mms($my_post) {
$post_id = $my_post; //$_GET["p"];
$queried_post = get_post($post_id);
$title = $queried_post->post_title;
preg_match_all('#\[mms\](.+)\[\/mms\]#', $queried_post->post_content, $matches);
echo 'EN: ' . $matches[1][0];
echo '<br><br><form action= " ' . get_permalink( $id ) . ' " method="post">
Numar: <input type="text" name="fname" />
<input name="submito" type="submit" />
</form>';
$numero = $_POST["fname"];
if(isset($_POST['submito'])&& $_POST['fname']){
$numero = $_POST["fname"];
header("Location: http://server/&to=$numero&text='.$matches[1][0].'&from=Moldcell");
}
When I submit the form instead of getting the value of $matches[1][0] I get Array[0].
Is there someting I did wrong? What can I do to make it grab the value of preg_match_all results?