Saving Each Token in Separate row in Database - mysql

I am trying to save each string token in separate row in database, so that i can compare it with other string Tokens.
I am using PHP explode function and my syntax is:
<?php
$someWords = "Please don't, blow me to pieces.";
$wordChunks = explode(" ", $someWords);
for($i = 0; $i < count($wordChunks); $i++){
echo "Piece $i = $wordChunks[$i] <br />";
$con = mysqli_connect("localhost","","","test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO TableName (file1) VALUES ('$wordChunks')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added successfully";
mysqli_close($con);
}
?>
It gives this output
And i want this output
[

Use the MySQL mysqli_real_escape_string function to escape the string before including it in the query:
$sql = 'INSERT INTO TableName (file1) VALUES ('.mysqli_real_escape_string($wordChunks[$i]).')';

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

Getting data from database using part of the URL as a value - PHP

My url type is like "http://localhost/boardgame/profile/Duncan/" the last word is the user name...
I just try to get some data from database and I need a user name to do this. I tried to get it from page URL but it doesn't work. Where did I go wrong? What has to be done? I'll be greateful if anybody can help...
<?php
$actual_link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//echo $actual_link;
$rest = substr($actual_link, 35, -1);
echo $rest;
$link = mysqli_connect("localhost", "root", "", "bgt");
if (mysqli_connect_error()) {
die ("Veritabanı bağlantısında hata var");
} if (($rest) !="") {
if (get_current_user_id($link) == '0') {
echo "<p>Kullanıcının koleksiyonunu görebilmek için giriş yapmanız
gerekiyor.</p>";
} else {
$query = "SELECT TITLE FROM wp_user_collections WHERE `user_name` =
'".mysqli_real_escape_string($link, $rest)."'";
echo "<div><h1>'".mysqli_real_escape_string($link, $rest)."'in
Koleksiyonu</h1><div>";
if($result = mysqli_query($link, $query)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>Oyun Adı</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>'" . $row['TITLE'] . "'</td>";
echo "</tr>";
}
echo "</table></div>";
}
}
}
} else {
echo "Kullanıcının koleksiyonunu görebilmek için <a
href='http://localhost/boardgame/profile/'".mysqli_real_escape_string($link,
$rest)."'>tıklayınız</a>";
}
?>
Here is the solution I have thought...using array then extracting the last element (or second last since there is a trailing '/' slash which is a delimiter)
$uri="http://localhost/boardgame/profile/Duncan/";
$uriParts=explode('/', $uri); //converts the uri string into an array of words separated by forward slash
$name=$uriParts[sizeOf($uriParts)-1-1]; //the user name comes from 2nd last item as the last item is empty
echo $name;
I could suggest you use Regular Expression to extract the user name, however I'm not well versed with it yet.

using mysqli instead of mysql accessing the DB

