I can't access a MySQL table - mysql

I have a form to user registry. Form send dates to InsertUser.php, which is the next file:
<?php
$link = mysql_connect("localhost", "root", "");
if (!$link) {
echo("ERROR");
}
else {
if (!mysql_select_db("myfacebook", $link)) {
echo("ERROR");
}
else {
$Consulta = "insert into usuarios(Nombre,Apellidos,Nick,Contraseña,Foto) values('" . $_POST["nombre"] . "','" . $_POST["apellidos"] . "','" . $_POST["nick"] . "','" . $_POST["contraseña"] . "','PruebaFoto')";
echo $Consulta;
$resultado = mysql_query($Consulta, $link) or die("Problema al insertar los datos.");
echo($resultado);
}
}
?>
When I sending and insert data, the form returns:
"Problema al insertar los datos."
I think that function mysql_query() is the problem, but I don't know repair the problem.

Let's clean this up a bit and make it a little easier to see what's going on
<?php
$link = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("myfacebook", $link) or die(mysql_error());
$Consulta = "insert into usuarios(Nombre,Apellidos,Nick,Contraseña,Foto) values('".mysql_real_escape_string($_POST["nombre"])."','".mysql_real_escape_string($_POST["apellidos"])."','".mysql_real_escape_string($_POST["nick"])."','".mysql_real_escape_string($_POST["contraseña"])."','PruebaFoto')";
if($sql = mysql_query($Consulta)) {
echo 'success';
} else {
echo 'error';
}
You need to escape your input so you're not open to SQL injection. I used mysql_real_escape_string().
You should learn mysqli or POD instead of mysql.
I used die() in my example just to keep things clean and easy to understand.

Related

How to make reference to one of my MySQL databases inside my PHP file?

I have already asked this related question: https://webmasters.stackexchange.com/questions/116055/using-mysql-database-data-directly-into-generating-articles-for-my-website-new/116056?noredirect=1#comment154341_116056
At this point, I'm starting to understand the code syntax and project structure a little better.
But I have made my database using MySQL console. it only has a few entries so far, I wanted to try to adapt the code in Zach's example, but here is the problem I have:
The problem is, I am unsure how to get the reference to my database object? In the code sample from Zach there is variable $db, I guess this is where i need to keep a reference to my own actual database.
Here is the psuedo-code (maybe) from Zach, note: he always said to me not to copy-paste it, but I'm just trying to see how I can use it in my project.
<?php
$SQL_Query = "SELECT * FROM your_table";
$SQL_Run = mysqli_query($db, $SQL_Query);
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
?>
So my question simply at moment is: How to create the reference $db?
Your answer is the correct way to establish a connection. I want to point out that there are two ways of writing that statement. The version you found online is one way, but from our previous conversation, you can write it like this:
<?php
// Establish how to log in
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// create the database connection
$db = new mysqli($servername, $username, $password, $dbname);
// if it fails, kill the site.
if (mysqli_connect_error($db)) {
die("Connection failed: " . mysqli_connect_error($db));
}
// your first query to grab all the article data
$SQL_Query = "SELECT * FROM your_table";
// run the query
$SQL_Run = mysqli_query($db, $SQL_Query);
// while data exists (it makes sure that you have post data, otherwise nothing shows up)
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
// Close the connection
mysqli_close($db);
?>
You will notice that the connections are written like a function.
mysqli_num_rows($result);
instead of
$result->num_rows
Both do the same thing, just a personal preference. That should hopefully clear some things up from your first post :)
I have got further on and I think have answered my own question. I found it a bit tricky to research because I don't understand all the different terms and names of features/api/scripts/etc. But I had just to read the documentation for mysqli_connect(), I set up the code as follows and now I have pulled all the data from the database into words on my html/php files.
From here I think I can rewrite the code to first sort it by date and then can of course put the latest posts at the top of each page etc.
I can also allow the user to click 'Genre' and only view Comedy for example.
Here is the code just to get the data parsed into my index.php file:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, type, title FROM releases";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Type: " . $row["type"]. " - Title " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I extended upon the above work by making the php script fetch all the entries in the database and create the previous html article I had once for each entry. In the SELECT statement I can control which types of entries are displayed (eg. For a certain category). Here was how I did it:
// make an html article based snippet (image, title, description, etc),
//once for each entry in the database table...
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "somepassword";
$dbname = "somedatabasename";
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM releases ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo '<section class="wrapper style1">';
echo '<div class="inner">';
echo '<header class="align-center">';
echo '<h2>'. $row["title"] . '</h2>';
echo '<div class="image fit">';
echo '<img src='. $row["imgurl"] .'>';
echo '</div> <p> RELEASE TITLE: ' . $row["title"] . '<br /> DATE POSTED: ' . $row["postdate"] . '<br /> DESCRIPTION: ' . $row["description"] . '</p>';
echo 'DOWNLOAD LINK: '.$row["link"].' <br />';
$NfoLink = $row["nfolink"];
if ($NfoLink != 'not found' && $NfoLink != '')
{
echo 'NFO LINK/MORE DOWNLOADS: '.$row["nfolink"].'';
}
echo '</header>';
echo '</div>';
echo '</section>';
}
}
else
{
echo "0 results";
}
$conn->close();
?>

