INSERT mysql_num_rows as a variable - php

I am creating a CMS in in which when you ADD NEW PAGE, a display_order will automatically grab the next highest number according to the number of rows already present. Here's what I currently have:
<?php
if(isset($_POST['updateContent'])){
require ("connection.php");
$sql = "SELECT * FROM pages";
$result = $conn->query($sql) or die(mysqli_error());
$content = $_POST['content'];
$title = $_POST['title'];
$id = $_POST['id'];
$order = mysqli_num_rows($result);
if (empty($id)){
/** ADD NEW SLIDE*/
$sql = "INSERT INTO pages (title, content, display_order, visible) VALUES ('".$title."', '".$content.", '".$order.", 0)";
}else{
/** UPDATE SLIDE*/
$sql = "UPDATE pages SET content = '".$content."', title = '".$title."' WHERE id = '".$id."'";
}
if ($result){
header("Location: admin.php");
}
}
?>
What this code is doing is taking the HTML form that I'm using in a page called edit.php and determining if it is new page or simply a page that is being updated. The error that I am getting is that NOTHING is posting to the database at all. If I remove the $sql, $result and $order lines.. the script works fine, but the display_order variable will not be set to the next highest number.

There is an error in your query:
INSERT INTO pages (title, content, display_order, visible)
VALUES ('".$title."', '".$content.", '".$order.", 0)";
^-- here
Should be:
INSERT INTO pages (title, content, display_order, visible)
VALUES ('".$title."', '".$content."', ".$order.", 0)";
^-- quote goes here
Also, using mysqli doesn't magically protect you from SQL-insertion. Escape dat input!

The common way to solve the situation is to use AUTO_INCREMENT field in pages table.
Sequentially insert and then ask for LAST_INSERT_ID
php way: http://php.net/manual/en/function.mysql-insert-id.php
native mysql way: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

Related

Assign the ID created to another column in the Database for URL

I have created a form where it inserts data into the databased.
Name of Link, URL of Link, Title of the page and the content.
However, I want to be able to assign the new ID that gets auto created in both the tables (nav and pages), and put it in url column in the nav table.
Is that possible?
My current insert into database code is below which works fine except for the mentioned question.
<?php if(isset($_POST['Insert'])){
require ("database/connect.php");
$navname = $_POST['navname'];
$url = $_POST['url'];
$title = $_POST['title'];
$pagename = $_POST['pagename'];
$content = $_POST['content'];
$sql1 = "INSERT INTO nav (name, url, title) VALUES('{$navname}','{$url}','{$title}')";
$sql2 = "INSERT INTO pages (name, content) VALUES('{$pagename}','{$content}')";
$result = $db->query($sql1) or die(mysqli_error());
$result = $db->query($sql2) or die(mysqli_error());
if($result){
header("Location: newpage.php?message=1");
}
}?>
$sql1 = "INSERT INTO nav (name, url, title) VALUES('{$navname}','{$url}','{$title}')";
$sql2 = "INSERT INTO pages (name, content) VALUES('{$pagename}','{$content}')";
$result1 = $db->query($sql1) or die(mysqli_error());
$id1 = $db->insert_id;
$result2 = $db->query($sql2) or die(mysqli_error());
$id2 = $db->insert_id;
// do something to make your url, call it $url, run another mysqli query to update nav.url where id = $id1

Fetching last inserted ID and using it as a parameter with PHP/MySQL

I'm very new to PHP, trying to figure things out.
I have the following php code:
$read_more = '[read more]';
$sql = "INSERT INTO database (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
The code is returning "http://www.example.com/index.php?id=0". Note that the "id" parameter is returning "0". My goal is to make it return the latest ID from the database, which is set to auto increment.
I've tried many things but nothing worked for me so far. Thanks!
EDIT: After hours of trial and error, this is how I was able to solve this problem:
//After connecting to the database
$sql = "INSERT INTO table (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
$result = mysqli_query($conn, $sql);
$id = mysqli_insert_id($conn);
Now the latest id is saved into a variable that I can use.
Try something like this instead. Check the documentation here.
// insert a datarow, primary key is auto_increment
// value is a unique key
$query = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query );
echo 'LAST_INSERT_ID: ',
mysql_query( "SELECT LAST_INSERT_ID()" ),
'<br>mysql_insert_id: ',
mysql_insert_id();

show row data from a specific ID

I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);

How do I reference the row I had just inserted into a MySQL table?

I have this function in a Code Igniter model that creates a new "video."
// Creates a new video.
public function newVideo($title, $description) {
$this->db->query("INSERT INTO videos VALUES (NULL, '$title', '$description')");
return // id of this new row
}
How do I obtain the ID of this new row in my MySQL table? I could get the last row and add 1, but there could be concurrency bugs I believe.
Very simple answer doesn't really need more than 30 chars does it?
$this->db->insert_id();
maybe you need something like this
$this->db->insert_id();
Try something like that :
$lastID = -1; //That's where it'll be stored
$query = "SELECT LAST_INSERT_ID()";
$result = mysql_query($query);
if ($result)
{
$row = mysql_fetch_row($result);
$lastID = $row[0];
}
Code for an insert is:
$sql = "INSERT INTO videos (title) VALUES(NULL, '$title', '$description')";
$this->db->query($sql);
More information on queries available at: http://codeigniter.com/user_guide/database/queries.html
Another workaround is that you can have a look into videos table in your database, and make you video id as autonumber, this will automatically generate an id for your video and then you can try this:
//on your model
$sql = "INSERT INTO videos (title,description) VALUES('$title', '$description')";
$this->db->query($sql);
//retrieve new video id
$this->db->insert_id()

How do I replace record if one variable has changed?

I am taking a calendar feed with a PHP file and I need to compare it to my database. If the $lastEdited variable is different than what is in the database, I need to change the record. I'm really new to SQL, so I'm not sure what to do. I just have Date_Edited set as a VARCHAR so I just need to compare the strings. I have this:
$query = "SELECT * FROM myTable WHERE Event_ID='$id'";
$result = mysql_query($query);
if (!mysql_num_rows($result)) {
mysql_query("INSERT INTO myTable (Event_ID, Date_added, Date_edited, Title)
VALUES ('$id', '$dateAdded', '$lastEdited', '$title')");
}
How do I compare $lastEdited to Date_edited and change the row if they are different?
you need to do something like
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($lastEdited != $row['Date_added']){
# run update query
mysql_query("update myTable set
// here insert all update fields you need like
Date_added = '$dateAdded', Date_edited = '$lastEdited' , Title = '$title'
WHERE Event_ID='$id' ");
}
You probably want to use the UPDATE statement.

Categories