please find below a script in php that that fetch data from my database company, the database is in phpMyadmin
I understand that there are secure ways to fetch data. My question is
Can I improve the code below using mysqli to fetch instead of mysql_query.
<?php
get results from database. Can I improve the code below using mysqli to fetch instead of mysql_query in the following line?.
$result = mysql_query("SELECT * FROM customer")
or die(mysql_error());
tables begins here with the customer id and customer name
echo "<table >";
echo "<tr>
<th>ID</th> the customer id
<th>Name</th> the customer name
</tr>";
// loop through results of database query, displaying them in the table
the table below display the columns in html using mysql fetch array. all data is displayed.
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
my purpose is embed the php in html in another way using msqli
echo "<tr>";
echo '<td>' . $row['CustomerID'].'</td>';
echo '<td>' . $row['Name']. '</td>';
echo "</tr>";
}
echo "</table>";
?>
my purpose is embed the php in html in another way using msqli
Just replace all the mysql with mysqli
$result = mysqli_query("SELECT * FROM customer");
while($row = mysqli_fetch_array( $result )) {
If you wanna keep it simple
Or do it like this...
/*Your connection info goes here...*/
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM customer";
if ($result = $mysqli->query($query)) {
echo "<table ><tr><th>ID</th><th>Name</th></tr>";
/* fetch results by row */
while ($row = $result->fetch_row()) {
echo "<tr><td>' . $row['CustomerID'].'</td><td>' . $row['Name']. '</td></tr>';
}
/* free the result set */
$result->close();
}
/* close the connection */
$mysqli->close();

Can I construct a php page to run a query check against 30 mysql databases?

I host at hostgator and have about 30 mysql databases (all different websites that sit on the same server). For the last year.. no problems and suddenly, the last 2 days, I've seen 5 - 10 of these databases marked as 'crashed' and they return no results... so my websites display no info. I have to run a "repair table mytable" to fix these and then they work great again.
Instead of logging in to go through the databases 1 by 1 every morning, is there a way I could setup a php page to connect to all 30 databases and run a simple select statement.. and if it works, return
"database db1 is working"
"database db2 is working"
and then when not working, return
"no reply from db3"
....or something similar?
Thanks!
There's no reason you couldn't have a script that lists all of your databasenames and login credentials, and try to connect in turn to each:
$logins = array(
array('dbname' => 'blah', 'user' => 'username1', 'password' => 'password1'),
array('dbname' => 'yuck', ....)
...
);
$failures = array();
foreach ($logins as $login) {
$con = mysql_connect('servername', $login['user'], $login['password']);
if (!$con) {
$failures[] = $login['dbname'] . " failed with " . mysql_error();
continue;
}
$result = mysql_select_db($login['dbname']);
if (!$result) {
$failures[] = "Failed to select " . $login['dbname'] . ": " . mysql_error();
continue;
}
$result = mysql_query("SELECT something FROM sometable");
if (!$result) {
$failures[] = "Faile to select from " . $login['dbname'] . ": " . mysql_error();
continue;
}
if (mysql_num_rows($result) != $some_expected_value) {
$failures[] = "Got incorrect rowcount " . mysql_num_rows($result) . " on " . $login['dbname'];
}
etc....
mysql_close();
}
if (count($failures) > 0) {
echo "Failures found: "
print_r($failures);
}
You should be able to do something like the following:
<?php
//connect to database
mysql_connect('database','user','password');
//get all database names
$result = mysql_query("show databases;");
//iterate over all databases returned from 'show databases' query
while($row = mysql_fetch_array($result)) {
//DB name is returned in the result set's first element. select that DB
mysql_selectdb($row[0]);
//get all tables in the database
$query = "show tables;";
$result2 = mysql_query($query);
echo "Query: (".$row[0].")$query\n";
echo mysql_error();
//iterate over all tables in the current database
while($row2 = mysql_fetch_array($result2)) {
//the first element of the returned array will always be the table name, so:
$query = "select * from ".$row2[0]." where 1=1;";
$result3 = mysql_query($query);
echo "Query:\t(".$row[0].'/'.$row2[0].")$query\n";
//If mysql_query returns false (i.e., $result3 is false), that means that
// the table is damaged
if(!$result3) {
echo "***Error on table '".$row2[0]."' *** ... Fixing...";
//So, we repair the table
mysql_query("repair table ".$row2[0].";");
}
}
}
?>

Insert into mysql

I want to pass parameters to a batch file which will then inserted into mysql database.
lunch.bat name surname
echo off
mysql -uusername -ppassword -e "set #1:=name; set #2:=surname; source insert.sql;"
In insert.sql
insert into mytable(namecol,surnamecol) values(#1,#2);
Someone can help me in writing both scripts?
Thanks
Added single quotes to handle string input... still wobly if quotes are supplied in the paramaters
#echo off
mysql -uusername -ppassword -e "set #1:='%1'; set #2:='%2'; source insert.sql;"
Done!
Here is a piece of my code that I been working on, although it post to database every time you visit the page. I've tried to add "unique key" with rand() in database. But the code still grabs "rand() on page" and post without "Submit" from form. Anyways this is how I insert data to Mysql. My database creates time and day timestamp() & order by "id."
// Select from database working
$statement = $database->prepare('SELECT * FROM pressroom ORDER BY id
DESC
LIMIT 0 , 30' );
$statement->execute();
$count = $statement->rowCount();
if( $count > 0 ) {
$R = $statement->fetchAll( PDO::FETCH_ASSOC );
for( $x = 0; $x < count($R); $x++ ) {
echo "<td><br>";
echo "<center><b>" . $R[ $x ]['name'] . "</th>";
echo ": <left></b>" . $R[ $x ]['comment'] . "</th>";
echo "<center>" . $R[ $x ]['date'] . "<hr></td>";
echo "</tr>";
}
}
// Make sure that the 'values' are in the same order or as
your table
$query = "INSERT INTO pressroom(first_name, last_name, Password )
VALUES ('table1','table2','table3')";
//connection prepare
try {
$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$results = $database->query($query);
//Prints results that are added to table
print_r($results);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}