Auto delete from SQL database

What can I add to this to make the record delete automatically after the endate has passed? I would like to post to automatically delete from the database after the endate has passed.
<?php
require "../login/config.php";
$host='';
$db = 'db';
$dbuser = 'dbo';
$dbpass = '';
$conn = mysql_connect($host, $dbuser, $dbpass,$db);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db');
if(isset($_POST['submit'])) {
$name=$_POST["element_1"];
$stdatemm=$_POST["element_2_1"];
$stdatedd=$_POST["element_2_2"];
$stdateyy=$_POST["element_2_3"];
$endatemm=$_POST["element_3_1"];
$endatedd=$_POST["element_3_2"];
$endateyy=$_POST["element_3_3"];
$stdate=$stdatemm."/".$stdatedd."/".$stdateyy;
$endate=$endatemm."/".$endatedd."/".$endateyy;
$user=$_POST["postuser"];
$query = "INSERT INTO (fname,stdate,endate,addr1,addr2,city,state,zip,name,size,type,content,link,description,user) VALUES('" . mysql_real_escape_string($name) . "','$stdate','$endate','" . mysql_real_escape_string($staddr) . "','" . mysql_real_escape_string($addr2) . "','$city','$state','$zip','" . mysql_real_escape_string($fileName) . "','$fileSize','$fileType','" . mysql_real_escape_string($content) . "','$_POST[element_7]','" . mysql_real_escape_string($desc) . "','$user')";
} } } else
$query = "INSERT INTO (fname,stdate,endate,addr1,addr2,city,state,zip,name,size,type,content,link,description,user) VALUES('" . mysql_real_escape_string($name) . "','$stdate','$endate','" . mysql_real_escape_string($staddr) . "','" . mysql_real_escape_string($addr2) . "','$city','$state','$zip',' ','0',' ',' ','$_POST[element_7]','" . mysql_real_escape_string($desc) . "','$user')";
$q2=mysql_query($query) or die('Error, query failed'. mysql_error());
if($q2) {
echo ""; } else {
echo "error";
}
?>
There is no way to "automatically delete records". What you could do however includes:
cause all of your queries to disregard rows that have surpassed their end date.
Create a scheduled task/job that runs on an interval that removes records that have surpassed their end date
Write a trigger to check for outdated records to remove which could fire prior to select, update, and deletes.

How to add insert into and log on pdo

