insert into phpMyAdmin - loop array - php

sorry, im a beginner. Still learning the basics of php.
Here is where i'm stuck. I'm using php to get the results and sending the results onto the database(phpMyAdmin).
I've set up a loop to get the results
i'm trying to get the above results to be sent to phpMyAdmin. i cannot work out on how to do it. I guess i need INSERT INTO somewhere inside the loop so that it can send each into phpMyAdmin There are about 10 different questions. they are displayed on the php but do not know where to go ahead from here
thanks for your help :)
edit
Thanks for the guide, I cannot seem to work out where mysql_query will go inside the loop.
mysql_query("INSERT INTO.......

Assuming u have connected to DB and has a proper table in the DB*.I am just modifying your code* so make sure about the value of $_POST['something'] and the way it should behave.
$con=mysqli_connect("localhost","username","password","dbname") or
die("Error " . mysqli_error($con));
if (isset($_POST['something']))
{
foreach ($_POST['something'] as $key => $value)
{
echo 'something #' . $key . ' You gave it ' . $value . '<br>';
$a="insert into tablename(columnname) values('$value')";
$b=mysqli_query($con,$a);
}
}
else
{
echo 'no options selected';
}

To connect to a database, you need to use the PHP mysqli_* functions. You can find more informations on the PHP online manual.
You can also use PDO (PHP Data Objects). Here's the link to a very good tutorial : http://www.phpeveryday.com/articles/PHP-Data-Object/PDO-Tutorial-P842.html
Both ways are valid and secure.

Related

cant retrieve data from mysql db with php

Sorry for my bad English,
I cant retrieve record from mysql database, there's no error messages and nothing showing. The things is I want to retrieve data on a page with session using external php file. My table has data on it, I've inserted it with phpmyadmin. Here's the code :
UPDATE
I only work on php file now, and here the konek.php
<?php
error_reporting(E_ALL);
$konek=new mysqli('localhost','root','zxcvbnm','jumat') or die(mysqli_connect_error);
$selek=mysqli_query($konek,'select * from kategori');
while($baris=mysqli_fetch_array($selek)){
echo $baris['kodekat'].' '.$baris['namakat'];
echo '<br>';
}
if($konek){
echo 'koneksi ok';
}
$konek->close();
?>
it only shows the 'koneksi ok' word, is the while not processed?
thank you in advance
What are you trying to do with this line:
if($i<=mysql_fetch_array($selek)){
If you are trying to compare with the no. of data use:
if($i<=mysql_num_rows($selek)){
From personal experience, I had trouble with this traditional MySQL api.
I'll share this small PDO tutorial that got me over this mess, hope this helps you as much as it helped me.
http://code.tutsplus.com/tutorials/php-database-access-are-you-doing-it-correctly--net-25338
Try this:
<?php
$konek=mysqli_connect("localhost","root","zxcvbnm","jumat") or die(mysqli_error());
$selek=mysqli_query($konek,"select kodekat,namakat from kategori");
$i=0;
if(mysqli_num_rows($selek) > 0 ){
while($baris = mysqli_fetch_array($selek)){
$id = $baris["kodekat"];
$nmk = $baris["namakat"];
echo"kode: ".$id."nama:".$nmk.'<br/>';
}
}else{
echo 'No items in database';
}
mysqli_close($konek);
?>
I know the problem.
Yhe problem is, my database is empty, I'm so forgetfull, :)
sorry for the inconvenience, I'm sorry I'm sorry,
the code is fine, all of them, :)
and all of answers above, I'm sure it works,
its my faults, that's my database was empty in the first place,

How do I use Google Charts with mySQL data?

I'm working on a website that stores information in databases using mysql. I want to display that information using interactive diagrams via google charts. The problem is that I cant figure out how to use the mysql data with google charts. I did some research and found that I need to encode the data in JSON format but I'm not sure as to how I can do that. Any help would be greatly appreciated.
Thanks.
(one method - there are probably many)
Use php to create the JSON strings from your query and pass these to google charts on the client.
(pcode)
<?php
$rows = PDO->query( "select col0, col1 from table" );
echo "jsonvar = {";
foreach( $rows as $row )
{
echo "{" . $row->col0 . "," . $row->col1 . "},";
}
echo "};";
?>
// some call to google charts on the client
gchart.make_a_cool_graph( jsonvar, otherparams,... );

Need help saving the answer from a Select into Database

Hi there;
I need some help; I need to save the answer from a select into my database. I do not know where I went wrong. Here is some details regarding my code.
I have a database named 'lib'
The table is named 'games'
I need to save the following into the table; 1) Game (all the words) and 2) Type
It is for a tournament website. So that I can make it available on the LAN via XAMPP.
Here is my code.
http://pastebin.com/iP7MCMzJ
Thanks in advance!
UPDATE:
Thanks for all the help! I have found and fixed my problem! In my database the VARCHAR was limited to 50 characters. I have fixed that. Now all is good :)
Thanks once again!
Well, you're not showing any code but this is how I'd expect it to work based on your description:
Your HTML will want to look something like:
<?php echo '<option name="game" value="' . htmlentities($game) . '">' . $row['game'] . '</option>'; ?>
Notice the name attribute? Also, I changed the way the HTML was written as yours was very tough to read.
PHP
if(isset($_POST['game']) && isset($_POST['type'])){
$game = $_POST['game'];
$type = $_POST['type'];
// PLEASE CLEAN YOUR INPUT PRIOR TO INSERTING THIS DATA!
Insert into games (Game, Type) VALUES ($game, $type)
}
else{
echo( "error getting info");
}

