Inserting a table in a database without knowing prefix - mysql

I have a small script that will insert two tables in a database, which works fine unless the user has changed the default prefix. I am wondering how I can call and use the "prefix" from the config file. Here is my code.
<?php
include("../../Config/config.php");
$link = mysql_connect($CONFIG['host'], $CONFIG['login'], $CONFIG['password'];
$db = ($CONFIG['database']);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$db", $link);
$sql = 'INSERT INTO settings '.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';
$exec = mysql_query($sql, $link);
if (!$exec) die(mysql_error());
mysql_close($link);
?>
You can see that I call "config.php" to get the database info. That would also work to get the prefix but I'm not sure how to implement the "prefix" with the rest of the code.
FYI: I'm a newbie :)
Thanks.

I got it, here's what worked.
<?php
require_once ("../../Config/config.php");
$link = mysql_connect($CONFIG['host'], $CONFIG['login'],$CONFIG['password']);
$table_prefix = ($CONFIG['prefix']);
$db = ($CONFIG['database']);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$db", $link);
$sql = 'INSERT INTO ' . $table_prefix . 'settings'.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';
$exec = mysql_query($sql, $link);
if (!$exec) die(mysql_error());
mysql_close($link);
?>
Thanks for the help BK435

Welcome!
I am assuming you can get the prefix and store it in variable. When calling your sql add this to your code ' . $TABLE_PREFIX . '. so your above insert would look something like:
$sql = 'INSERT INTO ' . $TABLE_PREFIX . 'settings '.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';

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();
?>

Warning: mysql_select_db() expects parameter 2 to be resource,

<?php
$servername = "localhost";
$username = "root";
$password = "Rachel";
$db = "hairdressingapointments";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected Sussessfully";
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
$sql = "SELECT `ApointmentDate`, `ApointmentTime` FROM `apointments` WHERE `staff_id`=1 && `quantity`>0";
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
echo $sql;
mysql_close();
?>
spent hours trying to figure this out and im guessing its something so simple. getting back the following error:
Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\wamp2\www\hairdressingapointments\TeresaApointments.php on line 15 which is,
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
You already connected to the database using
mysqli_connect(...);
So, you do not need
mysql_select_db(....);
Also change the query to this
$sql = "SELECT ApointmentDate, ApointmentTime FROM apointments WHERE staff_id=1 AND quantity>0";
If you use SQLWorkbench or SQLYog or some other tool, you can enter your SQL and make sure it is valid before adding it to your script.
Also, make sure the table name is really
apointments
and not
appointments
I got this information from php.net - mysqli_connect

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>

Having a MYSQL query within a PHP fwrite function

basically I am try to get the php file to create another php file which has XHTML, PHP and MYSQL within it. I am trying to include a MYSQL query but the problem is that the apostrophe (') that I use to start the fwrite string get confused when it reaches a MYSQL query because it too also has an apostrophe but I just want that string to continue not end. What should I do for this to work? Thanks in advance for any help.
The code (just the relevant bit):
$filename = "websites/".$firstpage.".php";
$filehandle = fopen($filename, 'w') or die("error opening file");
$datawrite = '
$query = "SELECT websitetitle FROM $weblist WHERE webID='$webID'";
$result = mysql_query ($query);
$row = mysql_fetch_array( $result );
echo $row['webID'];
';
fwrite($filehandle, $datawrite);
fclose($filehandle);
You should escape the ' in the query with \' This will not exec and end the string
$filename = "websites/".$firstpage.".php";
$filehandle = fopen($filename, 'w') or die("error opening file");
$datawrite = '
$query = "SELECT websitetitle FROM $weblist WHERE webID=\'$webID\'";
$result = mysql_query ($query);
$row = mysql_fetch_array( $result );
echo $row[\'webID\'];
';
fwrite($filehandle, $datawrite);
fclose($filehandle);
Check this out for reference
http://php.net/manual/en/language.types.string.php
Just use proper escaping and place a \ before the apostrophe.
$datawrite = '
$query = "SELECT websitetitle FROM $weblist WHERE webID=\'$webID\'";
$result = mysql_query ($query);
$row = mysql_fetch_array( $result );
echo $row[\'webID\'];
';

Blank page after attempt to insert

Whenever I try to insert data into my database 'users' I always get a blank page. It doesn't give me any errors, it doesn't include 'mainmenu.php', or return any feedback what so ever. Can someone help me out? Here is the code:
<?php
include("mainmenu.php");
$con = mysql_connect("localhost", "root", "*********");
if (!$con) {
die('Connection failure.' . mysql_error());
}
//Variable def
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$usrname = $_POST['usrname'];
$password = $_POST['password'];
mysql_select_db("users",$con) or die(mysql_error());
mysql_query("INSERT INTO data (usrname, fname, lname, password, email) VALUES ($usrname, $fname, $lname, $password, $email)") or die(mysql_error());
mysql_close($con)
echo("Thank you for registering!")
?>
It looks right to me.
don't you getting any syntax error?
first
mysql_close($con)
echo("Thank you for registering!")
change to
mysql_close($con);
echo("Thank you for registering!");
second, please quote your $_POST and escape it properly
read this - Escaping single quote in PHP when inserting into MySQL)
No errors? Add this at the top of the script:
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
First of all: Strings need delimiting:
mysql_query("INSERT INTO data (usrname, fname, lname, password, email) VALUES ('$usrname', '$fname', '$lname', '$password', '$email')";
Second: never ever pass un-checked user data into a database query. Use mysql_real_escape_string() on each value first.
mysql_query("INSERT INTO data (usrname, fname, lname, password, email) VALUES ($usrname, $fname, $lname, $password, $email)") or die(mysql_error());
Use this instead
$insert_sql = sprintf("INSERT INTO users (usrname, fname, lname, password, email) " .
"VALUES ('%s' ,'%s', '%s', '%s', %d); ",
mysqli_real_escape_string($conn, $usrname),
mysqli_real_escape_string($conn, $fname),
mysqli_real_escape_string($conn, $lname),
mysqli_real_escape_string($conn, md5($password)),
mysqli_real_escape_string($conn, $email),
mysqli_insert_id($conn));
Then Query The Above String
mysqli_query($conn, $insert_sql);
Then a Conditionals
if($insert_sql){
$usrname = $_SESSION['user_id'];
//url.ext e.g could be "home.php" or "you.html"
//header is used for redirecting a page
header("Location: url.ext");
}else{
$msg = "error inserting";
header("Location: " . $_SERVER['HTTP_REFERER'] . "?Message= ". $msg );
}