I have an sql to add over 100 field to mysql database. I want to include coding for PDO to avoid this sql injection thing but, i'm new to all of this and really I do not know how nor truly understand it. Any help would be greatly appreciated. My form has over 100 fields. I have no knowledge of how to do this. Thank you in advance.
Here's the code.
<html>
<body>
<?php
>if (isset($_POST['submit'])){
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "hostname";
$username = "username";
$password = "password";
$dbname = "dbname";
$mystuff = array( "tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state");
$sql_values=array();
foreach($mystuff as $fieldname) {
/* do validation! */
$sql_values[$fieldname] = "'" . mysql_real_excape_stiring($_POST[$fieldname]) . "'";
}
$con = mysql_connect("$hostname","$username","$password");
if (!$con){
die ("Can not connect:" . mysql_error());
}
mysql_select_db("dbname",$con);
$sql = "INSERT INTO dbname (".implode(',', $mystuff).") VALUES (" . implode(',', $sql_values) . ")";
mysql_query($sql,$con);
mysql_close($con);
}
foreach($mystuff as $fieldname) {
echo "...an input field...";
}
?>
</body>

MySQL update isn't updating

<?php
require("header.inc.php");
?>
<?php
if (isLoggedIn()) {
if (isset($_POST['CKey_Button'])) {
if (!isset($_POST['CKey'])) {
die("Error: The Character Key field was not set.");
}
}
$CKey = $_POST['CKey_Button'];
mysql_select_db("samp");
$query = mysql_query("SELECT `id` FROM `players` WHERE `CharacterKey` = '" . mysql_real_escape_string($_POST['CKey']) . "' LIMIT 1");
if (mysql_num_rows($query)) {
mysql_select_db("ucp");
mysql_query("UPDATE `users` SET `CharacterID` = '" . $CKey . "' WHERE `name` = '" . $user['name'] . "'");
header("./Dashboard.php");
exit;
}
else {
header("./index.php");
exit;
}
}
else {
header("./index.php");
exit;
}
?>
That is the code but it isn't updating and it just a blank screen, does anyone know why this could be happening(I have just started coding php so be nice if it's a newbie error).
EDIT: I have fixed it I was using $CKey as the button and not the actual key, hope this makes sense, I also changed = '" . $CKey . "' to = " . $CKey
Use mysql_error() to see if there is any error in your query
mysql_query($query) or die ('Error updating database: '.mysql_error());

I was looking to see if someone could tell me how secure this is

I am writing a code that will check 2 different tables to determine the privileges the user will have. The code looks like this:
$query1 = ("SELECT 1 FROM `customers` WHERE `Email` = '$email' AND `Password` = '$password'");
$query2 = ("SELECT 1 FROM `admins` WHERE `Email` = '$email' AND `Password` = '$password'");
$result1 = mysql_query($query1) or die(mysql_error());
$result2 = mysql_query($query2) or die(mysql_error());
if (mysql_num_rows($result1) == 1) {
// Log user in as a Customer
exit;
} else if (mysql_num_rows($result2) == 1) {
// Log user in as an Admin.
exit;
} else {
// Direct user to registration page.
}
Can anyone look at this and tell me if there would be any security risk by doing it this way? Thank you in advance for your help!
Firstly you have a change that your code is only known by you.
Secondly you have to check the input data. email and password area is not safety. You should prevent SQL injection. Otherwise your code is not secure.
By the way i'm offering you IP restricted login for admins. I'm using this. And it is more secure.
One big problem here is that the code is vulnerable for sql injections.
Which basicly means that the user could put code in the email or password form to bypass the check you have here.
A start would be to perform the following to your input BEFORE you use them in your query:
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
Though, the mysql library is not recommended by php, rather read about prepared statements in pdo here: http://www.php.net/manual/en/ref.pdo-mysql.php
But you can try the mysql_real_escape_string to have a first security measure against sql injections.
This is insecure if for example my password was
OR 1=1
I get access. Use mysql prepared statements
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("SELECT 1 FROM customers WHERE Email = (?) AND Password = (?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("ss", $email, $password)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>