delete a row from my sql table

I'm still new to php and working my way around it but i'm stuck at the following piece:
code for deleting a row in my table
i have a link directing towards this piece of my script. i run through the first half just fine but when i press on submit and try to execute my delete query it won't go to my second if statement let alone get to the delete query.
$pgd is the page id
my hunch is there is problem with the action in the form i'm building after my while statement
forgive me for the wierd formatting of my msg but its 2am and very tired, i promise to format my questions in the future better! any help is appreciated
edit: ok other then the obvious mistake of missing method=post #.#;
edit:
hey everyone,
first of all, i'd like to thank everyone for their response.
i just started coding in php last weekend so forgive my messy codes. the code is still running locally and my main goal was to finish the functions and then work on securing my code.
now back to the issue, i'm sorry if i was vague about my problem. i'll try to reiterate it.
my issue isn´t selecting an item i want to delete, the issue is that it won´t get to the 2nd if statement.
Re-edit:
this time with my current code:
if($_GET['delete'] == "y")
{
//content hier verwijderen
$sqlcont1="SELECT * FROM content where id ='".$_GET['id']."'";
echo $sqlcont1;
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while($rowcont1= mysql_fetch_array($resultcont1)){
echo '<form class="niceforms" action="?pg='.$pgd.'&delete=y&remove=y&id='.$_GET['id'].'" method="post">';
echo '<h1>'.$rowcont1['Titel'].'</h1>';
echo '<p>'.$rowcont1['Content'].'</p>';
echo '<input type="submit" value="Delete article">';
echo '</form>';
}
if($_GET['remove']=="y"){
echo 'rararara';
$id=$_GET['id'];
$sqlrem="DELETE FROM content WHERE id="$id;
echo $sqlrem;
mysql_query($sqlrem);
}
}
echoing $sqlrem gives me the following now:
DELETE FROM content WHERE id=8
that being my current code, i get in to the second IF statement but now to get it to delete!
#everyone:
ok maybe thinking out loud or following my steps worked but the code works, i know its very messy and it needs fine tuning. i'd like to thank everyone for their help and feedback. i'm liking this and you'll probably see me alot more often with nubby questions and messy codes with no escapes :(
First of all, you have SQL injection vulnerability in your script. Anyone can add some string that will be attached to your query, possibly altering it in a way that can make almost anything with the data from your database.
Escape your values with one of anti-SQL-injection methods. Read more for example on php.net/manual/en/function.mysql-query.php
To the point...
Your deletion code will be executed only if you invoke URL with two params (remove and delete set to y. That means your URL should look similar to something.php?delete=y&remove=y. Maybe you just did not spot it.
Please give details about any errors that occured and tell me whether the above mentioned solution helped.
mysql_fetch_array() returns an array
your while statement acts as an if, and does not iterate thru the array returned as you think it does
you need something like
$all_rows = mysql_fetch_array($result);
foreach ($all_rows as $row) {
$sql = "delete from table where id = " . $row['id'];
}
It looks to me like you're mixing two forms together here: you're wanting to see if you went to the delete row form (the first few lines), and you're trying to present the delete row form (the while loop.) I would break these two things apart. Have a page that simply displays your forms for row deletes, and another page that processes those requests. And another page that brings you to the delete rows page.
For now, just echo all the values you're expecting to receive in $_GET[] and see if they are what you expect them to be.
You have a lot of problems in that script alone, so just to make things easier (considering you uploaded a pic), put an
echo $sqlrem;
in your second if statement, see if the query is displayed. If not, it means it doesn't even get to that part of code, if it gets displayed, copy it and run it in phpmyadmin. That should output a more coherent error message. Tell us what that is and we'll work it through.
I also noticed that your DELETE SQL query might have an issue. If your $pgd' id is a integer, you shouldn't include the ' single quote, that is for string only.
**Correction**
$sqlrem = "DELETE FROM content WHERE id = " . controw1['id'];
EDIT
Anyway, just to help out everyone, I typed out his code for easier viewing.
I think his error is $rowcont1['Tilel'] --> that might caused PHP to have an error because that column doesn't exist. I assumed, it should be `Title' causing an typo error.
if(_$GET['delete'] == "y") {
$sqlcont1 = "SELECT * FROM content where id ='" . $_GET['id'] . "'";
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while ($rowcont1 = mysql_fetch_array($resultcont1)) {
echo '<form class = "niceforms" action = "?pg=' .$pgd . '&delete=y&remove=y">';
echo '<h1>' . $rowcont1['Title'] . '<h1>'; // <-- error here
echo '<p>' . $rowcont1['Content'] . '</p>';
echo '<input type = "submit" value = "Delete article">';
echo '</form>';
}
if ($_GET['remove'] == "y"){
$sqlrem = "DELETE FROM content WHERE id = " . $rowcont1['id'];
mysql_query ($sqlrem);
}
}

Display database contents? PHP / MySQL

So I have a chatroom type of database where the text that a user inserts gets stored into a databse as their username in one field and their message in the other. I want to have my page output the database info, so that people can see each others messages.
How do I do this?
Also, is it possible to make a for loop that checks to see if the database has been updated with a new message, therefore it reloads the page? (Then the page outputs the database info again to update everyones messages)
Please help.. i'm so confused.
Take a look at MySQL functions in PHP manual. You need to connect to the server/database and run a select query to get the data from tables.
As for the loop: you could use JavaScript setInterval function and combine that with AJAX call to periodically poll for new records.
Like the others have said, you will want to connect to your database and then query the table that you have the data in.
while($row = mysql_fetch_assoc($results))
{
echo $row['username'] . " said: " . $row['message'] . "<br />";
}
I use mysql_fetch_assoc() instead of mysql_fetch_array() since the arrays are associative arrays (not indexed by integers, but rather by names (associations))
As for displaying the update on the page dynamically, that involves AJAX. Basically what that means is that your page will call out to a background script to get the new records from the database. This would require a new field in your 'messages' table, something like 'msg_delivered' that you could set to '1' when it has been fetched.
You should check out this if you are interested in making an AJAX chat client: http://htmltimes.com/javascript-chat-client-in-jquery.php
To read anything from a mysql database you would use the mysql_connect() and the mysql_query() functions
eg:
$link = mysql_connect('localhost', 'root', '');
$results = mysql_query('select * from messages');
while($row = mysql_fetch_array($results))
{
echo $row['username'] . ': ' . $row['message'].'<br />';
}
To display new messages the best way would be to use AJAX and poll the database from there, either loading a separate page into a DIV or getting XML back and placing into HTML tags. I would recommend using JQuery for these kinds of tasks. Check http://www.sitepoint.com/article/ajax-jquery/ for an example.

Categories